作者 yangfu

Merge branch 'test'

正在显示 81 个修改的文件 包含 3830 行增加167 行删除

要显示太多修改。

为保证性能只显示 81 of 81+ 个文件。

select count(*) from manufacture.device_running_record where device_running_record_id <=2000000
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
--1.备份设备运行数据-按数量
-- 备份数据 2000000
select * into table manufacture.device_running_record_0_2000
from manufacture.device_running_record
where device_running_record_id <=2000000
-- 删除数据
delete from manufacture.device_running_record where device_running_record_id <=2000000;
-- 重建索引
reindex table manufacture.device_running_record;
--2.备份设备采集数据-按时间
-- 备份数据 2000000
select * into table manufacture.device_collections_history
from manufacture.device_collections
where created_at <'2022-6-01 16:00:00'
-- 删除数据
delete from manufacture.device_collections where created_at <'2022-6-01 16:00:00';
-- 重建索引
reindex table manufacture.device_collections;
--3.查看备份情况
select count(*) from manufacture.device_running_record_0_2000
select count(*) from manufacture.device_collections_history
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
\ No newline at end of file
... ...
delete FROM "dictionarys" where dictionary_id in (3812266576427090944);
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972873532463383552, 'ACM-001', '天联共创-生产制造-物料属性', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "外购"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "自制"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "委外"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972875981165167616, 'ACM-002', '天联共创-生产制造-物料管理-物料类别', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "原材料"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "半成品"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "成品"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972882719129994240, 'ACM-003', '天联共创-生产制造-单位', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "千克"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "个"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "包"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "箱"}, {"sort": 5, "isShow": 1, "itemCode": "5", "itemLabel": "", "itemValue": "片"}, {"sort": 6, "isShow": 1, "itemCode": "6", "itemLabel": "", "itemValue": "套"}, {"sort": 7, "isShow": 1, "itemCode": "7", "itemLabel": "", "itemValue": "份"}, {"sort": 8, "isShow": 1, "itemCode": "8", "itemLabel": "", "itemValue": "台"}, {"sort": 9, "isShow": 1, "itemCode": "9", "itemLabel": "", "itemValue": "米"}, {"sort": 10, "isShow": 1, "itemCode": "10", "itemLabel": "", "itemValue": "升"}, {"sort": 11, "isShow": 1, "itemCode": "11", "itemLabel": "", "itemValue": "辆"}, {"sort": 12, "isShow": 1, "itemCode": "12", "itemLabel": "", "itemValue": "秒"}, {"sort": 13, "isShow": 1, "itemCode": "13", "itemLabel": "", "itemValue": "栋"}, {"sort": 14, "isShow": 1, "itemCode": "14", "itemLabel": "", "itemValue": "袋"}, {"sort": 15, "isShow": 1, "itemCode": "15", "itemLabel": "", "itemValue": "kg"}, {"sort": 16, "isShow": 1, "itemCode": "16", "itemLabel": "", "itemValue": "串"}, {"sort": 17, "isShow": 1, "itemCode": "17", "itemLabel": "", "itemValue": "件"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3978995238135399424, 'ACM-004', '天联共创-生产制造-单位换算-物料类别', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "南瓜饼串"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "包装袋(空)"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "包装袋(件数)"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "装箱(件数)"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3812266576427090944, 'XTZD-003', '生产制造-单位', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "个"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "袋"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "kg"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "串"}, {"sort": 5, "isShow": 1, "itemCode": "5", "itemLabel": "", "itemValue": "箱"}, {"sort": 6, "isShow": 1, "itemCode": "6", "itemLabel": "", "itemValue": "件"}]');
... ...
-- 表product_material_group 增加唯一索引 idx_unq_product_material_group_company_id_org_id_material_group_number
create UNIQUE INDEX idx_unq_product_material_group_company_id_org_id_material_group_number on manufacture.product_material_group using btree(company_id,org_id,material_group_number,deleted_at);
-- 表product_material 增加唯一索引 idx_unq_product_material_company_id_material_number
create UNIQUE INDEX idx_unq_product_material_company_id_material_number on manufacture.product_material using btree(company_id,material_number,deleted_at);
-- 菜单脚本
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (269, 175, '物料信息', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL', '', 'menu', 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211608_CH2pTwT56j6TXfRdYhGxBfKRNFfpzWKE.png', 3, '', '7', '38,174,175', 1, 0, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (270, 269, '删除', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_DEL', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (271, 269, '新增', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_ADD', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (272, 269, '编辑', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_EDIT', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (273, 269, '查看', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_VIEW', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '产品管理', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_PRODUCT', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211429_wMrRfxYMyhBySwWkysZaXBbfDapSppBs.png', "sort" = 4, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 186;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '设备档案', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_DEVICE', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211439_WaAKb65X7wX2zjsMExDyy56XRnTRAmPD.png', "sort" = 5, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 193;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '工厂日历', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_CALENDAR', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211448_GBY3HhbPpNnNpnGPWGE6wETW6F6THfr4.png', "sort" = 6, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 199;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '单位换算', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_UNIT-CONVERSION', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211456_cKxKHHXHQnM3e7RZNxdkZ3n7ZXJjdKba.png', "sort" = 7, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 203;
\ No newline at end of file
... ...
... ... @@ -125,4 +125,6 @@ spec:
- name: MQTT_HOST
value: "47.97.5.102"
- name: MQTT_PORT
value: "6000"
\ No newline at end of file
value: "6000"
- name: MQTT_UP
value: "false"
\ No newline at end of file
... ...
... ... @@ -125,4 +125,6 @@ spec:
- name: MQTT_HOST
value: "47.97.5.102"
- name: MQTT_PORT
value: "6000"
\ No newline at end of file
value: "6000"
- name: MQTT_UP
value: "false"
\ No newline at end of file
... ...
... ... @@ -3,6 +3,7 @@ package main
import (
"fmt"
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
... ... @@ -10,7 +11,6 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
... ... @@ -29,8 +29,9 @@ func main() {
redis.InitRedis()
log.Logger.Info("server start ....")
log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG))
go mqtt.Start(log.Logger)
if constant.MQTT_UP {
go mqtt.Start(log.Logger)
}
go task.Run()
cron := crontab.NewCrontabService(nil)
cron.StartCrontabTask()
... ...
... ... @@ -37,6 +37,9 @@ func (crontabService *CrontabService) initTask() {
})
task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud)
autoInitWorkshopProductRecord := task.NewTask("AutoInitWorkshopProductRecord", "0 0 */4 * * *", AutoInitWorkshopProductRecord)
task.AddTask("AutoInitWorkshopProductRecord", autoInitWorkshopProductRecord)
autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord)
task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord)
... ... @@ -60,6 +63,12 @@ func (crontabService *CrontabService) initTask() {
syncProductPlan := task.NewTask("定时同步车间计划", "0 5 * * * *", SyncProductPlan)
task.AddTask("SyncProductPlan", syncProductPlan)
syncMaterialGroup := task.NewTask("定时同步物料分组", "0 0 0/2 * * *", SyncMaterialGroup)
task.AddTask("syncMaterialGroup", syncMaterialGroup)
syncMaterial := task.NewTask("定时同步物料", "0 0 0/2 * * *", SyncMaterial)
task.AddTask("syncMaterial", syncMaterial)
}
func (crontabService *CrontabService) StartCrontabTask() {
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
// AutoInitWorkshopProductRecord 自动初始化车间生产记录
func AutoInitWorkshopProductRecord(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "自动初始化车间生产记录"})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【自动初始化车间生产记录】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【自动初始化车间生产记录】 启动")
_, workshop, err := factory.FastPgWorkshop(transactionContext, constant.MANUFACTURE_DEFAULT_WORKSHOPID)
if err != nil {
return err
}
productPlanDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(transactionContext.(*pg.TransactionContext))
productPlans, err := productPlanDispatchRecordDao.ProductPlans(constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
utils.GetZeroTimeWithLocal(time.Now(), time.UTC), "")
if err != nil {
return err
}
if len(productPlans) == 0 {
log.Logger.Debug("【自动初始化车间生产记录】 当天执行计划为空")
return nil
}
workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(transactionContext.(*pg.TransactionContext))
workshopProductRecordRepository, _ := repository.NewWorkshopProductRecordRepository(transactionContext.(*pg.TransactionContext))
lines := workshop.GetProductLines(domain.NotDeleted)
for _, line := range lines {
for _, section := range line.ProductSections {
if !(section.SectionName == domain.ProductSection1 || section.SectionName == domain.ProductSection2) {
continue
}
if section.Removed == domain.Deleted {
continue
}
workstation := domain.NewWorkStation(workshop, line, section)
cid := constant.MANUFACTURE_DEFAULT_COMPANYID
oid := constant.MANUFACTURE_DEFAULT_ORGID
for _, plan := range productPlans {
var workshopProductRecord *domain.WorkshopProductRecord
workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, workstation.WorkStationId, plan.ProductPlanId, time.Now())
if err == domain.ErrorNotFound {
workshopProductRecord = domainService.NewWorkshopProductRecord(&domain.ProductRecord{
CompanyId: constant.MANUFACTURE_DEFAULT_COMPANYID,
OrgId: constant.MANUFACTURE_DEFAULT_ORGID,
WorkStation: workstation,
CreatedAt: time.Now(),
ProductRecordInfo: &domain.ProductRecordInfo{
ProductPlanId: plan.ProductPlanId,
PlanProductName: plan.PlanProductName,
BatchNumber: plan.BatchNumber,
},
}, plan)
if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
return err
}
log.Logger.Debug(fmt.Sprintf("【自动初始化车间生产记录】 工位:%v(%v) 初始产能:%v kg 日期:%v ID:%v",
workshopProductRecord.WorkStation.WorkStationId, workshopProductRecord.WorkStation.SectionName,
workshopProductRecord.ProductWeigh, workshopProductRecord.ProductRecordInfo.ProductDate, workshopProductRecord.WorkshopProductRecordId))
continue
}
if err != nil {
log.Logger.Error(err.Error())
return nil
}
}
}
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"runtime/debug"
"time"
)
// SyncMaterial 定时同步物料
func SyncMaterial(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料", "stack": string(debug.Stack())})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时同步物料】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
var pullType string = ""
if val := ctx.Value("pullType"); val != nil {
pullType = val.(string)
}
log.Logger.Debug("【定时同步物料】 启动")
pullK3CloudService := syncdata.PullDataK3CloudService{}
if err := pullK3CloudService.SyncDataMaterial(transactionContext.(*pg.TransactionContext), pullType, time.Time{}); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料"})
return nil
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"runtime/debug"
)
// SyncMaterialGroup 定时同步物料分组
func SyncMaterialGroup(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料分组", "stack": string(debug.Stack())})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时同步物料分组】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【定时同步物料分组】 启动")
pullK3CloudService := syncdata.PullDataK3CloudService{}
if err := pullK3CloudService.SyncDataMaterialGroup(transactionContext.(*pg.TransactionContext)); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料分组"})
return nil
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
... ... @@ -413,6 +413,58 @@ func FastPgDeviceDailyRunningRecord(transactionContext application.TransactionCo
return rep, mod, err
}
// FastProductMaterialGroup 快速返回物料
//
// transactionContext 事务
// id 对象唯一标识
func FastProductMaterialGroup(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialGroupRepository, *domain.ProductMaterialGroup, error) {
var rep domain.ProductMaterialGroupRepository
var mod *domain.ProductMaterialGroup
var err error
if value, err := CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if id > 0 {
if mod, err = rep.FindOne(map[string]interface{}{"productMaterialGroupId": id}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
return rep, mod, err
}
// FastProductMaterialGroup 快速返回物料
//
// transactionContext 事务
// id 对象唯一标识
func FastProductMaterial(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialRepository, *domain.ProductMaterial, error) {
var rep domain.ProductMaterialRepository
var mod *domain.ProductMaterial
var err error
if value, err := CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if id > 0 {
if mod, err = rep.FindOne(map[string]interface{}{"productMaterialId": id}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
return rep, mod, err
}
/***** 2.配置 *****/
type FastOptions struct {
... ...
... ... @@ -141,3 +141,19 @@ func CreateDeviceDailyRunningRecordRepository(options map[string]interface{}) (d
}
return repository.NewDeviceDailyRunningRecordRepository(transactionContext)
}
func CreateProductMaterialGroupRepository(options map[string]interface{}) (domain.ProductMaterialGroupRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewProductMaterialGroupRepository(transactionContext)
}
func CreateProductMaterialRepository(options map[string]interface{}) (domain.ProductMaterialRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewProductMaterialRepository(transactionContext)
}
... ...
... ... @@ -14,19 +14,15 @@ type CreateProductCommand struct {
// 组织ID
OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
// 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode" valid:"Required"`
// 产品名称
ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
// ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 数量(保留两位小数)
//Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"`
// ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// Unit string `cname:"单位" json:"unit" valid:"Required"`
// 单份重量(原材料)
UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
// 重量
//Weight float64 `cname:"重量" json:"weight" valid:"Required"`
}
func (createProductCommand *CreateProductCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -12,19 +12,15 @@ type UpdateProductCommand struct {
// 产品ID
ProductId int `cname:"产品ID" json:"productId" valid:"Required"`
// 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
//ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
// 产品名称
ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
ProductName string `cname:"产品名称" json:"productName" `
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 数量(保留两位小数)
//Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"`
ProductCategory string `cname:"产品类别" json:"productCategory"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
Unit string `cname:"单位" json:"unit"`
// 单份重量(原材料)
UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
// 重量
//Weight float64 `cname:"重量" json:"weight" valid:"Required"`
}
func (updateProductCommand *UpdateProductCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -14,7 +14,6 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
// 产品服务
... ... @@ -22,7 +21,7 @@ type ProductService struct {
}
// 创建产品服务
func (productService *ProductService) CreateProduct(createProductCommand *command.CreateProductCommand) (interface{}, error) {
func (productService *ProductService) CreateProduct(opt *domain.OperateInfo, createProductCommand *command.CreateProductCommand) (interface{}, error) {
if err := createProductCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
... ... @@ -37,50 +36,23 @@ func (productService *ProductService) CreateProduct(createProductCommand *comman
transactionContext.RollbackTransaction()
}()
if len(createProductCommand.ProductCode) == 0 {
generator := redis.NewProductCodeCache(createProductCommand.CompanyId)
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
createProductCommand.ProductCode = code
batchAddProductService, _ := domainService.NewPGBatchAddProductService(transactionContext.(*pgTransaction.TransactionContext))
item := &domain.ImportProductItem{
ProductCode: createProductCommand.ProductCode,
UnitWeight: utils.AssertString(createProductCommand.UnitWeight),
}
var userService = domainService.NewUserService()
var org *domain.Org
org, err = userService.Organization(createProductCommand.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
if _, err = batchAddProductService.BatchAddProduct(opt, []*domain.ImportProductItem{
item,
}, false); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
newProduct := &domain.Product{
CompanyId: createProductCommand.CompanyId,
OrgId: createProductCommand.OrgId,
ProductCode: createProductCommand.ProductCode,
ProductName: createProductCommand.ProductName,
ProductCategory: createProductCommand.ProductCategory,
ProductSpec: &domain.UnitQuantity{
Unit: createProductCommand.Unit,
UnitWeight: createProductCommand.UnitWeight,
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
productRepository, _, _ := factory.FastPgProduct(transactionContext, 0)
if item, err := productRepository.FindOne(map[string]interface{}{"companyId": createProductCommand.CompanyId, "productCode": createProductCommand.ProductCode}); err == nil && item != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交")
if len(item.FailReason) > 0 {
return nil, application.ThrowError(application.TRANSACTION_ERROR, item.FailReason)
}
if product, err := productRepository.Save(newProduct); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return product, nil
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 返回产品服务
... ... @@ -242,7 +214,7 @@ func (productService *ProductService) BatchRemoveProduct(cmd *command.BatchRemov
}
// 更新产品服务
func (productService *ProductService) UpdateProduct(updateProductCommand *command.UpdateProductCommand) (interface{}, error) {
func (productService *ProductService) UpdateProduct(opt *domain.OperateInfo, updateProductCommand *command.UpdateProductCommand) (interface{}, error) {
if err := updateProductCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
... ... @@ -260,19 +232,11 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(updateProductCommand.ProductCode) == 0 {
generator := redis.NewProductCodeCache(product.CompanyId)
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
updateProductCommand.ProductCode = code
}
if updateProductCommand.ProductCode != product.ProductCode {
if item, err := productRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "productCode": updateProductCommand.ProductCode}); err == nil && item != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交")
}
var material *domain.ProductMaterial
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
if material, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "materialNumber": product.ProductCode}); err != nil || material == nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "物料不存在")
}
var userService = domainService.NewUserService()
... ... @@ -281,8 +245,13 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
updateProductCommand.ProductName = material.MaterialName
updateProductCommand.Unit = material.ProductMaterialExt.Unit
updateProductCommand.ProductCategory = material.MaterialCategory.Category
data := tool_funs.SimpleStructToMap(updateProductCommand)
data["orgName"] = org.OrgName
if err := product.Update(data); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type BatchRemoveProductMaterialCommand struct {
// 物料ID们
ProductMaterialIds []int `cname:"物料ID" json:"productMaterialIds" valid:"Required"`
}
func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchRemoveProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchRemoveProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"reflect"
"regexp"
"strings"
)
type CreateProductMaterialCommand struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId"`
// 组织ID
OrgId int `cname:"组织ID" json:"orgId"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
// 物料编码
MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
// 物料属性
MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
// 规格
Specification string `cname:"规格" json:"specification" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// 保质期 单位:天
ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
// 备注
Remark string `cname:"备注" json:"remark"`
}
func (createProductMaterialCommand *CreateProductMaterialCommand) Valid(validation *validation.Validation) {
createProductMaterialCommand.MaterialNumber = strings.ToUpper(createProductMaterialCommand.MaterialNumber)
match, err := regexp.MatchString("^[A-Z0-9]+$", createProductMaterialCommand.MaterialNumber)
if !match {
validation.Error("物料编码只允许数字加大写字母组合")
return
}
if err != nil {
validation.Error(err.Error())
return
}
if len([]rune(createProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (createProductMaterialCommand *CreateProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveProductMaterialCommand struct {
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
}
func (removeProductMaterialCommand *RemoveProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeProductMaterialCommand *RemoveProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateProductMaterialCommand struct {
// 企业id
//CompanyId int `cname:"企业id" json:"companyId"`
// 组织ID
//OrgId int `cname:"组织ID" json:"orgId"`
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
//// 物料编码
//MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
// 物料属性
MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
// 规格
Specification string `cname:"规格" json:"specification" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// 保质期 单位:天
ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
// 备注
Remark string `cname:"备注" json:"remark"`
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) Valid(validation *validation.Validation) {
if len([]rune(updateProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
type DtoMaterial struct {
ProductMaterialId int `json:"productMaterialId"` // 物料ID
MaterialNumber string `json:"materialNumber"` //物料编码
MaterialName string `json:"materialName"` //物料名称
Specification string `json:"specification"` //规格型号
MaterialCategory string `json:"materialCategory"` //物料类别
Unit string `json:"unit"` //单位
MaterialAttribute string `json:"materialAttribute"` //物料属性
ProductMaterialGroupId int `json:"productMaterialGroupId"` //物料分组 string/string/string
ExpiredDay int `json:"expiredDay"` //保质期
Remark string `json:"remark"` //备注
ProductMaterialGroups []int `json:"productMaterialGroups"`
}
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
func DtoProductMaterial(productMaterialModel *domain.ProductMaterial) *DtoMaterial {
return &DtoMaterial{
ProductMaterialId: productMaterialModel.ProductMaterialId,
ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
MaterialNumber: productMaterialModel.MaterialNumber,
MaterialName: productMaterialModel.MaterialName,
MaterialAttribute: productMaterialModel.MaterialAttribute.Attribute,
MaterialCategory: productMaterialModel.MaterialCategory.Category,
Specification: productMaterialModel.ProductMaterialExt.Specification,
Remark: productMaterialModel.ProductMaterialExt.Remark,
Unit: productMaterialModel.ProductMaterialExt.Unit,
ExpiredDay: productMaterialModel.ProductMaterialExt.ExpiredDay,
}
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetProductMaterialQuery struct {
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
}
func (getProductMaterialQuery *GetProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getProductMaterialQuery *GetProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListProductMaterialQuery struct {
PageNumber int64 `json:"pageNumber"`
PageSize int64 `json:"pageSize"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
// 物料分组ID数组
ProductMaterialGroupIds []int
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory"`
CompanyId int
}
func (listProductMaterialQuery *ListProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listProductMaterialQuery *ListProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SearchProductMaterialQuery struct {
PageNumber int64 `json:"pageNumber"`
PageSize int64 `json:"pageSize"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
// 物料分组ID数组
ProductMaterialGroupIds []int
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory"`
CompanyId int
}
func (listProductMaterialQuery *SearchProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listProductMaterialQuery *SearchProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"time"
)
// 生产物料服务
type ProductMaterialService struct {
}
// 创建生产物料服务
func (productMaterialService *ProductMaterialService) CreateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.CreateProductMaterialCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newProductMaterial := &domain.ProductMaterial{
CompanyId: cmd.CompanyId,
OrgId: cmd.OrgId,
ProductMaterialGroupId: cmd.ProductMaterialGroupId,
MaterialNumber: cmd.MaterialNumber,
MaterialName: cmd.MaterialName,
MaterialAttribute: &domain.MaterialAttribute{Attribute: cmd.MaterialAttribute},
MaterialCategory: &domain.MaterialCategory{Category: cmd.MaterialCategory},
ProductMaterialExt: &domain.MaterialExt{
Specification: cmd.Specification,
Unit: cmd.Unit,
ExpiredDay: cmd.ExpiredDay,
Remark: cmd.Remark,
},
}
//var productMaterial *domain.ProductMaterial
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if _, err := materialService.AddMaterial(operateInfo, newProductMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 返回生产物料服务单个
func (productMaterialService *ProductMaterialService) GetProductMaterial(operateInfo *domain.OperateInfo, getProductMaterialQuery *query.GetProductMaterialQuery) (interface{}, error) {
if err := getProductMaterialQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"productMaterialId": getProductMaterialQuery.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialQuery.ProductMaterialId)))
} else {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
productMaterialGroupIdNames, _, err := materialService.AllMaterialGroupParentByBacktracking(operateInfo, productMaterial.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(productMaterialGroupIdNames) == 0 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var productMaterialGroups []int
for _, productMaterialGroupIdName := range productMaterialGroupIdNames {
productMaterialGroups = append(productMaterialGroups, productMaterialGroupIdName.ProductMaterialGroupId)
}
one := dto.DtoProductMaterial(productMaterial)
one.ProductMaterialGroups = productMaterialGroups
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return one, nil
}
}
// 返回生产物料服务列表,未用
func (productMaterialService *ProductMaterialService) ListProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.ListProductMaterialQuery) (interface{}, error) {
if err := listProductMaterialQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
var results []*dto.DtoMaterial
if listProductMaterialQuery.ProductMaterialGroupId != 0 {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
}
listProductMaterialQuery.CompanyId = operateInfo.CompanyId
if count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
for _, productMaterial := range productMaterials {
results = append(results, dto.DtoProductMaterial(productMaterial))
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"productMaterials": results,
}, nil
}
}
// 返回生产物料服务列表
func (productMaterialService *ProductMaterialService) SearchProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.SearchProductMaterialQuery) (int64, []*dto.DtoMaterial, error) {
if err := listProductMaterialQuery.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
results := make([]*dto.DtoMaterial, 0)
if listProductMaterialQuery.ProductMaterialGroupId != 0 {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
}
listProductMaterialQuery.CompanyId = operateInfo.CompanyId
count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
for _, productMaterial := range productMaterials {
results = append(results, dto.DtoProductMaterial(productMaterial))
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, results, err
}
// 移除生产物料服务
func (productMaterialService *ProductMaterialService) RemoveProductMaterial(operateInfo *domain.OperateInfo, removeProductMaterialCommand *command.RemoveProductMaterialCommand) (interface{}, error) {
if err := removeProductMaterialCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": removeProductMaterialCommand.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeProductMaterialCommand.ProductMaterialId)))
}
if productMaterial, err := productMaterialRepository.Remove(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterial, nil
}
}
// 更新生产物料服务
func (productMaterialService *ProductMaterialService) UpdateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": cmd.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
productMaterial.ProductMaterialGroupId = cmd.ProductMaterialGroupId
productMaterial.MaterialName = cmd.MaterialName
productMaterial.MaterialAttribute.Attribute = cmd.MaterialAttribute
productMaterial.MaterialCategory.Category = cmd.MaterialCategory
productMaterial.ProductMaterialExt = &domain.MaterialExt{
Specification: cmd.Specification,
Unit: cmd.Unit,
ExpiredDay: cmd.ExpiredDay,
Remark: cmd.Remark,
}
productMaterial.UpdatedAt = time.Now()
if _, err := productMaterialRepository.Save(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 批量移除生产物料服务
func (productMaterialService *ProductMaterialService) BatchRemoveProductMaterial(operateInfo *domain.OperateInfo, batchRemoveProductMaterialCommand *command.BatchRemoveProductMaterialCommand) (interface{}, error) {
if err := batchRemoveProductMaterialCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
for i := range batchRemoveProductMaterialCommand.ProductMaterialIds {
ProductMaterialId := batchRemoveProductMaterialCommand.ProductMaterialIds[i]
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(ProductMaterialId)))
}
if _, err := productMaterialRepository.Remove(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewProductMaterialService(options map[string]interface{}) *ProductMaterialService {
newProductMaterialService := &ProductMaterialService{}
return newProductMaterialService
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CreateProductMaterialGroupCommand struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
// 组织ID
OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
// 父级ID
Pid int `cname:"父级ID" json:"pid"`
// 物料分组名称
MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
// 物料分组编码
MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber,omitempty"`
}
func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveProductMaterialGroupCommand struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
}
func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateProductMaterialGroupCommand struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
// 物料分组名称
MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
// 物料分组编码
MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber"`
}
func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type MaterialGroupDto struct {
// 物料分组ID
ProductMaterialGroupId int `json:"id"`
// 企业id
//CompanyId int `json:"companyId"`
// 组织ID
//OrgId int `json:"orgId"`
// 父级ID
Pid int `json:"pid"`
// 路径 (不使用,如果父级改变的话,子级的Path要做更新)
//Path string `json:"path"`
// 物料分组名称
MaterialGroupName string `json:"materialGroupName"`
// 物料分组编码
MaterialGroupNumber string `json:"materialGroupNumber"`
}
func (d *MaterialGroupDto) LoadDto(m *domain.ProductMaterialGroup, orgId int) *MaterialGroupDto {
d.ProductMaterialGroupId = m.ProductMaterialGroupId
d.Pid = m.Pid
d.MaterialGroupName = m.MaterialGroupName
d.MaterialGroupNumber = m.MaterialGroupNumber
return d
}
func (productMaterialGroup *MaterialGroupDto) PID() string {
return fmt.Sprintf("%d", productMaterialGroup.Pid)
}
func (productMaterialGroup *MaterialGroupDto) ID() string {
return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
}
type MaterialGroupDtos []*MaterialGroupDto
func (tree MaterialGroupDtos) Len() int {
return len(tree)
}
func (tree MaterialGroupDtos) Less(i, j int) bool {
if tree[i].Pid < tree[j].Pid {
return true
}
if tree[i].Pid == tree[j].Pid {
return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
}
return false
}
func (tree MaterialGroupDtos) Swap(i, j int) {
tree[i], tree[j] = tree[j], tree[i]
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetProductMaterialGroupQuery struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
}
func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) Valid(validation *validation.Validation) {
}
func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getProductMaterialGroupQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getProductMaterialGroupQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListProductMaterialGroupQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
// 查询限制
Limit int `cname:"查询限制" json:"limit" valid:"Required"`
}
func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) Valid(validation *validation.Validation) {
}
func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialGroupQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialGroupQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SearchProductMaterialGroupQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
Limit int `cname:"查询限制" json:"limit"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 当前登录的组织
//OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
// 匹配多个组织
//InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty" valid:"Required"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
}
func (cmd *SearchProductMaterialGroupQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
}
func (cmd *SearchProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SelectorProductMaterialGroupQuery struct {
// 查询偏离量
//Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
//Limit int `cname:"查询限制" json:"limit"`
// options 'tree' 'list' default tree
Style string `json:"style"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 页码
//PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
//PageSize int `cname:"页数" json:"pageSize,omitempty"`
}
func (cmd *SelectorProductMaterialGroupQuery) Valid(validation *validation.Validation) {
//cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
cmd.Style = "tree"
}
func (cmd *SelectorProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"sort"
)
// 物料分组服务
type ProductMaterialGroupService struct {
}
// 创建物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) CreateProductMaterialGroup(operateInfo *domain.OperateInfo, createProductMaterialGroupCommand *command.CreateProductMaterialGroupCommand) (interface{}, error) {
if err := createProductMaterialGroupCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newProductMaterialGroup := &domain.ProductMaterialGroup{
Pid: createProductMaterialGroupCommand.Pid,
MaterialGroupName: createProductMaterialGroupCommand.MaterialGroupName,
MaterialGroupNumber: createProductMaterialGroupCommand.MaterialGroupNumber,
}
var productMaterialGroup *domain.ProductMaterialGroup
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if productMaterialGroup, err = materialService.AddMaterialGroup(operateInfo, newProductMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterialGroup, nil
}
// 返回物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) GetProductMaterialGroup(getProductMaterialGroupQuery *query.GetProductMaterialGroupQuery) (interface{}, error) {
if err := getProductMaterialGroupQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
productMaterialGroup, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"productMaterialGroupId": getProductMaterialGroupQuery.ProductMaterialGroupId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterialGroup == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialGroupQuery.ProductMaterialGroupId)))
}
//测试
//materialService,_:= domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
//nodes,child,_:=materialService.AllMaterialGroupChild(&domain.OperateInfo{CompanyId: productMaterialGroup.CompanyId},productMaterialGroup.ProductMaterialGroupId)
//log.Logger.Debug("节点的Child", map[string]interface{}{"data":child,"nodes":nodes})
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
materialGroupDto := dto.MaterialGroupDto{}
return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
}
// 返回物料分组服务列表
func (productMaterialGroupService *ProductMaterialGroupService) ListProductMaterialGroup(listProductMaterialGroupQuery *query.ListProductMaterialGroupQuery) (interface{}, error) {
if err := listProductMaterialGroupQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
if count, productMaterialGroups, err := productMaterialGroupRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialGroupQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"productMaterialGroups": productMaterialGroups,
}, nil
}
}
// 移除物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.RemoveProductMaterialGroupCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ids, err := materialService.AllMaterialGroupChild(operateInfo, cmd.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(ids) == 0 {
return nil, nil
}
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
count, _, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialGroupIds": ids, "limit": 1})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if count >= 1 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "请处理当前分组下存在的物料信息")
}
for _, id := range ids {
productMaterialGroupRepository, productMaterialGroup, err := factory.FastProductMaterialGroup(transactionContext, id)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if _, err = productMaterialGroupRepository.Remove(productMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 更新物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) UpdateProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialGroupCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
productMaterialGroup := &domain.ProductMaterialGroup{
ProductMaterialGroupId: cmd.ProductMaterialGroupId,
MaterialGroupName: cmd.MaterialGroupName,
//MaterialGroupNumber: cmd.MaterialGroupNumber,
}
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if productMaterialGroup, err := materialService.UpdateMaterialGroup(operateInfo, productMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
materialGroupDto := dto.MaterialGroupDto{}
return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
}
}
// 搜索物料分组服务列表
func (productMaterialGroupService *ProductMaterialGroupService) SearchProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SearchProductMaterialGroupQuery) (int64, interface{}, error) {
if err := cmd.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
queryOptions := utils.ObjectToMap(cmd)
count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var results = make([]*dto.MaterialGroupDto, 0)
for i := range productGroups {
newItem := &dto.MaterialGroupDto{}
newItem.LoadDto(productGroups[i], operateInfo.OrgId)
results = append(results, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, results, nil
}
func (productMaterialGroupService *ProductMaterialGroupService) SelectorProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SelectorProductMaterialGroupQuery) (int64, interface{}, error) {
if err := cmd.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
queryOptions := utils.ObjectToMap(cmd)
count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var results = make([]*dto.MaterialGroupDto, 0)
for i := range productGroups {
newItem := &dto.MaterialGroupDto{}
newItem.LoadDto(productGroups[i], operateInfo.OrgId)
results = append(results, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if cmd.Style == "tree" {
sort.Stable(dto.MaterialGroupDtos(results))
nodes := make([]utils.TreeNode, 0)
for i := range results {
nodes = append(nodes, results[i])
}
tree := utils.NewTree(nodes)
return count, tree.Nodes, nil
}
return count, results, nil
}
func NewProductMaterialGroupService(options map[string]interface{}) *ProductMaterialGroupService {
newProductMaterialGroupService := &ProductMaterialGroupService{}
return newProductMaterialGroupService
}
... ...
... ... @@ -5,11 +5,13 @@ import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
... ... @@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma
productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext))
productRecordDao, _ := dao.NewProductRecordDao(transactionContext.(*pg.TransactionContext))
begin := xtime.BeginningOfDay()
end := time.Now()
workstationId := domain.WorkstationKey(returnMaterialCommand.WorkshopId, returnMaterialCommand.LineId, returnMaterialCommand.SectionId)
totalReceive, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReceiveMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
totalReturn, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReturnMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
allowReturn := totalReceive - totalReturn
if totalReturn+returnMaterialCommand.Weigh > totalReceive {
if allowReturn > 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料,当前只允许退料 %v kg", totalReceive-totalReturn))
}
return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料"))
}
_, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CancelProductRecordCommand struct {
// 生产记录ID
ProductRecordId int `cname:"生产记录ID" json:"productRecordId" valid:"Required"`
}
func (cancelProductRecordCommand *CancelProductRecordCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (cancelProductRecordCommand *CancelProductRecordCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(cancelProductRecordCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cancelProductRecordCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
import (
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
)
// HistoryProductRecord 历史生成记录
type HistoryProductRecord struct {
// 生产记录ID
ProductRecordId int `json:"productRecordId,omitempty"`
// 批号
BatchNumber string `json:"batchNumber,omitempty"`
// 计划的产品名称
PlanProductName string `json:"planProductName,omitempty"`
// 创建时间
CreatedAt string `json:"createdAt,omitempty"`
// 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
ProductRecordType int `json:"productRecordType"`
// 生产工人
ProductWorker *domain.User `json:"productWorker,omitempty"`
// 产能 - 审核前
Weight float64 `json:"weight"`
// 状态 1:未审核 2:已审核 3:已撤回 4:已记录
Status int `json:"status"`
}
func (d *HistoryProductRecord) LoadDto(m *domain.ProductRecord) *HistoryProductRecord {
d.ProductRecordId = m.ProductRecordId
d.ProductWorker = m.ProductWorker
d.Weight = utils.Round(m.ProductRecordInfo.Original, 1)
d.Status = m.ProductRecordInfo.ApproveStatus
d.PlanProductName = m.ProductRecordInfo.PlanProductName
d.BatchNumber = m.ProductRecordInfo.BatchNumber
d.CreatedAt = m.CreatedAt.Local().Format("2006-01-02 15:04:05")
d.ProductRecordType = m.ProductRecordType
if m.ProductRecordType != domain.RecordTypeSecondLevelWeigh &&
m.ProductRecordInfo.ApproveStatus == domain.ProductRecordNotApprove &&
!(xtime.BeginningOfDay().Equal(xtime.New(m.CreatedAt.Local()).BeginningOfDay())) {
//log.Logger.Debug("not equal", map[string]interface{}{"t1": xtime.BeginningOfDay(), "t2": xtime.New(m.CreatedAt.Local()).BeginningOfDay()})
d.Status = domain.ProductRecordLogged
}
return d
}
... ...
package query
import (
"fmt"
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"reflect"
"strings"
"time"
"github.com/beego/beego/v2/core/validation"
)
type HistoryProductRecordQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
Limit int `cname:"查询限制" json:"limit"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
// 匹配多个组织
InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId,omitempty"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId,omitempty"`
// 工段ID
SectionId int `json:"sectionId,omitempty"`
// 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重" json:"productRecordType"`
// 生产线名称
//LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
//SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 员工类型 1:固定 2:派遣 3.临时
//EmployeeType int `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
//BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
//EndTime string `cname:"结束时间" json:"endTime"`
// 上一次记录ID
LastProductRecordId int `cname:"上一次记录ID" json:"lastProductRecordId"`
// 日期
Date string `cname:"日期" json:"date"`
// 生产员工ID
ProductWorkerId int `cname:"生产员工ID" json:"productWorkerId"`
// 状态 0:全部 1:未审核 2:已审核 3:已撤回 4:已记录
Status int `cname:"状态" json:"status"`
// 开始时间
ProductBeginTime time.Time `cname:"开始时间" json:"productBeginTime"`
// 结束时间
ProductEndTime time.Time `cname:"结束时间" json:"productEndTime"`
}
func (cmd *HistoryProductRecordQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
//var err error
//if len(cmd.BeginTime) > 0 {
// if cmd.ProductBeginTime, err = time.Parse("2006-01-02 15:04:05", cmd.BeginTime); err != nil {
// log.Logger.Error(err.Error())
// validation.Error("开始时间有误")
// return
// }
//}
//if len(cmd.EndTime) > 0 {
// if cmd.ProductEndTime, err = time.Parse("2006-01-02 15:04:05", cmd.EndTime); err != nil {
// log.Logger.Error(err.Error())
// validation.Error("结束时间有误")
// return
// }
// if cmd.ProductEndTime.Equal(cmd.ProductBeginTime) {
// cmd.ProductEndTime = cmd.ProductEndTime.Add(time.Hour * 24)
// }
//}
if len(cmd.Date) > 0 {
t, err := xtime.Parse(cmd.Date)
if err != nil {
log.Logger.Error(err.Error())
validation.Error("日期有误")
return
}
cmd.ProductBeginTime = t
cmd.ProductEndTime = t.AddDate(0, 0, 1)
}
if cmd.Status == domain.ProductRecordNotApprove {
cmd.Status = domain.ProductRecordNotApprove
if xtime.IsZero(cmd.ProductBeginTime) || xtime.BeforeEqual(cmd.ProductBeginTime, xtime.BeginningOfDay()) {
cmd.ProductBeginTime = xtime.BeginningOfDay()
}
} else if cmd.Status == domain.ProductRecordLogged {
cmd.Status = domain.ProductRecordNotApprove
if len(cmd.Date) == 0 && xtime.IsZero(cmd.ProductEndTime) {
cmd.ProductEndTime = xtime.BeginningOfDay()
}
if len(cmd.Date) > 0 && !xtime.BeforeEqual(cmd.ProductEndTime, xtime.BeginningOfDay()) {
cmd.Status = domain.ProductRecordLogged
}
}
}
func (cmd *HistoryProductRecordQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
... ... @@ -274,6 +274,41 @@ func (productRecordService *ProductRecordService) SearchProductRecord(operateInf
return count, result, nil
}
// 返回生产记录服务列表
func (productRecordService *ProductRecordService) HistoryProductRecord(operateInfo *domain.OperateInfo, query *query.HistoryProductRecordQuery) (int64, interface{}, error) {
if err := query.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productRecordRepository domain.ProductRecordRepository
productRecordRepository, _, _ = factory.FastPgProductRecord(transactionContext, 0)
count, productRecords, err := productRecordRepository.Find(utils.ObjectToMap(query))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var result = make([]*dto.HistoryProductRecord, 0)
for i := range productRecords {
item := productRecords[i]
newItem := &dto.HistoryProductRecord{}
newItem.LoadDto(item)
result = append(result, newItem)
}
return count, result, nil
}
// 生产记录统计
func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *command.ProductRecordStaticsCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
... ... @@ -308,6 +343,33 @@ func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *comm
return nil, nil
}
// 生产记录审核
func (productRecordService *ProductRecordService) CancelProductRecord(cmd *command.CancelProductRecordCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
svr, err := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
if _, err = svr.Cancel(cmd.ProductRecordId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewProductRecordService(options map[string]interface{}) *ProductRecordService {
newProductRecordService := &ProductRecordService{}
return newProductRecordService
... ...
package syncdata
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
... ... @@ -209,6 +210,101 @@ func (srv *PullDataK3CloudService) PullMaterial(timeFilter time.Time) error {
return nil
}
func (srv *PullDataK3CloudService) pullMaterial(timeFilter time.Time) ([]models.MaterialK3cloud, error) {
//拉取数据
var filterString []string
if !timeFilter.IsZero() {
str := timeFilter.Format("2006-01-02T15:04:05")
filterString = append(filterString, "FModifyDate>='"+str+"'")
}
client, err := newK3cloudClient()
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fieldKeys := []string{
"FMATERIALID", "FSpecification", "FName", "FNumber",
"FDocumentStatus", "FForbidStatus", "FErpClsID",
"FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
"FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName", "FCategoryID",
}
var (
startRow int
allResult []map[string]string
queryErr error
)
for {
result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
FormId: "BD_MATERIAL",
Data: k3cloud.ExecuteBillQueryData{
FormId: "BD_MATERIAL",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
StartRow: startRow,
Limit: 1000,
FilterString: strings.Join(filterString, " and "),
},
})
if err != nil {
queryErr = err
break
}
mp := result.ToMapString()
if len(mp) == 0 {
break
}
allResult = append(allResult, mp...)
startRow += 1000
}
if queryErr != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
materialModels []models.MaterialK3cloud
materialTemp models.MaterialK3cloud
)
nowTime := time.Now()
for _, item := range allResult {
materialId, err := strconv.Atoi(item["FMATERIALID"])
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fErpClsID, _ := strconv.Atoi(item["FErpClsID"])
fBaseUnitId, _ := strconv.Atoi(item["FBaseUnitId"])
materialGroup, _ := strconv.Atoi(item["MaterialGroup"])
fUseOrgId, _ := strconv.Atoi(item["FUseOrgId"])
refStatus, _ := strconv.Atoi(item["RefStatus"])
fCreateDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FCreateDate"])
fModifyDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FModifyDate"])
fForbidDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FForbidDate"])
fApproveDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FApproveDate"])
materialTemp = models.MaterialK3cloud{
MaterialId: materialId,
Name: item["FName"],
Number: item["FNumber"],
Specification: item["FSpecification"],
ForbidStatus: item["FForbidStatus"],
ErpClsId: fErpClsID,
BaseUnitId: fBaseUnitId,
BaseUnitName: item["FBaseUnitId.FName"],
CreateDate: fCreateDate,
ModifyDate: fModifyDate,
ForbidDate: fForbidDate,
ApproveDate: fApproveDate,
MaterialGroup: materialGroup,
MaterialGroupNumber: item["FMaterialGroup.FNumber"],
MaterialGroupName: item["FMaterialGroup.FName"],
RefStatus: refStatus,
UseOrgId: fUseOrgId,
UseOrgName: item["FUseOrgId.FName"],
JoinProductId: 0,
DataVersion: nowTime.Unix(),
FCategoryID: item["FCategoryID"],
}
materialModels = append(materialModels, materialTemp)
}
return materialModels, nil
}
//PullMaterialGroup 拉取物料分组
func (srv *PullDataK3CloudService) PullMaterialGroup() error {
client, err := newK3cloudClient()
... ... @@ -462,6 +558,33 @@ func (srv *PullDataK3CloudService) PullPrdMo(timeFilter time.Time) error {
return nil
}
// PullMaterialCategory 拉取物料分类
func (srv *PullDataK3CloudService) PullMaterialCategory() (map[string]string, error) {
client, err := newK3cloudClient()
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fieldKeys := []string{
"FName", "FNUMBER", "FMasterId",
}
result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
FormId: "BD_MATERIALCATEGORY",
Data: k3cloud.ExecuteBillQueryData{
FormId: "BD_MATERIALCATEGORY",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
//TopRowCount: 4,
FilterString: "",
},
})
categorys := result.ToMapString()
var categorysById = make(map[string]string)
for _, v := range categorys {
categorysById[v["FMasterId"]] = v["FName"]
}
return categorysById, nil
}
// 同步产品
func (srv *PullDataK3CloudService) SyncDataProduct(ptr *pgTransaction.TransactionContext, fromTime time.Time) error {
prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
... ... @@ -612,3 +735,165 @@ func (srv *PullDataK3CloudService) SyncDataProductPlan(ptr *pgTransaction.Transa
}
return nil
}
// 同步产品
func (srv *PullDataK3CloudService) SyncDataMaterialGroup(ptr *pgTransaction.TransactionContext) error {
prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
if err != nil {
return err
}
var userService = domainService.NewUserService()
org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fromMaterialGroups, err := prdMoDao.SearchMaterialGroup() // 默认企业名称素天下、或者使用组织ID
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
cid = constant.MANUFACTURE_DEFAULT_COMPANYID
oid = constant.MANUFACTURE_DEFAULT_ORGID
)
productMaterialGroupRepository, _, _ := factory.FastProductMaterialGroup(ptr, 0)
_, materialGroups, err := productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
if err != nil {
return err
}
mapMaterialGroups := domain.ProductMaterialGroups(materialGroups).ToMapByGroupNumber()
mapFromMaterialGroups := models.MaterialGroupK3clouds(fromMaterialGroups).ToMapId()
for _, from := range fromMaterialGroups {
to, ok := mapMaterialGroups[from.Number]
if ok {
// 更新
if to.MaterialGroupName != from.Name {
log.Logger.Info(fmt.Sprintf("更新物料分组 old:%v new:%v", to.MaterialGroupName, from.Name), map[string]interface{}{"material": to})
to.MaterialGroupName = from.Name
}
continue
}
var parentId int
if from.ParentId > 0 {
parent, ok := mapFromMaterialGroups[from.ParentId]
if !ok {
log.Logger.Warn("parent node not exits", map[string]interface{}{"material": to})
continue
}
toParent, ok := mapMaterialGroups[parent.Number]
if !ok {
log.Logger.Warn("to parent node not exits", map[string]interface{}{"material": to})
continue
}
parentId = toParent.ProductMaterialGroupId
}
productMaterialGroup := &domain.ProductMaterialGroup{
CompanyId: cid,
OrgId: oid,
Pid: parentId,
MaterialGroupName: from.Name,
MaterialGroupNumber: from.Number,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
if productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup); err != nil {
return err
}
mapMaterialGroups[productMaterialGroup.MaterialGroupNumber] = productMaterialGroup
}
return nil
}
// SyncDataMaterial 同步物料数据
// pullType 拉取数据方式 full:全量 其他:增量
func (srv *PullDataK3CloudService) SyncDataMaterial(ptr *pgTransaction.TransactionContext, pullType string, fromTime time.Time) error {
var (
lastTime = utils.GetZeroTime(time.Now()).Add(-time.Hour * 24) //前一天有修改的记录
org *domain.Org
err error
)
if pullType == "full" {
lastTime = time.Time{}
}
var userService = domainService.NewUserService()
org, err = userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
cid = constant.MANUFACTURE_DEFAULT_COMPANYID
oid = constant.MANUFACTURE_DEFAULT_ORGID
productMaterialRepository, _, _ = factory.FastProductMaterial(ptr, 0)
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(ptr, 0)
materialGroups domain.ProductMaterialGroups
)
_, materialGroups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
if err != nil {
return err
}
mapMaterialGroup := materialGroups.ToMapByGroupNumber()
records, err := srv.pullMaterial(lastTime)
if err != nil {
return err
}
mapMaterialCategory, err := srv.PullMaterialCategory()
if err != nil {
return err
}
log.Logger.Debug(fmt.Sprintf("【同步物料数据】查询数据条数:%v", len(records)))
_, materialsFromDb, _ := productMaterialRepository.Find(map[string]interface{}{"companyId": cid, "limit": 20000})
mapMaterialsFromDb := domain.ProductMaterials(materialsFromDb).ToMapByNumber()
for index, item := range records {
var (
material *domain.ProductMaterial
materialGroup *domain.ProductMaterialGroup
ok bool
attribute string //物料属性
category string //物料类别
)
if item.UseOrgName != "素天下" {
continue
}
if materialGroup, ok = mapMaterialGroup[item.MaterialGroupNumber]; !ok {
continue
}
if _, ok := mapMaterialsFromDb[item.Number]; ok {
continue
}
if v, ok := mapMaterialCategory[item.FCategoryID]; ok {
category = v
}
attribute = domain.MaterialAttributeDescription(item.ErpClsId)
material = &domain.ProductMaterial{
CompanyId: cid,
OrgId: oid,
ProductMaterialGroupId: materialGroup.ProductMaterialGroupId,
MaterialName: item.Name,
MaterialNumber: item.Number,
MaterialAttribute: &domain.MaterialAttribute{Attribute: attribute},
MaterialCategory: &domain.MaterialCategory{Category: category},
ProductMaterialExt: &domain.MaterialExt{
Specification: item.Specification,
Unit: item.BaseUnitName,
ExpiredDay: 0,
Remark: "",
Source: "k3cloud",
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
if material, err = productMaterialRepository.Save(material); err != nil {
log.Logger.Debug(fmt.Sprintf("同步失败 序号:%v 物料数据 id:%v number:%v name:%v 错误:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName, err.Error()))
continue
}
log.Logger.Debug(fmt.Sprintf("同步 序号:%v 物料数据 id:%v number:%v name:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName))
}
return nil
}
... ...
... ... @@ -13,10 +13,13 @@ type MaterialUnitConversionDto struct {
ToUnitQuantity *domain.UnitQuantity `json:"toUnitQuantity,omitempty"`
}
func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion) *MaterialUnitConversionDto {
func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion, material *domain.ProductMaterial) *MaterialUnitConversionDto {
d.UnitConversionId = m.UnitConversionId
d.MaterialName = m.Material.MaterialName
d.FromUnitQuantity = m.FromUnitQuantity
d.ToUnitQuantity = m.ToUnitQuantity
if material != nil {
d.MaterialName = material.MaterialName
}
return d
}
... ...
... ... @@ -25,7 +25,7 @@ type UnitConversionDto struct {
AuthFlag bool `json:"authFlag"`
}
func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitConversionDto {
func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int, productMaterial *domain.ProductMaterial) *UnitConversionDto {
d.UnitConversionId = m.UnitConversionId
d.WorkStation = m.WorkStation
d.Material = m.Material
... ... @@ -36,5 +36,8 @@ func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitCo
if m.Ext != nil {
d.OrgName = m.Ext.OrgName
}
if productMaterial != nil {
d.Material.MaterialName = productMaterial.MaterialName
}
return d
}
... ...
... ... @@ -91,12 +91,21 @@ func (unitConversionService *UnitConversionService) GetUnitConversion(getUnitCon
//var unitConversionRepository domain.UnitConversionRepository
var unitConversion *domain.UnitConversion
_, unitConversion, err = factory.FastPgUnitConversion(transactionContext, getUnitConversionQuery.UnitConversionId)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var productMaterial *domain.ProductMaterial
if unitConversion.Material.ProductMaterialId > 0 {
_, productMaterial, err = factory.FastProductMaterial(transactionContext, unitConversion.Material.ProductMaterialId)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := &dto.UnitConversionDto{}
result.LoadDto(unitConversion, 0)
result.LoadDto(unitConversion, 0, productMaterial)
return result, nil
}
... ... @@ -293,17 +302,29 @@ func (unitConversionService *UnitConversionService) SearchUnitConversion(operate
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
if len(productMaterialIds) > 0 {
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
}
var result = make([]*dto.UnitConversionDto, 0)
for i := range unitConversions {
item := unitConversions[i]
newItem := &dto.UnitConversionDto{}
newItem.LoadDto(item, operateInfo.OrgId)
newItem.LoadDto(item, operateInfo.OrgId, mapProductMaterial[item.Material.ProductMaterialId])
result = append(result, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, result, nil
}
... ... @@ -331,11 +352,22 @@ func (unitConversionService *UnitConversionService) SearchMaterial(operateInfo *
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
if len(productMaterialIds) > 0 {
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
}
var result = make([]*dto.MaterialUnitConversionDto, 0)
for i := range unitConversions {
item := unitConversions[i]
newItem := &dto.MaterialUnitConversionDto{}
newItem.LoadDto(item)
newItem.LoadDto(item, mapProductMaterial[item.Material.ProductMaterialId])
result = append(result, newItem)
}
return count, map[string]interface{}{
... ...
... ... @@ -14,6 +14,7 @@ var HTTP_PORT int = 8081
var CACHE_PREFIX = "allied-creation-manufacture-dev"
var LOG_LEVEL = "debug"
var LOG_FILE = "app.log"
var PPROF_ON = true
//天联共创基础模块
var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com"
... ... @@ -45,5 +46,6 @@ func init() {
SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV)
HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT)
SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
PPROF_ON = Configurator.DefaultBool("PPROF_ON", PPROF_ON)
CACHE_PREFIX = SERVICE_NAME
}
... ...
... ... @@ -28,10 +28,12 @@ var MQTT_HOST = "47.97.5.102"
var MQTT_PORT = "6000"
var MQTT_USER = "admin"
var MQTT_PASSWORD = "123456"
var MQTT_UP = true
func init() {
MQTT_HOST = Configurator.DefaultString("MQTT_HOST", MQTT_HOST)
MQTT_PORT = Configurator.DefaultString("MQTT_PORT", MQTT_PORT)
MQTT_USER = Configurator.DefaultString("MQTT_USER", MQTT_USER)
MQTT_PASSWORD = Configurator.DefaultString("MQTT_PASSWORD", MQTT_PASSWORD)
MQTT_UP = Configurator.DefaultBool("MQTT_UP", MQTT_UP)
}
... ...
... ... @@ -7,6 +7,8 @@ import (
const MaxQueryRow = 10000
const PathSegment = ","
// 班次
const (
WorkOnFullDay = 1 //全天
... ...
... ... @@ -2,6 +2,9 @@ package domain
// 冗余附加数据
type Ext struct {
// 操作人
Operator *User `json:"operator,omitempty"`
// 组织名称
OrgName string `json:"orgName,omitempty"`
... ... @@ -35,3 +38,8 @@ func (e *Ext) WithProductPlanExt(ext *ProductPlanExt) *Ext {
e.ProductPlanExt = ext
return e
}
func (e *Ext) WithOperator(ext *User) *Ext {
e.Operator = ext
return e
}
... ...
... ... @@ -2,8 +2,36 @@ package domain
// 物料
type Material struct {
// 物料名称
// 物料ID
ProductMaterialId int `json:"productMaterialId"`
// 物料名称 (最新数据需要查询物料表)
MaterialName string `json:"materialName,omitempty"`
// 物料类别
// 物料类别 ‘南瓜饼串’、‘ 包装袋(空)’、‘包装袋(件数)’、装箱(件数)
MaterialCategory string `json:"materialCategory,omitempty"`
}
// 物料类别
type MaterialCategory struct {
//Id int `json:"id"`
Category string `json:"category"`
}
// 物料属性
type MaterialAttribute struct {
//Id int `json:"id"`
Attribute string `json:"attribute"`
}
// 物料扩展数据
type MaterialExt struct {
// 规格
Specification string `json:"specification"`
// 单位
Unit string `json:"unit"`
// 保质期 单位:天
ExpiredDay int `json:"expiredDay"`
// 备注
Remark string `json:"remark"`
// 来源 k3cloud
Source string `json:"source"`
}
... ...
... ... @@ -2,6 +2,7 @@ package domain
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"strconv"
"time"
)
... ... @@ -99,15 +100,18 @@ type ImportProductItem struct {
}
func (item *ImportProductItem) Valid() error {
if len(item.ProductName) == 0 {
return fmt.Errorf("品名不能为空")
}
if len(item.Unit) == 0 {
return fmt.Errorf("规格不能为空")
}
if len(item.ProductCategory) == 0 {
return fmt.Errorf("类别不能为空")
if len(item.ProductCode) == 0 {
return fmt.Errorf("产品编号不能为空")
}
//if len(item.ProductName) == 0 {
// return fmt.Errorf("品名不能为空")
//}
//if len(item.Unit) == 0 {
// return fmt.Errorf("规格不能为空")
//}
//if len(item.ProductCategory) == 0 {
// return fmt.Errorf("类别不能为空")
//}
if len(item.UnitWeight) == 0 {
item.UnitWeight = "0"
}
... ... @@ -116,3 +120,13 @@ func (item *ImportProductItem) Valid() error {
}
return nil
}
type Products []*Product
func (products Products) ProductCodes() []string {
var result = utils.NewSet()
for _, v := range products {
result.Add(v.ProductCode)
}
return result.KeysStr()
}
... ...
... ... @@ -80,15 +80,48 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr
if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) {
return 0
}
wt := utils.Round(productAttendanceRecord.SignOut.Sub(productAttendanceRecord.SignIn).Hours(), 1)
signIn := roundTime(productAttendanceRecord.SignIn)
signOut := roundTime(productAttendanceRecord.SignOut)
wt := utils.Round(signOut.Sub(signIn).Hours(), 2)
if productCalendar == nil {
return wt
return roundWorkTime(wt)
}
wt = wt - productAttendanceRecord.AttendanceBreakTime(productCalendar)
if wt < 0 {
return 0
}
return wt
return roundWorkTime(wt)
}
// roundWorkTime 工时取整[0:0.167]=> 0 \ [0.167,0.667]=> 0.5 \ [0.667,1]=>1
// 10/60 = 0.167 40/60 = 0.667
func roundWorkTime(wt float64) float64 {
i := float64(int(wt))
f := wt - i
if f < 0.167 {
return i
}
if f >= 0.167 && f < 0.667 {
return i + 0.5
}
if f >= 0.667 {
return i + 1
}
return i
}
func roundTime(t time.Time) time.Time {
hour, min, _ := t.Local().Clock()
y, m, d := t.Local().Date()
newTime := time.Date(y, m, d, hour, 0, 0, 0, time.Local)
if min < 11 {
min = 0
} else if min >= 11 && min < 41 {
min = 30
} else {
min = 60
}
return newTime.Add(time.Minute * time.Duration(min))
}
func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error {
... ...
package domain
import "time"
// 生产物料
type ProductMaterial struct {
// 物料ID
ProductMaterialId int `json:"productMaterialId"`
// 企业id
CompanyId int `json:"companyId"`
// 组织ID
OrgId int `json:"orgId"`
// 物料分组ID
ProductMaterialGroupId int `json:"productMaterialGroupId"`
// 物料编码
MaterialNumber string `json:"materialNumber"`
// 物料名称
MaterialName string `json:"materialName"`
// 物料属性
MaterialAttribute *MaterialAttribute `json:"materialAttribute"`
// 物料类别
MaterialCategory *MaterialCategory `json:"materialCategory"`
// 物料扩展
ProductMaterialExt *MaterialExt `json:"productMaterialExt"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 扩展
Ext *Ext `json:"ext"`
}
type ProductMaterialRepository interface {
Save(productMaterial *ProductMaterial) (*ProductMaterial, error)
Remove(productMaterial *ProductMaterial) (*ProductMaterial, error)
FindOne(queryOptions map[string]interface{}) (*ProductMaterial, error)
Find(queryOptions map[string]interface{}) (int64, []*ProductMaterial, error)
}
func (productMaterial *ProductMaterial) Identify() interface{} {
if productMaterial.ProductMaterialId == 0 {
return nil
}
return productMaterial.ProductMaterialId
}
func (productMaterial *ProductMaterial) Update(data map[string]interface{}) error {
return nil
}
type ProductMaterials []*ProductMaterial
func (productMaterials ProductMaterials) ToMapById() map[int]*ProductMaterial {
var mapProductMaterial = make(map[int]*ProductMaterial, 0)
for _, v := range productMaterials {
mapProductMaterial[v.ProductMaterialId] = v
}
return mapProductMaterial
}
func (productMaterials ProductMaterials) ToMapByNumber() map[string]*ProductMaterial {
var mapProductMaterial = make(map[string]*ProductMaterial, 0)
for _, v := range productMaterials {
mapProductMaterial[v.MaterialNumber] = v
}
return mapProductMaterial
}
// 10:资产,9:配置,2:自制,11:费用,12:模型,5:虚拟,7:一次性,13:产品系列 12:模型,3:委外,4:特征,6:服务,1:外购
var mapMaterialCategory = map[int]string{
1: "外购",
2: "自制",
3: "委外",
4: "特征",
5: "虚拟",
6: "服务",
7: "一次性",
8: "",
9: "配置",
10: "资产",
11: "费用",
12: "模型",
13: "产品系列",
}
func MaterialAttributeDescription(code int) string {
if v, ok := mapMaterialCategory[code]; ok {
return v
}
return ""
}
... ...
package domain
import (
"fmt"
"strconv"
"time"
)
// 物料分组
type ProductMaterialGroup struct {
// 物料分组ID
ProductMaterialGroupId int `json:"productMaterialGroupId"`
// 企业id
CompanyId int `json:"companyId"`
// 组织ID
OrgId int `json:"orgId"`
// 父级ID
Pid int `json:"pid"`
// 路径 (不使用,如果父级改变的话,子级的Path要做更新)
//Path string `json:"path"`
// 物料分组名称
MaterialGroupName string `json:"materialGroupName"`
// 物料分组编码
MaterialGroupNumber string `json:"materialGroupNumber"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 扩展数据
Ext *Ext `json:"ext,omitempty"`
}
type ProductMaterialGroupRepository interface {
Save(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
Remove(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
FindOne(queryOptions map[string]interface{}) (*ProductMaterialGroup, error)
Find(queryOptions map[string]interface{}) (int64, []*ProductMaterialGroup, error)
}
func (productMaterialGroup *ProductMaterialGroup) Identify() interface{} {
if productMaterialGroup.ProductMaterialGroupId == 0 {
return nil
}
return productMaterialGroup.ProductMaterialGroupId
}
func (productMaterialGroup *ProductMaterialGroup) Update(data map[string]interface{}) error {
return nil
}
func (productMaterialGroup *ProductMaterialGroup) GroupNumberComposeUp(parent *ProductMaterialGroup, latestNumber string, total int) string {
iNumber, err := strconv.ParseInt(latestNumber, 10, 64)
if err == nil {
iNumber += 1
return formatFunc(iNumber)
}
if parent != nil {
return parent.MaterialGroupNumber + formatFunc(int64(total+1))
}
return formatFunc(int64(total + 1))
}
func formatFunc(iNumber int64) string {
sNumber := fmt.Sprintf("%d", iNumber)
if len(sNumber)%2 == 1 {
return "0" + sNumber
}
return sNumber
}
/***** 1.实现树 *****/
func (productMaterialGroup *ProductMaterialGroup) PID() string {
return fmt.Sprintf("%d", productMaterialGroup.Pid)
}
func (productMaterialGroup *ProductMaterialGroup) ID() string {
return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
}
type ProductMaterialGroups []*ProductMaterialGroup
func (tree ProductMaterialGroups) Len() int {
return len(tree)
}
func (tree ProductMaterialGroups) Less(i, j int) bool {
if tree[i].Pid < tree[j].Pid {
return true
}
if tree[i].Pid == tree[j].Pid {
return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
}
return false
}
func (tree ProductMaterialGroups) Swap(i, j int) {
tree[i], tree[j] = tree[j], tree[i]
}
func (tree ProductMaterialGroups) ToMapByGroupNumber() map[string]*ProductMaterialGroup {
var result = make(map[string]*ProductMaterialGroup)
for i := range tree {
result[tree[i].MaterialGroupNumber] = tree[i]
}
return result
}
... ...
... ... @@ -17,6 +17,8 @@ const (
const (
ProductRecordNotApprove = 1 // 未审核
ProductRecordApproved = 2 // 已审核
ProductRecordWithdraw = 3 // 已撤回
ProductRecordLogged = 4 // 已记录
)
// 生产记录
... ... @@ -82,6 +84,21 @@ func (productRecord *ProductRecord) Approve(approveUser *User, weighAfter float6
return nil
}
func (productRecord *ProductRecord) Cancel() error {
if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordApproved {
return errors.New("已审核")
}
if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordWithdraw {
return errors.New("已撤销")
}
//if xtime.BeforeEqual(productRecord.CreatedAt, xtime.BeginningOfDay()) {
// return errors.New("已记录")
//}
productRecord.ProductRecordInfo.ApproveStatus = ProductRecordWithdraw
productRecord.UpdatedAt = time.Now()
return nil
}
func TaskKeyPatternProductRecordStatics() string {
return fmt.Sprintf("%v:task:product-record:statics", constant.CACHE_PREFIX)
}
... ...
... ... @@ -11,7 +11,7 @@ const (
)
const (
ProductSection1 = "打料"
ProductSection1 = "制模"
ProductSection2 = "成型"
ProductSection3 = "穿串"
ProductSection4 = "包装"
... ...
package domain
import "time"
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
)
// 单位换算
type UnitConversion struct {
... ... @@ -57,3 +60,16 @@ func (unitConversion *UnitConversion) Update(data map[string]interface{}) error
unitConversion.UpdatedAt = time.Now()
return nil
}
type UnitConversions []*UnitConversion
func (unitConversions UnitConversions) ProductMaterialIds() []int {
set := utils.NewSet()
for i := range unitConversions {
if unitConversions[i].Material.ProductMaterialId == 0 {
continue
}
set.Add(unitConversions[i].Material.ProductMaterialId)
}
return set.KeysInt()
}
... ...
... ... @@ -25,7 +25,6 @@ func (dao *DeviceDailyRunningRecordDao) TimeSectionRunningRecord(companyId, orgI
tx := dao.transactionContext.PgTx
sql := fmt.Sprintf(`
WITH ts_product as(
select sum(a.weight) total,a.ts from (
select
... ... @@ -38,7 +37,7 @@ WITH ts_product as(
and work_station->>'workshopId'='?'
and work_station->>'lineId'='?'
and work_station->>'sectionName'=?
and created_at >?
and created_at >=?
and created_at <?
) a
group by a.ts
... ... @@ -47,14 +46,14 @@ WITH ts_product as(
-- select * from ts_product
, ts_product_list as (
select d.ts,ts_product.total from (
select to_char(c.ts::timestamp,'mm-dd') ts from (
select generate_series(to_timestamp(?),to_timestamp(?),'1 day') ts
select to_char(c.ts,'mm-dd') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai',to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai','1 day') ts
) c ) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total
from ts_product_list
`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime.Unix(), endTime.Unix()); err != nil {
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime); err != nil {
return err
}
return nil
... ... @@ -120,7 +119,7 @@ select * from device_running_oee
}
// 时段产能
func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, result interface{}) error {
func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, endTime time.Time, result interface{}) error {
tx := dao.transactionContext.PgTx
sql := fmt.Sprintf(`
... ... @@ -137,7 +136,8 @@ WITH ts_product as(
and work_station->>'lineId'='?'
and work_station->>'sectionName'=?
and device_running_record_info->>'deviceType'='CCJ'
and created_at >?
and created_at >=?
and created_at < ?
) a
group by a.ts
order by ts
... ... @@ -145,19 +145,15 @@ WITH ts_product as(
-- select * from ts_product
, ts_product_list as (
select d.ts,ts_product.total from (
select to_char(c.ts::timestamp,'HH24:MI') ts from (
select generate_series(a.end - interval '5 hour',
"replace"(to_char(a.end, 'yyyy-mm-dd HH24:') || cast(date_part('minute',a.end) as integer)/30*30+30, ':0', ':00')::timestamp,
'30 minute') ts from (
select to_timestamp(to_char(now() at time ZONE 'Asia/shanghai','yyyy-mm-dd HH24'),'yyyy-mm-dd HH24') as end
) a
) c
select "replace"(to_char(created_at at time ZONE 'Asia/shanghai', 'HH24:') || cast(date_part('minute',created_at) as integer)/30*30, ':0', ':00') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),'30 minute') created_at
) a
) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total
from ts_product_list
`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime); err != nil {
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime.Add(-time.Minute*1)); err != nil {
return err
}
return nil
... ...
... ... @@ -178,3 +178,13 @@ func (d *MaterialK3cloudDao) GetLastVersion() (int64, error) {
}
return materialData[0].DataVersion, nil
}
func (d *MaterialK3cloudDao) SearchMaterialGroup() ([]*models.MaterialGroupK3cloud, error) {
var materialData []*models.MaterialGroupK3cloud
query := d.transactionContext.PgTx.Model(&materialData)
query.OrderExpr("number asc")
if err := query.Select(); err != nil {
return nil, err
}
return materialData, nil
}
... ...
... ... @@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC
// 日期
// 产品编号
// 调度状态 status
func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
func (dao *ProductPlanDispatchRecordDao) ProductPlanDispatchRecord(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
tx := dao.transactionContext.PgTx
productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord)
query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{})
... ... @@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
query.Where("org_id = ?", orgId)
query.Where("work_station->>'workStationId'=?", workStationId)
query.Where("product_date = ?", date)
query.Where("plan_dispatch_status = ?", status)
if status > 0 {
query.Where("plan_dispatch_status = ?", status)
}
query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode)
query.Order("updated_at desc")
if err := query.First(); err != nil {
... ... @@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel)
}
}
func (dao *ProductPlanDispatchRecordDao) ProductPlan(companyId, orgId int, workshopId int, date time.Time, productCode string) (*domain.ProductPlan, error) {
tx := dao.transactionContext.PgTx
productPlan := new(models.ProductPlan)
query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
query.Where("company_id = ?", companyId)
query.Where("org_id = ?", orgId)
query.Where("workshop->>'workshopId'='?'", workshopId)
query.Where("product_date = ?", date)
if len(productCode) > 0 {
query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
}
query.Order("updated_at desc")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productPlan.ProductPlanId == 0 {
return nil, nil
} else {
return transform.TransformToProductPlanDomainModelFromPgModels(productPlan)
}
}
func (dao *ProductPlanDispatchRecordDao) ProductPlans(companyId, orgId int, workshopId int, date time.Time, productCode string) ([]*domain.ProductPlan, error) {
tx := dao.transactionContext.PgTx
productPlan := new(models.ProductPlan)
query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
query.Where("company_id = ?", companyId)
query.Where("org_id = ?", orgId)
query.Where("workshop->>'workshopId'='?'", workshopId)
query.Where("product_date = ?", date)
if len(productCode) > 0 {
query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
}
query.Order("updated_at desc")
var productPlanModels = make([]*models.ProductPlan, 0)
var productPlans = make([]*domain.ProductPlan, 0)
if err := query.Select(&productPlanModels); err != nil {
return productPlans, err
} else {
for _, productPlanModel := range productPlanModels {
if productPlan, err := transform.TransformToProductPlanDomainModelFromPgModels(productPlanModel); err != nil {
return productPlans, err
} else {
productPlans = append(productPlans, productPlan)
}
}
return productPlans, nil
}
}
... ...
... ... @@ -170,3 +170,18 @@ func (d *PrdMoK3cloudDao) GetLatestData(fromTime time.Time) ([]*models.PrdMoK3cl
}
return result, nil
}
// GetLatestMaterialData 增量获取物料数据
func (d *PrdMoK3cloudDao) GetLatestMaterialData(fromTime time.Time, offset, limit int) ([]*models.MaterialK3cloud, int, error) {
m := new(models.MaterialK3cloud)
result := make([]*models.MaterialK3cloud, 0)
query := d.transactionContext.PgTx.Model(m)
if !fromTime.IsZero() {
query.Where("modify_date>=?", fromTime)
}
err := query.Select(&result)
if err != nil {
return nil, 0, err
}
return result, len(result), nil
}
... ...
package dao
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type ProductMaterialGroupDao struct {
transactionContext *pgTransaction.TransactionContext
}
func (dao *ProductMaterialGroupDao) CurrentGroupLatestNumber(companyId int, productMaterialGroupId int) (string, int, error) {
m := new(models.ProductMaterialGroup)
var result string
var total int
query := dao.transactionContext.PgTx.Model(m).Where("company_id = ?", companyId)
query.Where("pid = ?", productMaterialGroupId)
query.ColumnExpr("max(material_group_number) number")
query.ColumnExpr("count(material_group_number) total")
query.AllWithDeleted()
err := query.Select(&result, &total)
return result, total, err
}
func NewProductMaterialGroupDao(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialGroupDao{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from (
and product_record_info->>'approveStatus'='2'
and created_at >=?
and created_at <?
and work_station->>'sectionName' in ('打料','成型','穿串','包装')
and work_station->>'sectionName' in ('制模','成型','穿串','包装')
) a
group by a.workStationId
)
... ... @@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0)
)
--select * from item_product_rate
select a.sname, coalesce(b.rate,0) rate from (
select unnest(ARRAY ['打料','成型','穿串','包装']) sname
select unnest(ARRAY ['制模','成型','穿串','包装']) sname
) a left join item_product_rate b on a.sname=b.sname`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil {
return err
}
return nil
}
// ProductWeightStatics 产能统计
func (dao *ProductRecordDao) ProductWeightStatics(companyId, orgId, productRecordType, productPlanId int, workstationId string, beginTime time.Time, endTime time.Time) (float64, error) {
tx := dao.transactionContext.PgTx
var result = struct {
Total float64
}{}
sql := fmt.Sprintf(`
select coalesce(sum(cast(product_record_info->>'original' as DECIMAL)),0) total
from manufacture.product_records
where company_id = ? and org_id = ? and product_record_type = ?
and work_station->>'workStationId' = ?
and product_record_info->>'productPlanId' = '?'
and created_at >= ? and created_at < ?
`)
if _, err := tx.QueryOne(&result, sql, companyId, orgId, productRecordType, workstationId, productPlanId, beginTime, endTime); err != nil {
return 0, err
}
return result.Total, nil
}
... ...
... ... @@ -3,6 +3,6 @@ package domainService
import "testing"
func TestSectionProductive(t *testing.T) {
svr := NewByteBankService()
svr.SectionProductive()
//svr := NewByteBankService()
//svr.SectionProductive()
}
... ...
... ... @@ -6,8 +6,8 @@ import (
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"strconv"
"time"
... ... @@ -36,10 +36,22 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var generator = redis.NewProductCodeCache(opt.CompanyId)
var materials domain.ProductMaterials
if materials, err = ptr.GetProductMaterialByImportItems(opt.CompanyId, list); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapMaterials := materials.ToMapByNumber()
for i := range list {
item := list[i]
if v, ok := mapMaterials[item.ProductCode]; !ok {
item.FailReason = "导入的产品编号不存在"
failRows = append(failRows, item)
continue
} else {
item.Unit = v.ProductMaterialExt.Unit
item.ProductName = v.MaterialName
item.ProductCategory = v.MaterialCategory.Category
}
if err := item.Valid(); err != nil {
item.FailReason = err.Error()
failRows = append(failRows, item)
... ... @@ -69,14 +81,6 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
continue
}
}
if len(newItem.ProductCode) == 0 {
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
newItem.ProductCode = code
}
if _, ok := mapProduct[newItem.ProductCode]; !ok {
mapProduct[newItem.ProductCode] = newItem
... ... @@ -105,6 +109,28 @@ func (ptr *PGBatchAddProductService) updateProduct(opt *domain.OperateInfo, item
return nil
}
func (ptr *PGBatchAddProductService) GetProductMaterialByProductCodes(companyId int, productCodes []string) ([]*domain.ProductMaterial, error) {
productMaterialRepository, _ := repository.NewProductMaterialRepository(ptr.transactionContext)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"companyId": companyId, "materialNumbers": productCodes})
return productMaterials, err
}
func (ptr *PGBatchAddProductService) GetProductMaterialByImportItems(companyId int, list []*domain.ImportProductItem) ([]*domain.ProductMaterial, error) {
productCodes := ptr.GetProductCodesByImportItems(list)
if len(productCodes) == 0 {
return []*domain.ProductMaterial{}, nil
}
return ptr.GetProductMaterialByProductCodes(companyId, productCodes)
}
func (ptr *PGBatchAddProductService) GetProductCodesByImportItems(list []*domain.ImportProductItem) []string {
var result = utils.NewSet()
for _, v := range list {
result.Add(v.ProductCode)
}
return result.KeysStr()
}
func NewPGBatchAddProductService(transactionContext *pgTransaction.TransactionContext) (*PGBatchAddProductService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -94,11 +94,19 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
}
productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
var response = make([]interface{}, 0)
var tmpXData = make([]string, 0)
var (
response = make([]interface{}, 0)
tmpXData = make([]string, 0)
beginTime = xtime.BeginningOfDay() //time.Now().Add(-time.Hour*5)
endTime = time.Now()
)
if !xtime.IsZero(request.Date.Time()) && !request.Date.Time().Equal(beginTime) {
beginTime = request.Date.Time()
endTime = request.Date.Time().AddDate(0, 0, 1)
}
for _, v := range workshop.GetProductLines(domain.NotDeleted) {
var result = make([]*record, 0)
if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, time.Now().Add(-time.Hour*5), &result); err != nil {
if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beginTime, endTime, &result); err != nil {
log.Logger.Error(err.Error())
continue
}
... ... @@ -123,10 +131,10 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
}
type HourProductiveStatisticsRequest struct {
CompanyId int `json:"companyId" valid:"Required"`
OrgId int `json:"orgId" valid:"Required"`
WorkshopId int `json:"workshopId" valid:"Required"`
Date time.Time `json:"date"`
CompanyId int `json:"companyId" valid:"Required"`
OrgId int `json:"orgId" valid:"Required"`
WorkshopId int `json:"workshopId" valid:"Required"`
Date utils.TimeString `json:"date"`
}
func NewXYData(xData []string, values interface{}) interface{} {
... ... @@ -141,7 +149,7 @@ func NewXYData(xData []string, values interface{}) interface{} {
return values
}
// 时段产能-统计 (传串设备)
// DailyProductiveStatistics 每日产能-统计 (传串设备)
func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) {
var request = &HourProductiveStatisticsRequest{}
if err := utils.LoadQueryObject(queryOptions, request); err != nil {
... ... @@ -153,9 +161,13 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
Ts string `json:"ts"`
Total float64 `json:"total"`
}
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
var (
beingTime = xtime.BeginningOfDay().AddDate(0, 0, -6)
endTime = xtime.BeginningOfDay().AddDate(0, 0, 1).Add(-time.Second)
)
if !xtime.IsZero(time.Time(request.Date)) {
beingTime = request.Date.Time().AddDate(0, 0, -6)
endTime = request.Date.Time().AddDate(0, 0, 1).Add(-time.Second)
}
workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
if err != nil || workshop == nil {
... ... @@ -168,7 +180,7 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
for _, v := range workshop.GetProductLines(domain.NotDeleted) {
var result = make([]*record, 0)
if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, date.Add(-time.Hour*24*7), date, &result); err != nil {
if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beingTime, endTime, &result); err != nil {
log.Logger.Error(err.Error())
continue
}
... ... @@ -213,8 +225,8 @@ func (ptr *PGCommonStatisticsService) ProportionOfSecondLevelStatistics(queryOpt
}
productRecordDao, _ := dao.NewProductRecordDao(ptr.transactionContext)
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
if !xtime.IsZero(time.Time(request.Date)) {
date = request.Date.Time()
}
var input = []struct {
name string
... ... @@ -262,8 +274,8 @@ func (ptr *PGCommonStatisticsService) WorkshopProductionEfficiencyStatistics(que
}
productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
if !xtime.IsZero(time.Time(request.Date)) {
date = time.Time(request.Date)
}
var input = []struct {
name string
... ...
package domainService
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"sort"
"time"
)
type PGMaterialService struct {
transactionContext *pgTransaction.TransactionContext
}
// 物料
func (ptr *PGMaterialService) AddMaterial(opt *domain.OperateInfo, item *domain.ProductMaterial) (*domain.ProductMaterial, error) {
var (
user *domain.User
org *domain.Org
err error
newProductMaterial *domain.ProductMaterial
productMaterialRepository, _ = repository.NewProductMaterialRepository(ptr.transactionContext)
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
_, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId})
if err != nil {
return nil, err
}
if newProductMaterial, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialNumber": item.MaterialNumber}); err == nil || newProductMaterial != nil {
return nil, fmt.Errorf("物料编码已存在")
}
newProductMaterial = &domain.ProductMaterial{
CompanyId: item.CompanyId,
OrgId: item.OrgId,
ProductMaterialGroupId: item.ProductMaterialGroupId,
MaterialName: item.MaterialName,
MaterialNumber: item.MaterialNumber,
MaterialAttribute: item.MaterialAttribute,
MaterialCategory: item.MaterialCategory,
ProductMaterialExt: item.ProductMaterialExt,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithOperator(user),
}
return productMaterialRepository.Save(newProductMaterial)
}
// 物料分组
func (ptr *PGMaterialService) AddMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
var (
user *domain.User
org *domain.Org
err error
parent *domain.ProductMaterialGroup
newProductMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
productMaterialGroupDao *dao.ProductMaterialGroupDao
latestNumber string
total int
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
if item.Pid != 0 {
if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
return nil, fmt.Errorf("上级物料分组不存在")
}
}
if newProductMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || newProductMaterialGroup != nil {
return nil, fmt.Errorf("物料分组编码已存在")
}
productMaterialGroupDao, _ = dao.NewProductMaterialGroupDao(ptr.transactionContext)
latestNumber, total, err = productMaterialGroupDao.CurrentGroupLatestNumber(opt.CompanyId, item.Pid)
if err != nil {
return nil, err
}
newProductMaterialGroup = &domain.ProductMaterialGroup{
CompanyId: opt.CompanyId,
OrgId: opt.OrgId,
Pid: item.Pid,
//Path: item.GetPath(parent),
MaterialGroupName: item.MaterialGroupName,
MaterialGroupNumber: item.MaterialGroupNumber,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithOperator(user),
}
newProductMaterialGroup.MaterialGroupNumber = newProductMaterialGroup.GroupNumberComposeUp(parent, latestNumber, total)
newProductMaterialGroup, err = productMaterialGroupRepository.Save(newProductMaterialGroup)
return newProductMaterialGroup, err
}
func (ptr *PGMaterialService) UpdateMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
var (
user *domain.User
org *domain.Org
err error
//parent *domain.ProductMaterialGroup
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
//if item.ProductMaterialGroupId == item.Pid {
// return nil, fmt.Errorf("当前物料分组不能做为自己上级")
//}
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, fmt.Errorf("物料分组不存在")
}
//if item.Pid != productMaterialGroup.ProductMaterialGroupId && item.Pid != 0 {
// if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
// return nil, fmt.Errorf("上级物料分组不存在")
// }
//}
//if productMaterialGroup.MaterialGroupNumber != item.MaterialGroupNumber {
// if group, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || group != nil {
// return nil, fmt.Errorf("物料分组编码已存在")
// }
//}
//productMaterialGroup.MaterialGroupNumber = item.MaterialGroupNumber
productMaterialGroup.MaterialGroupName = item.MaterialGroupName
productMaterialGroup.UpdatedAt = item.UpdatedAt
productMaterialGroup.Ext = domain.NewExt(org.OrgName).WithOperator(user)
productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup)
return productMaterialGroup, err
}
func (ptr *PGMaterialService) AllMaterialGroupChild(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
groups domain.ProductMaterialGroups
)
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
_, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
if len(groups) == 0 || err != nil {
return nil, listId, err
}
// 先排序 sort pid,id asc
sort.Stable(groups)
var treeNodes = make([]utils.TreeNode, len(groups))
for i := 0; i < len(groups); i++ {
treeNodes[i] = groups[i]
}
tree := utils.NewTree(treeNodes)
child := tree.AllChildNode(productMaterialGroup)
var result = make([]*domain.ProductMaterialGroup, 0)
for i := range child {
if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
result = append(result, v)
listId = append(listId, v.ProductMaterialGroupId)
}
}
return result, listId, err
}
func (ptr *PGMaterialService) AllMaterialGroupParent(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
groups domain.ProductMaterialGroups
)
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
_, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
if len(groups) == 0 || err != nil {
return nil, listId, err
}
// 先排序 sort pid,id asc
sort.Stable(groups)
var treeNodes = make([]utils.TreeNode, len(groups))
for i := 0; i < len(groups); i++ {
treeNodes[i] = groups[i]
}
tree := utils.NewTree(treeNodes)
child := tree.TreeNodePaths(productMaterialGroup)
var result = make([]*domain.ProductMaterialGroup, 0)
for i := range child {
if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
result = append(result, v)
listId = append(listId, v.ProductMaterialGroupId)
}
}
return result, listId, err
}
func (ptr *PGMaterialService) AllMaterialGroupParentByBacktracking(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
pid = productMaterialGroupId
mapExists = make(map[int]int)
)
var result = make([]*domain.ProductMaterialGroup, 0)
for {
if pid == 0 {
break
}
if _, exists := mapExists[pid]; exists {
break
}
mapExists[pid] = pid
productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": pid, "allWithDeleted": "1"})
if err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
pid = productMaterialGroup.Pid
result = append([]*domain.ProductMaterialGroup{productMaterialGroup}, result...)
}
return result, listId, err
}
func NewPGMaterialService(transactionContext *pgTransaction.TransactionContext) (*PGMaterialService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PGMaterialService{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -180,6 +180,30 @@ func (ptr *PGProductRecordService) Approve(productRecordId int, approveUserId in
return struct{}{}, nil
}
// Approve 审核生产记录 (二级品审核)
func (ptr *PGProductRecordService) Cancel(productRecordId int) (interface{}, error) {
productRecordRepository, err := repository.NewProductRecordRepository(ptr.transactionContext)
var productRecord *domain.ProductRecord
productRecord, err = productRecordRepository.FindOne(map[string]interface{}{"productRecordId": productRecordId})
if err != nil {
return nil, err
}
if err = productRecord.Cancel(); err != nil {
return nil, err
}
if _, err = productRecordRepository.Save(productRecord); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// 发送Job
productRecord.ProductRecordInfo.Weigh = -productRecord.ProductRecordInfo.Weigh
if err = SendProductRecordStaticsJob(productRecord); err != nil {
return nil, err
}
return struct{}{}, nil
}
func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, approveUserId int, weight float64, status int) (interface{}, error) {
var productRecordRepository, _ = repository.NewProductRecordRepository(ptr.transactionContext)
var record *domain.ProductRecord
... ...
... ... @@ -11,7 +11,7 @@ import (
)
const (
ProductSection1 = "打料"
ProductSection1 = "制模" //打料更新为制模
ProductSection2 = "成型"
ProductSection3 = "穿串"
ProductSection4 = "包装"
... ... @@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext)
workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt)
if err == domain.ErrorNotFound {
workshopProductRecord = newWorkshopProductRecord(productRecord, productPlan)
workshopProductRecord = NewWorkshopProductRecord(productRecord, productPlan)
} else {
if err != nil {
log.Logger.Error(err.Error())
... ... @@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original))
workshopProductRecord.UpdateProductWeigh(productRecord)
// 打料 跟 成型工段的初始产能是批次的产能
if productRecord.WorkStation.SectionName == ProductSection1 && productRecord.WorkStation.SectionName == ProductSection2 {
workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
}
//if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
// workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
//}
if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
// TODO:异常处理
... ... @@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
return nil, nil
}
// newEmployeeProductRecord 员工生产记录
func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
// NewWorkshopProductRecord 车间生产记录
func NewWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
record := &domain.WorkshopProductRecord{
CompanyId: productRecord.CompanyId,
OrgId: productRecord.OrgId,
... ... @@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *
}
// 打料、成型有初始值
if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
record.ProductWeigh = productPlan.PlanDevoted.Weight
record.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
}
return record
}
... ...
... ... @@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d
// 封箱机、串串机需要定位到批次
if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi ||
datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local)
if plan, err = ptr.findDeviceProductPlan(companyId, orgId, workStation.WorkStationId, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
if plan, err = ptr.findProductPlanAndActive(companyId, orgId, workStation, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType})
} else {
planId = plan.PlanDispatchRecordExt.ProductPlanId
... ... @@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId,
}
// 查找设备的生产计划,如果计划没有上线的话将他上线
func (ptr *PGWorkshopDataConsumeService) findDeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
func (ptr *PGWorkshopDataConsumeService) findProductPlanAndActive(companyId, orgId int, workStation *domain.WorkStation, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext)
planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext)
var setPlanOnline = false
record, err := planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOnline)
record, err := planDispatchRecordDao.ProductPlanDispatchRecord(companyId, orgId, workStation.WorkStationId, date, productCode, 0)
// 未找到当前工段的调度计划,从计划管理查询是否有匹配记录,如果有在调度计划中上线
var productPlan *domain.ProductPlan
if err == domain.ErrorNotFound {
if record, err = planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOffline); err != nil {
return nil, err
} else {
setPlanOnline = true
if productPlan, err = planDispatchRecordDao.ProductPlan(companyId, orgId, workStation.WorkshopId, date, productCode); err == nil && productPlan != nil {
var productPlanDispatch = domain.NewProductPlanDispatchRecord(productPlan, workStation)
if productPlanDispatch, err = planDispatchRecordRepository.Save(productPlanDispatch); err != nil {
return nil, err
}
return productPlanDispatch, nil
}
return nil, err
}
if setPlanOnline {
record.ChangeStatus(domain.PlanOnline)
if err != nil {
return nil, err
}
if record != nil && record.PlanDispatchStatus == domain.PlanOffline {
if err = record.ChangeStatus(domain.PlanOnline); err != nil {
return nil, err
}
if record, err = planDispatchRecordRepository.Save(record); err != nil {
return nil, err
}
... ...
... ... @@ -48,6 +48,8 @@ func init() {
(*models.DeviceDailyRunningRecord)(nil),
(*models.DeviceRunningRecord)(nil),
(*models.WorkshopPlanCompletionRecord)(nil),
(*models.ProductMaterialGroup)(nil),
(*models.ProductMaterial)(nil),
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
... ...
... ... @@ -9,3 +9,13 @@ type MaterialGroupK3cloud struct {
ParentId int `comment:"父级id" pg:"parent_id"`
DataVersion int64 `comment:"数据版本" pg:"data_version"`
}
type MaterialGroupK3clouds []*MaterialGroupK3cloud
func (materialGroupK3clouds MaterialGroupK3clouds) ToMapId() map[int]*MaterialGroupK3cloud {
var result = make(map[int]*MaterialGroupK3cloud)
for i := range materialGroupK3clouds {
result[materialGroupK3clouds[i].Id] = materialGroupK3clouds[i]
}
return result
}
... ...
... ... @@ -25,6 +25,7 @@ type MaterialK3cloud struct {
UseOrgName string `comment:"使用组织" pg:"use_org_name"`
JoinProductId int64 `comment:"关联的product表id" pg:"join_product_id"`
DataVersion int64 `comment:"数据版本" pg:"data_version"`
FCategoryID string `pg:"-"`
}
//批量处理sql脚本样例
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"time"
)
type ProductMaterial struct {
tableName string `comment:"生产物料" pg:"manufacture.product_material"`
// 物料ID
ProductMaterialId int `comment:"物料ID" pg:"pk:product_material_id"`
// 企业id
CompanyId int `comment:"企业id"`
// 组织ID
OrgId int `comment:"组织ID"`
// 物料分组ID
ProductMaterialGroupId int `comment:"物料分组ID"`
// 物料编码
MaterialNumber string `comment:"物料编码"`
// 物料名称
MaterialName string `comment:"物料名称"`
// 物料属性
MaterialAttribute *domain.MaterialAttribute `comment:"物料属性"`
// 物料类别
MaterialCategory *domain.MaterialCategory `comment:"物料类别"`
// 物料扩展
ProductMaterialExt *domain.MaterialExt `comment:"物料扩展"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
// 扩展
Ext *domain.Ext `comment:"扩展"`
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"time"
)
type ProductMaterialGroup struct {
tableName string `comment:"物料分组" pg:"manufacture.product_material_group"`
// 物料分组ID
ProductMaterialGroupId int `comment:"物料分组ID" pg:"pk:product_material_group_id"`
// 企业id
CompanyId int `comment:"企业id"`
// 组织ID
OrgId int `comment:"组织ID"`
// 父级ID
Pid int `comment:"父级ID"`
// 路径
// Path string `comment:"路径"`
// 物料分组名称
MaterialGroupName string `comment:"物料分组名称"`
// 物料分组编码
MaterialGroupNumber string `comment:"物料分组编码"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
// 扩展
Ext *domain.Ext `comment:"扩展"`
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
func TransformToProductMaterialDomainModelFromPgModels(productMaterialModel *models.ProductMaterial) (*domain.ProductMaterial, error) {
return &domain.ProductMaterial{
ProductMaterialId: productMaterialModel.ProductMaterialId,
CompanyId: productMaterialModel.CompanyId,
OrgId: productMaterialModel.OrgId,
ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
MaterialNumber: productMaterialModel.MaterialNumber,
MaterialName: productMaterialModel.MaterialName,
MaterialAttribute: productMaterialModel.MaterialAttribute,
MaterialCategory: productMaterialModel.MaterialCategory,
ProductMaterialExt: productMaterialModel.ProductMaterialExt,
CreatedAt: productMaterialModel.CreatedAt,
UpdatedAt: productMaterialModel.UpdatedAt,
DeletedAt: productMaterialModel.DeletedAt,
Ext: productMaterialModel.Ext,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
func TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel *models.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
return &domain.ProductMaterialGroup{
ProductMaterialGroupId: productMaterialGroupModel.ProductMaterialGroupId,
CompanyId: productMaterialGroupModel.CompanyId,
OrgId: productMaterialGroupModel.OrgId,
Pid: productMaterialGroupModel.Pid,
//Path: productMaterialGroupModel.Path,
MaterialGroupName: productMaterialGroupModel.MaterialGroupName,
MaterialGroupNumber: productMaterialGroupModel.MaterialGroupNumber,
CreatedAt: productMaterialGroupModel.CreatedAt,
UpdatedAt: productMaterialGroupModel.UpdatedAt,
DeletedAt: productMaterialGroupModel.DeletedAt,
Ext: productMaterialGroupModel.Ext,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)
type ProductMaterialGroupRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ProductMaterialGroupRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *ProductMaterialGroupRepository) Save(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
sqlBuildFields := []string{
"product_material_group_id",
"company_id",
"org_id",
"pid",
//"path",
"material_group_name",
"material_group_number",
"created_at",
"updated_at",
"deleted_at",
"ext",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if productMaterialGroup.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterialGroup.ProductMaterialGroupId,
&productMaterialGroup.CompanyId,
&productMaterialGroup.OrgId,
&productMaterialGroup.Pid,
//&productMaterialGroup.Path,
&productMaterialGroup.MaterialGroupName,
&productMaterialGroup.MaterialGroupNumber,
&productMaterialGroup.CreatedAt,
&productMaterialGroup.UpdatedAt,
&productMaterialGroup.DeletedAt,
&productMaterialGroup.Ext,
),
fmt.Sprintf("INSERT INTO manufacture.product_material_group (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productMaterialGroup.CompanyId,
productMaterialGroup.OrgId,
productMaterialGroup.Pid,
//productMaterialGroup.Path,
productMaterialGroup.MaterialGroupName,
productMaterialGroup.MaterialGroupNumber,
productMaterialGroup.CreatedAt,
productMaterialGroup.UpdatedAt,
productMaterialGroup.Ext,
); err != nil {
return productMaterialGroup, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterialGroup.ProductMaterialGroupId,
&productMaterialGroup.CompanyId,
&productMaterialGroup.OrgId,
&productMaterialGroup.Pid,
//&productMaterialGroup.Path,
&productMaterialGroup.MaterialGroupName,
&productMaterialGroup.MaterialGroupNumber,
&productMaterialGroup.CreatedAt,
&productMaterialGroup.UpdatedAt,
&productMaterialGroup.DeletedAt,
&productMaterialGroup.Ext,
),
fmt.Sprintf("UPDATE manufacture.product_material_group SET %s WHERE product_material_group_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productMaterialGroup.CompanyId,
productMaterialGroup.OrgId,
productMaterialGroup.Pid,
//productMaterialGroup.Path,
productMaterialGroup.MaterialGroupName,
productMaterialGroup.MaterialGroupNumber,
productMaterialGroup.CreatedAt,
productMaterialGroup.UpdatedAt,
productMaterialGroup.Ext,
productMaterialGroup.Identify(),
); err != nil {
return productMaterialGroup, err
}
}
return productMaterialGroup, nil
}
func (repository *ProductMaterialGroupRepository) Remove(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
productMaterialGroupModel := new(models.ProductMaterialGroup)
productMaterialGroupModel.ProductMaterialGroupId = productMaterialGroup.Identify().(int)
if _, err := tx.Model(productMaterialGroupModel).WherePK().Delete(); err != nil {
return productMaterialGroup, err
}
return productMaterialGroup, nil
}
func (repository *ProductMaterialGroupRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
productMaterialGroupModel := new(models.ProductMaterialGroup)
query := sqlbuilder.BuildQuery(tx.Model(productMaterialGroupModel), queryOptions)
query.SetWhereByQueryOption("product_material_group_id = ?", "productMaterialGroupId")
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("material_group_number = ?", "materialGroupNumber")
if _, ok := queryOptions["allWithDeleted"]; ok {
query.AllWithDeleted()
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productMaterialGroupModel.ProductMaterialGroupId == 0 {
return nil, nil
} else {
return transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel)
}
}
func (repository *ProductMaterialGroupRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
var productMaterialGroupModels []*models.ProductMaterialGroup
productMaterialGroups := make([]*domain.ProductMaterialGroup, 0)
query := sqlbuilder.BuildQuery(tx.Model(&productMaterialGroupModels), queryOptions)
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetWhereByQueryOption("company_id = ?", "companyId")
if v, ok := queryOptions["orderByProductMaterialGroupId"]; ok {
query.SetOrderDirect("product_material_group_id", v.(string))
} else {
query.SetOrderDirect("product_material_group_id", "DESC")
}
if count, err := query.SelectAndCount(); err != nil {
return 0, productMaterialGroups, err
} else {
for _, productMaterialGroupModel := range productMaterialGroupModels {
if productMaterialGroup, err := transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel); err != nil {
return 0, productMaterialGroups, err
} else {
productMaterialGroups = append(productMaterialGroups, productMaterialGroup)
}
}
return int64(count), productMaterialGroups, nil
}
}
func NewProductMaterialGroupRepository(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialGroupRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)
type ProductMaterialRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ProductMaterialRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *ProductMaterialRepository) Save(productMaterial *domain.ProductMaterial) (*domain.ProductMaterial, error) {
sqlBuildFields := []string{
"product_material_id",
"company_id",
"org_id",
"product_material_group_id",
"material_number",
"material_name",
"material_attribute",
"material_category",
"product_material_ext",
"created_at",
"updated_at",
"deleted_at",
"ext",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if productMaterial.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterial.ProductMaterialId,
&productMaterial.CompanyId,
&productMaterial.OrgId,
&productMaterial.ProductMaterialGroupId,
&productMaterial.MaterialNumber,
&productMaterial.MaterialName,
&productMaterial.MaterialAttribute,
&productMaterial.MaterialCategory,
&productMaterial.ProductMaterialExt,
&productMaterial.CreatedAt,
&productMaterial.UpdatedAt,
&productMaterial.DeletedAt,
&productMaterial.Ext,
),
fmt.Sprintf("INSERT INTO manufacture.product_material (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productMaterial.CompanyId,
productMaterial.OrgId,
productMaterial.ProductMaterialGroupId,
productMaterial.MaterialNumber,
productMaterial.MaterialName,
productMaterial.MaterialAttribute,
productMaterial.MaterialCategory,
productMaterial.ProductMaterialExt,
productMaterial.CreatedAt,
productMaterial.UpdatedAt,
productMaterial.Ext,
); err != nil {
return productMaterial, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterial.ProductMaterialId,
&productMaterial.CompanyId,
&productMaterial.OrgId,
&productMaterial.ProductMaterialGroupId,
&productMaterial.MaterialNumber,
&productMaterial.MaterialName,
&productMaterial.MaterialAttribute,
&productMaterial.MaterialCategory,
&productMaterial.ProductMaterialExt,
&productMaterial.CreatedAt,
&productMaterial.UpdatedAt,
&productMaterial.DeletedAt,
&productMaterial.Ext,
),
fmt.Sprintf("UPDATE manufacture.product_material SET %s WHERE product_material_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productMaterial.CompanyId,
productMaterial.OrgId,
productMaterial.ProductMaterialGroupId,
productMaterial.MaterialNumber,
productMaterial.MaterialName,
productMaterial.MaterialAttribute,
productMaterial.MaterialCategory,
productMaterial.ProductMaterialExt,
productMaterial.CreatedAt,
productMaterial.UpdatedAt,
productMaterial.Ext,
productMaterial.Identify(),
); err != nil {
return productMaterial, err
}
}
return productMaterial, nil
}
func (repository *ProductMaterialRepository) Remove(productMaterial *domain.ProductMaterial) (*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
productMaterialModel := new(models.ProductMaterial)
productMaterialModel.ProductMaterialId = productMaterial.Identify().(int)
if _, err := tx.Model(productMaterialModel).WherePK().Delete(); err != nil {
return productMaterial, err
}
return productMaterial, nil
}
// query compose
// 1. company_id,material_number
func (repository *ProductMaterialRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
productMaterialModel := new(models.ProductMaterial)
query := sqlbuilder.BuildQuery(tx.Model(productMaterialModel), queryOptions)
query.SetWhereByQueryOption("product_material.product_material_id = ?", "productMaterialId")
query.SetWhereByQueryOption("product_material.company_id = ?", "companyId")
query.SetWhereByQueryOption("product_material.material_number = ?", "materialNumber")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productMaterialModel.ProductMaterialId == 0 {
return nil, nil
} else {
return transform.TransformToProductMaterialDomainModelFromPgModels(productMaterialModel)
}
}
func (repository *ProductMaterialRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
var productMaterialModels []*models.ProductMaterial
productMaterials := make([]*domain.ProductMaterial, 0)
query := sqlbuilder.BuildQuery(tx.Model(&productMaterialModels), queryOptions)
query.SetWhereByQueryOption("company_id = ?", "companyId")
if v, ok := queryOptions["productMaterialIds"]; ok && len(v.([]int)) > 0 {
query.Where("product_material_id in (?)", pg.In(v))
}
if v, ok := queryOptions["productMaterialGroupIds"]; ok && len(v.([]int)) > 0 {
query.Where("product_material_group_id in (?)", pg.In(v))
}
if v, ok := queryOptions["materialName"]; ok && v != "" {
query.Where("material_name like ?", fmt.Sprintf("%%%v%%", v))
}
if v, ok := queryOptions["materialCategory"]; ok && v != "" {
query.Where(fmt.Sprintf(`material_category->>'category' = '%v'`, v))
}
if v, ok := queryOptions["materialNumbers"]; ok && len(v.([]string)) > 0 {
query.Where("material_number in (?)", pg.In(v))
}
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("product_material_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, productMaterials, err
} else {
for _, productMaterialModel := range productMaterialModels {
if productMaterial, err := transform.TransformToProductMaterialDomainModelFromPgModels(productMaterialModel); err != nil {
return 0, productMaterials, err
} else {
productMaterials = append(productMaterials, productMaterial)
}
}
return int64(count), productMaterials, nil
}
}
func NewProductMaterialRepository(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -147,12 +147,18 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
query.SetWhereByQueryOption("product_record_type & ? >0", "productRecordType")
query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
query.SetWhereByQueryOption("work_station->>'lineId'='?'", "lineId")
query.SetWhereByQueryOption("work_station->>'sectionId'='?'", "sectionId")
if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int)) > 0 {
query.Where(`org_id in (?)`, pg.In(v))
}
if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_worker->>'userName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["productWorkerId"]; ok && v.(int) > 0 {
query.Where(`product_worker->>'userId' = '?'`, v)
}
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`work_station->>'workshopName' like '%%%v%%'`, v))
}
... ... @@ -180,6 +186,12 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
if v, ok := queryOptions["productPlanId"]; ok && v.(int) > 0 {
query.Where(fmt.Sprintf(`product_record_info->>'productPlanId' = '%v'`, v))
}
if v, ok := queryOptions["status"]; ok && v.(int) > 0 {
query.Where(fmt.Sprintf(`product_record_info->>'approveStatus' = '%v'`, v))
}
if v, ok := queryOptions["lastProductRecordId"]; ok && v.(int) > 0 {
query.Where(`product_record_id < ?`, v)
}
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("product_record_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
... ...
... ... @@ -2,6 +2,7 @@ package k3cloud
import (
"errors"
"fmt"
"io"
"time"
... ... @@ -87,3 +88,20 @@ func (c *Client) ExecuteBillQuery(param RequestExecuteBillQuery) (*BillQueryResu
queryResult := newBillQueryResult(dataByte, param.Data.FieldKeys)
return queryResult, queryResult.Error()
}
// ExecuteMetaDataQuery 元数据查询
func (c *Client) ExecuteMetaDataQuery(param RequestMetaDataQuery) ([]byte, error) {
api := "/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo.common.kdsvc"
resp, err := c.PostRequest(api, param)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var dataByte []byte
dataByte, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
fmt.Println("data ", string(dataByte))
return dataByte, nil
}
... ...
package k3cloud
import (
"fmt"
"strings"
"testing"
"time"
)
var (
... ... @@ -40,7 +42,7 @@ func TestExecuteBillQuery(t *testing.T) {
"FDocumentStatus", "FForbidStatus", "FErpClsID",
"FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
"FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName", "FCategoryID",
}
result, err := client.ExecuteBillQuery(RequestExecuteBillQuery{
FormId: "BD_MATERIAL",
... ... @@ -85,3 +87,52 @@ func TestExecuteBillQuery2(t *testing.T) {
return
}
}
func TestMetaDataQuery(t *testing.T) {
client, err := NewClient(hostUrl, acctID, username, password)
if err != nil {
t.Error(err)
return
}
inputs := []struct {
formId string
desc string
}{
{"BD_MATERIALCATEGORY", "货类别没"},
{"BD_MATERIALCATEGORY", "货类别没"},
}
for _, v := range inputs {
result, err := client.ExecuteMetaDataQuery(RequestMetaDataQuery{Data{FormId: v.formId}, v.formId})
if err != nil {
fmt.Println(err.Error())
}
t.Log(v.formId, v.desc, string(result))
}
time.Sleep(time.Second)
}
func TestExecuteMATERIALCATEGORYQuery(t *testing.T) {
client, err := NewClient(hostUrl, acctID, username, password)
if err != nil {
t.Error(err)
return
}
fieldKeys := []string{
"FName", "FNUMBER", "FMasterId",
}
result, err := client.ExecuteBillQuery(RequestExecuteBillQuery{
FormId: "PRD_MO",
Data: ExecuteBillQueryData{
FormId: "BD_MATERIALCATEGORY",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
//TopRowCount: 4,
FilterString: "",
},
})
t.Logf("result buf===> %s \n", string(result.Buf))
if err != nil {
t.Error(err)
return
}
}
... ...
... ... @@ -51,3 +51,13 @@ type (
Data ExecuteBillQueryData `json:"data"`
}
)
type (
RequestMetaDataQuery struct {
Data Data `json:"data"`
FormId string `json:"FormId"` //必录,查询表单元数据唯一标识
}
Data struct {
FormId string `json:"FormId"` //必录,查询表单元数据唯一标识
}
)
... ...