作者 yangfu

Merge branch 'test'

正在显示 85 个修改的文件 包含 3754 行增加190 行删除

要显示太多修改。

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

  1 +select count(*) from manufacture.device_running_record where device_running_record_id <=2000000
  2 +select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
  3 +
  4 +--1.备份设备运行数据-按数量
  5 +-- 备份数据 2000000
  6 +select * into table manufacture.device_running_record_0_2000
  7 +from manufacture.device_running_record
  8 +where device_running_record_id <=2000000
  9 +-- 删除数据
  10 +delete from manufacture.device_running_record where device_running_record_id <=2000000;
  11 +-- 重建索引
  12 +reindex table manufacture.device_running_record;
  13 +
  14 +
  15 +
  16 +--2.备份设备采集数据-按时间
  17 +-- 备份数据 2000000
  18 +select * into table manufacture.device_collections_history
  19 +from manufacture.device_collections
  20 +where created_at <'2022-6-01 16:00:00'
  21 +-- 删除数据
  22 +delete from manufacture.device_collections where created_at <'2022-6-01 16:00:00';
  23 +-- 重建索引
  24 +reindex table manufacture.device_collections;
  25 +
  26 +
  27 +--3.查看备份情况
  28 +select count(*) from manufacture.device_running_record_0_2000
  29 +select count(*) from manufacture.device_collections_history
  30 +select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
  1 +delete FROM "dictionarys" where dictionary_id in (3812266576427090944);
  2 +
  3 +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": "委外"}]');
  4 +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": "成品"}]');
  5 +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": "件"}]');
  6 +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": "装箱(件数)"}]');
  7 +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": "件"}]');
  1 +
  2 +-- 表product_material_group 增加唯一索引 idx_unq_product_material_group_company_id_org_id_material_group_number
  3 +
  4 +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);
  5 +
  6 +-- 表product_material 增加唯一索引 idx_unq_product_material_company_id_material_number
  7 +create UNIQUE INDEX idx_unq_product_material_company_id_material_number on manufacture.product_material using btree(company_id,material_number,deleted_at);
  8 +
  9 +
  10 +-- 菜单脚本
  11 +
  12 +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);
  13 +
  14 +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);
  15 +
  16 +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);
  17 +
  18 +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);
  19 +
  20 +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);
  21 +
  22 +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;
  23 +
  24 +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;
  25 +
  26 +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;
  27 +
  28 +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;
  1 +
  2 +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 (274, 42, '同步考勤机', 'ADMIN_SYSTEM-MANAGE_BASE_USER_SYNC', 'w1-1-1-1-9', 'button', '', 9, '同步考勤机', '7', '37,39,40,42', 1, 0, NULL);
  1 +apiVersion: v1
  2 +kind: Service
  3 +metadata:
  4 + name: allied-creation-manufacture
  5 + namespace: mmm-suplus-test
  6 + labels:
  7 + k8s-app: allied-creation-manufacture
  8 +spec:
  9 + ports:
  10 + - name: "http"
  11 + port: 80
  12 + targetPort: 8082
  13 + selector:
  14 + k8s-app: allied-creation-manufacture
  15 +---
  16 +apiVersion: extensions/v1beta1
  17 +kind: Deployment
  18 +metadata:
  19 + name: allied-creation-manufacture
  20 + namespace: mmm-suplus-test
  21 + labels:
  22 + k8s-app: allied-creation-manufacture
  23 +spec:
  24 + replicas: 1
  25 + template:
  26 + metadata:
  27 + labels:
  28 + k8s-app: allied-creation-manufacture
  29 + spec:
  30 + affinity:
  31 + nodeAffinity:
  32 + preferredDuringSchedulingIgnoredDuringExecution:
  33 + - preference: {}
  34 + weight: 100
  35 + requiredDuringSchedulingIgnoredDuringExecution:
  36 + nodeSelectorTerms:
  37 + - matchExpressions:
  38 + - key: kubernetes.io/hostname
  39 + operator: In
  40 + values:
  41 + - cn-hangzhou.i-bp1djh1xn7taumbue1ze
  42 + - cn-hangzhou.i-bp1djh1xn7taumbue1zd
  43 + - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
  44 + - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
  45 + containers:
  46 + - name: allied-creation-manufacture
  47 + image: 192.168.0.243:5000/mmm/allied-creation-manufacture:dev
  48 + imagePullPolicy: Always
  49 + ports:
  50 + - containerPort: 8082
  51 + env:
  52 + - name: POSTGRESQL_DB_NAME
  53 + valueFrom:
  54 + configMapKeyRef:
  55 + name: suplus-config
  56 + key: postgresqlalliedcreation.dbname
  57 + - name: POSTGRESQL_USER
  58 + valueFrom:
  59 + configMapKeyRef:
  60 + name: suplus-config
  61 + key: postgresql.user
  62 + - name: POSTGRESQL_PASSWORD
  63 + valueFrom:
  64 + configMapKeyRef:
  65 + name: suplus-config
  66 + key: postgresql.password
  67 + - name: POSTGRESQL_HOST
  68 + valueFrom:
  69 + configMapKeyRef:
  70 + name: suplus-config
  71 + key: postgresql.host
  72 + - name: POSTGRESQL_PORT
  73 + valueFrom:
  74 + configMapKeyRef:
  75 + name: suplus-config
  76 + key: postgresql.port
  77 + - name: REDIS_HOST
  78 + valueFrom:
  79 + configMapKeyRef:
  80 + name: suplus-config
  81 + key: redis.ip
  82 + - name: REDIS_PORT
  83 + valueFrom:
  84 + configMapKeyRef:
  85 + name: suplus-config
  86 + key: redis.port
  87 + - name: REDIS_AUTH
  88 + value: ""
  89 + - name: LOG_LEVEL
  90 + value: "debug"
  91 + - name: ERROR_BASE_CODE
  92 + value: "1"
  93 + - name: ERROR_BASE_CODE_MULTIPLE
  94 + value: "2000"
  95 + - name: ENABLE_KAFKA_LOG
  96 + value: "true"
  97 + - name: HTTP_PORT
  98 + value: "8082"
  99 + - name: SERVICE_ENV
  100 + value: "test"
  101 + - name: SUPLUS_ADMIN_BASE_HOST
  102 + value: "http://suplus-admin-base-dev.fjmaimaimai.com"
  103 + - name: ALLIED_CREATION_GATEWAY_HOST
  104 + value: "https://allied-creation-gateway-test.fjmaimaimai.com"
  105 + - name: ALLIED_CREATION_USER_HOST
  106 + value: "https://allied-creation-user-test.fjmaimaimai.com"
  107 + - name: ALLIED_CREATION_COOPERATION_HOST
  108 + value: "https://allied-creation-cooperation-test.fjmaimaimai.com"
  109 + - name: ALLIED_CREATION_BASIC_HOST
  110 + value: "https://allied-creation-basic-test.fjmaimaimai.com"
  111 + - name: ALLIED_CREATION_MANUFACTURE_HOST
  112 + value: "http://allied-creation-manufacture-test.fjmaimaimai.com"
  113 + - name: SMS_SERVE_HOST
  114 + value: "https://sms.fjmaimaimai.com:9897"
  115 + - name: SUPLUS_SALE_APP
  116 + value: "http://suplus-sale-app-gateway-test.fjmaimaimai.com"
  117 + - name: MANUFACTURE_DEFAULT_COMPANYID
  118 + value: "23"
  119 + - name: MANUFACTURE_DEFAULT_ORGID
  120 + value: "487"
  121 + - name: MANUFACTURE_DEFAULT_WORKSHOPID
  122 + value: "28"
  123 + - name: MANUFACTURE_PRODUCT_TYPE
  124 + value: "SG,SG"
  125 + - name: MQTT_HOST
  126 + value: "47.97.5.102"
  127 + - name: MQTT_PORT
  128 + value: "6000"
  129 + - name: MQTT_UP
  130 + value: "false"
@@ -125,4 +125,6 @@ spec: @@ -125,4 +125,6 @@ spec:
125 - name: MQTT_HOST 125 - name: MQTT_HOST
126 value: "47.97.5.102" 126 value: "47.97.5.102"
127 - name: MQTT_PORT 127 - name: MQTT_PORT
128 - value: "6000"  
  128 + value: "6000"
  129 + - name: MQTT_UP
  130 + value: "false"
@@ -3,6 +3,7 @@ package main @@ -3,6 +3,7 @@ package main
3 import ( 3 import (
4 "fmt" 4 "fmt"
5 "github.com/beego/beego/v2/server/web" 5 "github.com/beego/beego/v2/server/web"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant" 7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis" 8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log" 9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
@@ -10,7 +11,6 @@ import ( @@ -10,7 +11,6 @@ import (
10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task"
11 "time" 12 "time"
12 13
13 - "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"  
14 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant" 14 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
15 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg" 15 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
16 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis" 16 _ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
@@ -29,8 +29,9 @@ func main() { @@ -29,8 +29,9 @@ func main() {
29 redis.InitRedis() 29 redis.InitRedis()
30 log.Logger.Info("server start ....") 30 log.Logger.Info("server start ....")
31 log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG)) 31 log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG))
32 -  
33 - go mqtt.Start(log.Logger) 32 + if constant.MQTT_UP {
  33 + go mqtt.Start(log.Logger)
  34 + }
34 go task.Run() 35 go task.Run()
35 cron := crontab.NewCrontabService(nil) 36 cron := crontab.NewCrontabService(nil)
36 cron.StartCrontabTask() 37 cron.StartCrontabTask()
@@ -18,25 +18,28 @@ func NewCrontabService(options map[string]interface{}) *CrontabService { @@ -18,25 +18,28 @@ func NewCrontabService(options map[string]interface{}) *CrontabService {
18 } 18 }
19 19
20 func (crontabService *CrontabService) initTask() { 20 func (crontabService *CrontabService) initTask() {
21 - //拉取物料数据 每5分执行  
22 - pullMaterialK3cloud := task.NewTask("pullMaterialK3cloud", "0 */5 0 * * *", func(ctx context.Context) error { 21 + //拉取物料数据 每4小时执行
  22 + pullMaterialK3cloud := task.NewTask("pullMaterialK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
23 srv := syncdata.PullDataK3CloudService{} 23 srv := syncdata.PullDataK3CloudService{}
24 return srv.PullMaterialNewest() 24 return srv.PullMaterialNewest()
25 }) 25 })
26 task.AddTask("pullMaterialK3cloud", pullMaterialK3cloud) 26 task.AddTask("pullMaterialK3cloud", pullMaterialK3cloud)
27 - //拉取物料分组数据 每5分执行  
28 - pullMaterialGroupK3cloud := task.NewTask("pullMaterialGroupK3cloud", "0 */5 0 * * *", func(ctx context.Context) error { 27 + //拉取物料分组数据 每4小时执行
  28 + pullMaterialGroupK3cloud := task.NewTask("pullMaterialGroupK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
29 srv := syncdata.PullDataK3CloudService{} 29 srv := syncdata.PullDataK3CloudService{}
30 return srv.PullMaterialGroup() 30 return srv.PullMaterialGroup()
31 }) 31 })
32 task.AddTask("pullMaterialGroupK3cloud", pullMaterialGroupK3cloud) 32 task.AddTask("pullMaterialGroupK3cloud", pullMaterialGroupK3cloud)
33 - //拉取订生产订单数据 每5分执行  
34 - PullPrdMoK3cloud := task.NewTask("PullPrdMoK3cloud", "0 */5 0 * * *", func(ctx context.Context) error { 33 + //拉取订生产订单数据 每4小时执行
  34 + PullPrdMoK3cloud := task.NewTask("PullPrdMoK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
35 srv := syncdata.PullDataK3CloudService{} 35 srv := syncdata.PullDataK3CloudService{}
36 return srv.PullPrdMoNewest() 36 return srv.PullPrdMoNewest()
37 }) 37 })
38 task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud) 38 task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud)
39 39
  40 + autoInitWorkshopProductRecord := task.NewTask("AutoInitWorkshopProductRecord", "0 0 */4 * * *", AutoInitWorkshopProductRecord)
  41 + task.AddTask("AutoInitWorkshopProductRecord", autoInitWorkshopProductRecord)
  42 +
40 autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord) 43 autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord)
41 task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord) 44 task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord)
42 45
@@ -60,6 +63,12 @@ func (crontabService *CrontabService) initTask() { @@ -60,6 +63,12 @@ func (crontabService *CrontabService) initTask() {
60 63
61 syncProductPlan := task.NewTask("定时同步车间计划", "0 5 * * * *", SyncProductPlan) 64 syncProductPlan := task.NewTask("定时同步车间计划", "0 5 * * * *", SyncProductPlan)
62 task.AddTask("SyncProductPlan", syncProductPlan) 65 task.AddTask("SyncProductPlan", syncProductPlan)
  66 +
  67 + syncMaterialGroup := task.NewTask("定时同步物料分组", "0 0 0/2 * * *", SyncMaterialGroup)
  68 + task.AddTask("syncMaterialGroup", syncMaterialGroup)
  69 +
  70 + syncMaterial := task.NewTask("定时同步物料", "0 0 0/2 * * *", SyncMaterial)
  71 + task.AddTask("syncMaterial", syncMaterial)
63 } 72 }
64 73
65 func (crontabService *CrontabService) StartCrontabTask() { 74 func (crontabService *CrontabService) StartCrontabTask() {
@@ -41,7 +41,7 @@ func AutoApproveProductRecord(ctx context.Context) error { @@ -41,7 +41,7 @@ func AutoApproveProductRecord(ctx context.Context) error {
41 41
42 approveAttendanceRecordsService, _ := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext)) 42 approveAttendanceRecordsService, _ := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
43 43
44 - if _, err = approveAttendanceRecordsService.BatchApprove(records, 0, 0, domain.AttendanceAutoApproved); err != nil { 44 + if _, err = approveAttendanceRecordsService.BatchApprove(records, 0, 0, domain.ProductRecordAutoApproved); err != nil {
45 log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时审核生产记录"}) 45 log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时审核生产记录"})
46 return err 46 return err
47 } 47 }
  1 +package crontab
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 + "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
  13 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  15 + "time"
  16 +)
  17 +
  18 +// AutoInitWorkshopProductRecord 自动初始化车间生产记录
  19 +func AutoInitWorkshopProductRecord(ctx context.Context) error {
  20 + defer func() {
  21 + if r := recover(); r != nil {
  22 + log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "自动初始化车间生产记录"})
  23 + }
  24 + }()
  25 + transactionContext, err := factory.CreateTransactionContext(nil)
  26 + if err != nil {
  27 + return err
  28 + }
  29 + if err := transactionContext.StartTransaction(); err != nil {
  30 + return err
  31 + }
  32 + defer func() {
  33 + if err != nil {
  34 + log.Logger.Error("【自动初始化车间生产记录】 失败:" + err.Error())
  35 + }
  36 + transactionContext.RollbackTransaction()
  37 + }()
  38 + log.Logger.Debug("【自动初始化车间生产记录】 启动")
  39 + _, workshop, err := factory.FastPgWorkshop(transactionContext, constant.MANUFACTURE_DEFAULT_WORKSHOPID)
  40 + if err != nil {
  41 + return err
  42 + }
  43 + productPlanDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(transactionContext.(*pg.TransactionContext))
  44 + productPlans, err := productPlanDispatchRecordDao.ProductPlans(constant.MANUFACTURE_DEFAULT_COMPANYID,
  45 + constant.MANUFACTURE_DEFAULT_ORGID,
  46 + constant.MANUFACTURE_DEFAULT_WORKSHOPID,
  47 + utils.GetZeroTimeWithLocal(time.Now(), time.UTC), "")
  48 + if err != nil {
  49 + return err
  50 + }
  51 + if len(productPlans) == 0 {
  52 + log.Logger.Debug("【自动初始化车间生产记录】 当天执行计划为空")
  53 + return nil
  54 + }
  55 + workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(transactionContext.(*pg.TransactionContext))
  56 + workshopProductRecordRepository, _ := repository.NewWorkshopProductRecordRepository(transactionContext.(*pg.TransactionContext))
  57 + lines := workshop.GetProductLines(domain.NotDeleted)
  58 + for _, line := range lines {
  59 + for _, section := range line.ProductSections {
  60 + if !(section.SectionName == domain.ProductSection1 || section.SectionName == domain.ProductSection2) {
  61 + continue
  62 + }
  63 + if section.Removed == domain.Deleted {
  64 + continue
  65 + }
  66 + workstation := domain.NewWorkStation(workshop, line, section)
  67 + cid := constant.MANUFACTURE_DEFAULT_COMPANYID
  68 + oid := constant.MANUFACTURE_DEFAULT_ORGID
  69 + for _, plan := range productPlans {
  70 + var workshopProductRecord *domain.WorkshopProductRecord
  71 + workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, workstation.WorkStationId, plan.ProductPlanId, time.Now())
  72 + if err == domain.ErrorNotFound {
  73 + productRecord := &domain.ProductRecord{
  74 + CompanyId: constant.MANUFACTURE_DEFAULT_COMPANYID,
  75 + OrgId: constant.MANUFACTURE_DEFAULT_ORGID,
  76 + WorkStation: workstation,
  77 + CreatedAt: time.Now(),
  78 + ProductRecordInfo: &domain.ProductRecordInfo{
  79 + ProductPlanId: plan.ProductPlanId,
  80 + PlanProductName: plan.PlanProductName,
  81 + BatchNumber: plan.BatchNumber,
  82 + },
  83 + }
  84 + workshopProductRecord = domainService.NewWorkshopProductRecord(productRecord, plan)
  85 + workshopProductRecord.UpdateProductWeigh(productRecord)
  86 + if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
  87 + return err
  88 + }
  89 + log.Logger.Debug(fmt.Sprintf("【自动初始化车间生产记录】 工位:%v(%v) 初始产能:%v kg 日期:%v ID:%v",
  90 + workshopProductRecord.WorkStation.WorkStationId, workshopProductRecord.WorkStation.SectionName,
  91 + workshopProductRecord.ProductWeigh, workshopProductRecord.ProductRecordInfo.ProductDate, workshopProductRecord.WorkshopProductRecordId))
  92 + continue
  93 + }
  94 + if err != nil {
  95 + log.Logger.Error(err.Error())
  96 + return nil
  97 + }
  98 + }
  99 + }
  100 + }
  101 + if err = transactionContext.CommitTransaction(); err != nil {
  102 + return err
  103 + }
  104 + return nil
  105 +}
  1 +package crontab
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 + "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  10 + "runtime/debug"
  11 + "time"
  12 +)
  13 +
  14 +// SyncMaterial 定时同步物料
  15 +func SyncMaterial(ctx context.Context) error {
  16 + defer func() {
  17 + if r := recover(); r != nil {
  18 + log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料", "stack": string(debug.Stack())})
  19 + }
  20 + }()
  21 + transactionContext, err := factory.CreateTransactionContext(nil)
  22 + if err != nil {
  23 + return err
  24 + }
  25 + if err := transactionContext.StartTransaction(); err != nil {
  26 + return err
  27 + }
  28 + defer func() {
  29 + if err != nil {
  30 + log.Logger.Error("【定时同步物料】 失败:" + err.Error())
  31 + }
  32 + transactionContext.RollbackTransaction()
  33 + }()
  34 + var pullType string = ""
  35 + if val := ctx.Value("pullType"); val != nil {
  36 + pullType = val.(string)
  37 + }
  38 + log.Logger.Debug("【定时同步物料】 启动")
  39 + pullK3CloudService := syncdata.PullDataK3CloudService{}
  40 + if err := pullK3CloudService.SyncDataMaterial(transactionContext.(*pg.TransactionContext), pullType, time.Time{}); err != nil {
  41 + log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料"})
  42 + return nil
  43 + }
  44 + if err = transactionContext.CommitTransaction(); err != nil {
  45 + return err
  46 + }
  47 + return nil
  48 +}
  1 +package crontab
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 + "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  10 + "runtime/debug"
  11 +)
  12 +
  13 +// SyncMaterialGroup 定时同步物料分组
  14 +func SyncMaterialGroup(ctx context.Context) error {
  15 + defer func() {
  16 + if r := recover(); r != nil {
  17 + log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料分组", "stack": string(debug.Stack())})
  18 + }
  19 + }()
  20 + transactionContext, err := factory.CreateTransactionContext(nil)
  21 + if err != nil {
  22 + return err
  23 + }
  24 + if err := transactionContext.StartTransaction(); err != nil {
  25 + return err
  26 + }
  27 + defer func() {
  28 + if err != nil {
  29 + log.Logger.Error("【定时同步物料分组】 失败:" + err.Error())
  30 + }
  31 + transactionContext.RollbackTransaction()
  32 + }()
  33 +
  34 + log.Logger.Debug("【定时同步物料分组】 启动")
  35 + pullK3CloudService := syncdata.PullDataK3CloudService{}
  36 + if err := pullK3CloudService.SyncDataMaterialGroup(transactionContext.(*pg.TransactionContext)); err != nil {
  37 + log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料分组"})
  38 + return nil
  39 + }
  40 + if err = transactionContext.CommitTransaction(); err != nil {
  41 + return err
  42 + }
  43 + return nil
  44 +}
@@ -413,6 +413,58 @@ func FastPgDeviceDailyRunningRecord(transactionContext application.TransactionCo @@ -413,6 +413,58 @@ func FastPgDeviceDailyRunningRecord(transactionContext application.TransactionCo
413 return rep, mod, err 413 return rep, mod, err
414 } 414 }
415 415
  416 +// FastProductMaterialGroup 快速返回物料
  417 +//
  418 +// transactionContext 事务
  419 +// id 对象唯一标识
  420 +func FastProductMaterialGroup(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialGroupRepository, *domain.ProductMaterialGroup, error) {
  421 + var rep domain.ProductMaterialGroupRepository
  422 + var mod *domain.ProductMaterialGroup
  423 + var err error
  424 + if value, err := CreateProductMaterialGroupRepository(map[string]interface{}{
  425 + "transactionContext": transactionContext,
  426 + }); err != nil {
  427 + return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  428 + } else {
  429 + rep = value
  430 + }
  431 + if id > 0 {
  432 + if mod, err = rep.FindOne(map[string]interface{}{"productMaterialGroupId": id}); err != nil {
  433 + if err == domain.ErrorNotFound {
  434 + return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
  435 + }
  436 + return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  437 + }
  438 + }
  439 + return rep, mod, err
  440 +}
  441 +
  442 +// FastProductMaterialGroup 快速返回物料
  443 +//
  444 +// transactionContext 事务
  445 +// id 对象唯一标识
  446 +func FastProductMaterial(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialRepository, *domain.ProductMaterial, error) {
  447 + var rep domain.ProductMaterialRepository
  448 + var mod *domain.ProductMaterial
  449 + var err error
  450 + if value, err := CreateProductMaterialRepository(map[string]interface{}{
  451 + "transactionContext": transactionContext,
  452 + }); err != nil {
  453 + return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  454 + } else {
  455 + rep = value
  456 + }
  457 + if id > 0 {
  458 + if mod, err = rep.FindOne(map[string]interface{}{"productMaterialId": id}); err != nil {
  459 + if err == domain.ErrorNotFound {
  460 + return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
  461 + }
  462 + return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  463 + }
  464 + }
  465 + return rep, mod, err
  466 +}
  467 +
416 /***** 2.配置 *****/ 468 /***** 2.配置 *****/
417 469
418 type FastOptions struct { 470 type FastOptions struct {
@@ -141,3 +141,19 @@ func CreateDeviceDailyRunningRecordRepository(options map[string]interface{}) (d @@ -141,3 +141,19 @@ func CreateDeviceDailyRunningRecordRepository(options map[string]interface{}) (d
141 } 141 }
142 return repository.NewDeviceDailyRunningRecordRepository(transactionContext) 142 return repository.NewDeviceDailyRunningRecordRepository(transactionContext)
143 } 143 }
  144 +
  145 +func CreateProductMaterialGroupRepository(options map[string]interface{}) (domain.ProductMaterialGroupRepository, error) {
  146 + var transactionContext *pg.TransactionContext
  147 + if value, ok := options["transactionContext"]; ok {
  148 + transactionContext = value.(*pg.TransactionContext)
  149 + }
  150 + return repository.NewProductMaterialGroupRepository(transactionContext)
  151 +}
  152 +
  153 +func CreateProductMaterialRepository(options map[string]interface{}) (domain.ProductMaterialRepository, error) {
  154 + var transactionContext *pg.TransactionContext
  155 + if value, ok := options["transactionContext"]; ok {
  156 + transactionContext = value.(*pg.TransactionContext)
  157 + }
  158 + return repository.NewProductMaterialRepository(transactionContext)
  159 +}
@@ -14,19 +14,15 @@ type CreateProductCommand struct { @@ -14,19 +14,15 @@ type CreateProductCommand struct {
14 // 组织ID 14 // 组织ID
15 OrgId int `cname:"组织ID" json:"orgId" valid:"Required"` 15 OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
16 // 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001 16 // 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
17 - ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"` 17 + ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode" valid:"Required"`
18 // 产品名称 18 // 产品名称
19 - ProductName string `cname:"产品名称" json:"productName" valid:"Required"` 19 + // ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
20 // 产品类别 20 // 产品类别
21 - ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`  
22 - // 数量(保留两位小数)  
23 - //Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"` 21 + // ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
24 // 单位 22 // 单位
25 - Unit string `cname:"单位" json:"unit" valid:"Required"` 23 + // Unit string `cname:"单位" json:"unit" valid:"Required"`
26 // 单份重量(原材料) 24 // 单份重量(原材料)
27 UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"` 25 UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
28 - // 重量  
29 - //Weight float64 `cname:"重量" json:"weight" valid:"Required"`  
30 } 26 }
31 27
32 func (createProductCommand *CreateProductCommand) Valid(validation *validation.Validation) { 28 func (createProductCommand *CreateProductCommand) Valid(validation *validation.Validation) {
@@ -12,19 +12,15 @@ type UpdateProductCommand struct { @@ -12,19 +12,15 @@ type UpdateProductCommand struct {
12 // 产品ID 12 // 产品ID
13 ProductId int `cname:"产品ID" json:"productId" valid:"Required"` 13 ProductId int `cname:"产品ID" json:"productId" valid:"Required"`
14 // 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001 14 // 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
15 - ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"` 15 + //ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
16 // 产品名称 16 // 产品名称
17 - ProductName string `cname:"产品名称" json:"productName" valid:"Required"` 17 + ProductName string `cname:"产品名称" json:"productName" `
18 // 产品类别 18 // 产品类别
19 - ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`  
20 - // 数量(保留两位小数)  
21 - //Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"` 19 + ProductCategory string `cname:"产品类别" json:"productCategory"`
22 // 单位 20 // 单位
23 - Unit string `cname:"单位" json:"unit" valid:"Required"` 21 + Unit string `cname:"单位" json:"unit"`
24 // 单份重量(原材料) 22 // 单份重量(原材料)
25 UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"` 23 UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
26 - // 重量  
27 - //Weight float64 `cname:"重量" json:"weight" valid:"Required"`  
28 } 24 }
29 25
30 func (updateProductCommand *UpdateProductCommand) Valid(validation *validation.Validation) { 26 func (updateProductCommand *UpdateProductCommand) Valid(validation *validation.Validation) {
@@ -14,7 +14,6 @@ import ( @@ -14,7 +14,6 @@ import (
14 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis" 14 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
16 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log" 16 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
17 - "time"  
18 ) 17 )
19 18
20 // 产品服务 19 // 产品服务
@@ -22,7 +21,7 @@ type ProductService struct { @@ -22,7 +21,7 @@ type ProductService struct {
22 } 21 }
23 22
24 // 创建产品服务 23 // 创建产品服务
25 -func (productService *ProductService) CreateProduct(createProductCommand *command.CreateProductCommand) (interface{}, error) { 24 +func (productService *ProductService) CreateProduct(opt *domain.OperateInfo, createProductCommand *command.CreateProductCommand) (interface{}, error) {
26 if err := createProductCommand.ValidateCommand(); err != nil { 25 if err := createProductCommand.ValidateCommand(); err != nil {
27 return nil, application.ThrowError(application.ARG_ERROR, err.Error()) 26 return nil, application.ThrowError(application.ARG_ERROR, err.Error())
28 } 27 }
@@ -37,50 +36,23 @@ func (productService *ProductService) CreateProduct(createProductCommand *comman @@ -37,50 +36,23 @@ func (productService *ProductService) CreateProduct(createProductCommand *comman
37 transactionContext.RollbackTransaction() 36 transactionContext.RollbackTransaction()
38 }() 37 }()
39 38
40 - if len(createProductCommand.ProductCode) == 0 {  
41 - generator := redis.NewProductCodeCache(createProductCommand.CompanyId)  
42 - code, err := redis.GenCode(generator)  
43 - if err != nil {  
44 - log.Logger.Error(err.Error())  
45 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")  
46 - }  
47 - createProductCommand.ProductCode = code 39 + batchAddProductService, _ := domainService.NewPGBatchAddProductService(transactionContext.(*pgTransaction.TransactionContext))
  40 + item := &domain.ImportProductItem{
  41 + ProductCode: createProductCommand.ProductCode,
  42 + UnitWeight: utils.AssertString(createProductCommand.UnitWeight),
48 } 43 }
49 - var userService = domainService.NewUserService()  
50 - var org *domain.Org  
51 - org, err = userService.Organization(createProductCommand.OrgId)  
52 - if err != nil {  
53 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 44 + if _, err = batchAddProductService.BatchAddProduct(opt, []*domain.ImportProductItem{
  45 + item,
  46 + }, false); err != nil {
  47 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
54 } 48 }
55 -  
56 - newProduct := &domain.Product{  
57 - CompanyId: createProductCommand.CompanyId,  
58 - OrgId: createProductCommand.OrgId,  
59 - ProductCode: createProductCommand.ProductCode,  
60 - ProductName: createProductCommand.ProductName,  
61 - ProductCategory: createProductCommand.ProductCategory,  
62 - ProductSpec: &domain.UnitQuantity{  
63 - Unit: createProductCommand.Unit,  
64 - UnitWeight: createProductCommand.UnitWeight,  
65 - },  
66 - CreatedAt: time.Now(),  
67 - UpdatedAt: time.Now(),  
68 - Ext: domain.NewExt(org.OrgName),  
69 - }  
70 - productRepository, _, _ := factory.FastPgProduct(transactionContext, 0)  
71 -  
72 - if item, err := productRepository.FindOne(map[string]interface{}{"companyId": createProductCommand.CompanyId, "productCode": createProductCommand.ProductCode}); err == nil && item != nil {  
73 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交") 49 + if len(item.FailReason) > 0 {
  50 + return nil, application.ThrowError(application.TRANSACTION_ERROR, item.FailReason)
74 } 51 }
75 -  
76 - if product, err := productRepository.Save(newProduct); err != nil {  
77 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())  
78 - } else {  
79 - if err := transactionContext.CommitTransaction(); err != nil {  
80 - return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())  
81 - }  
82 - return product, nil 52 + if err := transactionContext.CommitTransaction(); err != nil {
  53 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
83 } 54 }
  55 + return struct{}{}, nil
84 } 56 }
85 57
86 // 返回产品服务 58 // 返回产品服务
@@ -242,7 +214,7 @@ func (productService *ProductService) BatchRemoveProduct(cmd *command.BatchRemov @@ -242,7 +214,7 @@ func (productService *ProductService) BatchRemoveProduct(cmd *command.BatchRemov
242 } 214 }
243 215
244 // 更新产品服务 216 // 更新产品服务
245 -func (productService *ProductService) UpdateProduct(updateProductCommand *command.UpdateProductCommand) (interface{}, error) { 217 +func (productService *ProductService) UpdateProduct(opt *domain.OperateInfo, updateProductCommand *command.UpdateProductCommand) (interface{}, error) {
246 if err := updateProductCommand.ValidateCommand(); err != nil { 218 if err := updateProductCommand.ValidateCommand(); err != nil {
247 return nil, application.ThrowError(application.ARG_ERROR, err.Error()) 219 return nil, application.ThrowError(application.ARG_ERROR, err.Error())
248 } 220 }
@@ -260,19 +232,11 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman @@ -260,19 +232,11 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
260 if err != nil { 232 if err != nil {
261 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 233 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
262 } 234 }
263 - if len(updateProductCommand.ProductCode) == 0 {  
264 - generator := redis.NewProductCodeCache(product.CompanyId)  
265 - code, err := redis.GenCode(generator)  
266 - if err != nil {  
267 - log.Logger.Error(err.Error())  
268 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")  
269 - }  
270 - updateProductCommand.ProductCode = code  
271 - }  
272 - if updateProductCommand.ProductCode != product.ProductCode {  
273 - if item, err := productRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "productCode": updateProductCommand.ProductCode}); err == nil && item != nil {  
274 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交")  
275 - } 235 +
  236 + var material *domain.ProductMaterial
  237 + productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
  238 + if material, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "materialNumber": product.ProductCode}); err != nil || material == nil {
  239 + return nil, application.ThrowError(application.BUSINESS_ERROR, "物料不存在")
276 } 240 }
277 241
278 var userService = domainService.NewUserService() 242 var userService = domainService.NewUserService()
@@ -281,8 +245,13 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman @@ -281,8 +245,13 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
281 if err != nil { 245 if err != nil {
282 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 246 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
283 } 247 }
  248 +
  249 + updateProductCommand.ProductName = material.MaterialName
  250 + updateProductCommand.Unit = material.ProductMaterialExt.Unit
  251 + updateProductCommand.ProductCategory = material.MaterialCategory.Category
284 data := tool_funs.SimpleStructToMap(updateProductCommand) 252 data := tool_funs.SimpleStructToMap(updateProductCommand)
285 data["orgName"] = org.OrgName 253 data["orgName"] = org.OrgName
  254 +
286 if err := product.Update(data); err != nil { 255 if err := product.Update(data); err != nil {
287 return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error()) 256 return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
288 } 257 }
@@ -73,7 +73,7 @@ func (d *ProductGroupEmployeesDtos) LoadDto(groups ...*domain.ProductGroup) { @@ -73,7 +73,7 @@ func (d *ProductGroupEmployeesDtos) LoadDto(groups ...*domain.ProductGroup) {
73 } 73 }
74 } 74 }
75 75
76 -func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRecord, mapGroupUser map[string]*domain.User, keyFunc func(int) string) { 76 +func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRecord, mapGroupUser map[string]*domain.User, keyFunc func(int) string, checkUserEnableFunc func(int) bool) {
77 var mapUser = make(map[int]int) 77 var mapUser = make(map[int]int)
78 // 打卡的用户 78 // 打卡的用户
79 for _, v := range list { 79 for _, v := range list {
@@ -83,6 +83,9 @@ func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRe @@ -83,6 +83,9 @@ func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRe
83 item.ProductGroupId = 0 83 item.ProductGroupId = 0
84 item.GroupName = "" 84 item.GroupName = ""
85 item.Online = true 85 item.Online = true
  86 + if enable := checkUserEnableFunc(item.UserId); !enable {
  87 + continue
  88 + }
86 if v, ok := mapGroupUser[keyFunc(item.UserId)]; ok { 89 if v, ok := mapGroupUser[keyFunc(item.UserId)]; ok {
87 item.GroupName = v.GroupName 90 item.GroupName = v.GroupName
88 item.ProductGroupId = v.GroupId 91 item.ProductGroupId = v.GroupId
@@ -107,6 +110,9 @@ func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRe @@ -107,6 +110,9 @@ func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRe
107 item.UserName = v.UserName 110 item.UserName = v.UserName
108 item.ProductGroupId = v.GroupId 111 item.ProductGroupId = v.GroupId
109 item.GroupName = v.GroupName 112 item.GroupName = v.GroupName
  113 + if enable := checkUserEnableFunc(item.UserId); !enable {
  114 + continue
  115 + }
110 mapUser[item.UserId] = item.UserId 116 mapUser[item.UserId] = item.UserId
111 d.Append(item) 117 d.Append(item)
112 } 118 }
@@ -11,6 +11,7 @@ import ( @@ -11,6 +11,7 @@ import (
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService" 12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
14 "sort" 15 "sort"
15 "strings" 16 "strings"
16 "time" 17 "time"
@@ -491,7 +492,20 @@ func (productGroupService *ProductGroupService) SearchProductGroupEmployeesV2(op @@ -491,7 +492,20 @@ func (productGroupService *ProductGroupService) SearchProductGroupEmployeesV2(op
491 productGroupRepository, _, _ := factory.FastPgProductGroup(transactionContext, 0) 492 productGroupRepository, _, _ := factory.FastPgProductGroup(transactionContext, 0)
492 mapUser, keyFunc := domainService.FindGroupMembers(productGroupRepository, cmd.CompanyId, cmd.OrgId, domain.WorkstationKey(cmd.WorkshopId, cmd.LineId, cmd.SectionId)) 493 mapUser, keyFunc := domainService.FindGroupMembers(productGroupRepository, cmd.CompanyId, cmd.OrgId, domain.WorkstationKey(cmd.WorkshopId, cmd.LineId, cmd.SectionId))
493 var results = dto.NewProductGroupEmployeesDtos() 494 var results = dto.NewProductGroupEmployeesDtos()
494 - results.LoadDtoV2(productGroups, mapUser, keyFunc) 495 +
  496 + userService := domainService.NewUserService()
  497 + checkUserEnableFunc := func(userId int) bool {
  498 + user, err := userService.User(userId)
  499 + if err != nil {
  500 + return false
  501 + }
  502 + if user.EnableStatus == int(domain.UserStatusEnable) {
  503 + return true
  504 + }
  505 + log.Logger.Debug(fmt.Sprintf("ID:%d 用户:%s 状态:%d 已被禁用,过滤", user.UserId, user.UserName, user.EnableStatus))
  506 + return false
  507 + }
  508 + results.LoadDtoV2(productGroups, mapUser, keyFunc, checkUserEnableFunc)
495 sort.Stable(results) 509 sort.Stable(results)
496 if err := transactionContext.CommitTransaction(); err != nil { 510 if err := transactionContext.CommitTransaction(); err != nil {
497 return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error()) 511 return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type BatchRemoveProductMaterialCommand struct {
  12 + // 物料ID们
  13 + ProductMaterialIds []int `cname:"物料ID" json:"productMaterialIds" valid:"Required"`
  14 +}
  15 +
  16 +func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) Valid(validation *validation.Validation) {
  17 + //validation.SetError("CustomValid", "未实现的自定义认证")
  18 +}
  19 +
  20 +func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) ValidateCommand() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(batchRemoveProductMaterialCommand)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(batchRemoveProductMaterialCommand).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/beego/beego/v2/core/validation"
  6 + "reflect"
  7 + "regexp"
  8 + "strings"
  9 +)
  10 +
  11 +type CreateProductMaterialCommand struct {
  12 + // 企业id
  13 + CompanyId int `cname:"企业id" json:"companyId"`
  14 + // 组织ID
  15 + OrgId int `cname:"组织ID" json:"orgId"`
  16 + // 物料分组ID
  17 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
  18 + // 物料编码
  19 + MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
  20 + // 物料名称
  21 + MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
  22 + // 物料属性
  23 + MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
  24 + // 物料类别
  25 + MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
  26 + // 规格
  27 + Specification string `cname:"规格" json:"specification" valid:"Required"`
  28 + // 单位
  29 + Unit string `cname:"单位" json:"unit" valid:"Required"`
  30 + // 保质期 单位:天
  31 + ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
  32 + // 备注
  33 + Remark string `cname:"备注" json:"remark"`
  34 +}
  35 +
  36 +func (createProductMaterialCommand *CreateProductMaterialCommand) Valid(validation *validation.Validation) {
  37 + createProductMaterialCommand.MaterialNumber = strings.ToUpper(createProductMaterialCommand.MaterialNumber)
  38 + match, err := regexp.MatchString("^[A-Z0-9]+$", createProductMaterialCommand.MaterialNumber)
  39 + if !match {
  40 + validation.Error("物料编码只允许数字加大写字母组合")
  41 + return
  42 + }
  43 + if err != nil {
  44 + validation.Error(err.Error())
  45 + return
  46 + }
  47 + if len([]rune(createProductMaterialCommand.Specification)) > 50 {
  48 + validation.Error("规格最多允许50个字符")
  49 + return
  50 + }
  51 +}
  52 +
  53 +func (createProductMaterialCommand *CreateProductMaterialCommand) ValidateCommand() error {
  54 + valid := validation.Validation{}
  55 + b, err := valid.Valid(createProductMaterialCommand)
  56 + if err != nil {
  57 + return err
  58 + }
  59 + if !b {
  60 + elem := reflect.TypeOf(createProductMaterialCommand).Elem()
  61 + for _, validErr := range valid.Errors {
  62 + field, isExist := elem.FieldByName(validErr.Field)
  63 + if isExist {
  64 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  65 + } else {
  66 + return fmt.Errorf(validErr.Message)
  67 + }
  68 + }
  69 + }
  70 + return nil
  71 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type RemoveProductMaterialCommand struct {
  12 + // 物料ID
  13 + ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
  14 +}
  15 +
  16 +func (removeProductMaterialCommand *RemoveProductMaterialCommand) Valid(validation *validation.Validation) {
  17 + //validation.SetError("CustomValid", "未实现的自定义认证")
  18 +}
  19 +
  20 +func (removeProductMaterialCommand *RemoveProductMaterialCommand) ValidateCommand() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(removeProductMaterialCommand)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(removeProductMaterialCommand).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type UpdateProductMaterialCommand struct {
  12 + // 企业id
  13 + //CompanyId int `cname:"企业id" json:"companyId"`
  14 + // 组织ID
  15 + //OrgId int `cname:"组织ID" json:"orgId"`
  16 + // 物料ID
  17 + ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
  18 + // 物料分组ID
  19 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
  20 + //// 物料编码
  21 + //MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
  22 + // 物料名称
  23 + MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
  24 + // 物料属性
  25 + MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
  26 + // 物料类别
  27 + MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
  28 + // 规格
  29 + Specification string `cname:"规格" json:"specification" valid:"Required"`
  30 + // 单位
  31 + Unit string `cname:"单位" json:"unit" valid:"Required"`
  32 + // 保质期 单位:天
  33 + ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
  34 + // 备注
  35 + Remark string `cname:"备注" json:"remark"`
  36 +}
  37 +
  38 +func (updateProductMaterialCommand *UpdateProductMaterialCommand) Valid(validation *validation.Validation) {
  39 + if len([]rune(updateProductMaterialCommand.Specification)) > 50 {
  40 + validation.Error("规格最多允许50个字符")
  41 + return
  42 + }
  43 +}
  44 +
  45 +func (updateProductMaterialCommand *UpdateProductMaterialCommand) ValidateCommand() error {
  46 + valid := validation.Validation{}
  47 + b, err := valid.Valid(updateProductMaterialCommand)
  48 + if err != nil {
  49 + return err
  50 + }
  51 + if !b {
  52 + elem := reflect.TypeOf(updateProductMaterialCommand).Elem()
  53 + for _, validErr := range valid.Errors {
  54 + field, isExist := elem.FieldByName(validErr.Field)
  55 + if isExist {
  56 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  57 + } else {
  58 + return fmt.Errorf(validErr.Message)
  59 + }
  60 + }
  61 + }
  62 + return nil
  63 +}
  1 +package dto
  2 +
  3 +type DtoMaterial struct {
  4 + ProductMaterialId int `json:"productMaterialId"` // 物料ID
  5 + MaterialNumber string `json:"materialNumber"` //物料编码
  6 + MaterialName string `json:"materialName"` //物料名称
  7 + Specification string `json:"specification"` //规格型号
  8 + MaterialCategory string `json:"materialCategory"` //物料类别
  9 + Unit string `json:"unit"` //单位
  10 + MaterialAttribute string `json:"materialAttribute"` //物料属性
  11 + ProductMaterialGroupId int `json:"productMaterialGroupId"` //物料分组 string/string/string
  12 + ExpiredDay int `json:"expiredDay"` //保质期
  13 + Remark string `json:"remark"` //备注
  14 + ProductMaterialGroups []int `json:"productMaterialGroups"`
  15 +}
  1 +package dto
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 +)
  6 +
  7 +func DtoProductMaterial(productMaterialModel *domain.ProductMaterial) *DtoMaterial {
  8 + return &DtoMaterial{
  9 + ProductMaterialId: productMaterialModel.ProductMaterialId,
  10 + ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
  11 + MaterialNumber: productMaterialModel.MaterialNumber,
  12 + MaterialName: productMaterialModel.MaterialName,
  13 + MaterialAttribute: productMaterialModel.MaterialAttribute.Attribute,
  14 + MaterialCategory: productMaterialModel.MaterialCategory.Category,
  15 + Specification: productMaterialModel.ProductMaterialExt.Specification,
  16 + Remark: productMaterialModel.ProductMaterialExt.Remark,
  17 + Unit: productMaterialModel.ProductMaterialExt.Unit,
  18 + ExpiredDay: productMaterialModel.ProductMaterialExt.ExpiredDay,
  19 + }
  20 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type GetProductMaterialQuery struct {
  12 + // 物料ID
  13 + ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
  14 +}
  15 +
  16 +func (getProductMaterialQuery *GetProductMaterialQuery) Valid(validation *validation.Validation) {
  17 + //validation.SetError("CustomValid", "未实现的自定义认证")
  18 +}
  19 +
  20 +func (getProductMaterialQuery *GetProductMaterialQuery) ValidateQuery() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(getProductMaterialQuery)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(getProductMaterialQuery).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type ListProductMaterialQuery struct {
  12 + PageNumber int64 `json:"pageNumber"`
  13 + PageSize int64 `json:"pageSize"`
  14 + // 物料分组ID
  15 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
  16 + // 物料分组ID数组
  17 + ProductMaterialGroupIds []int
  18 + // 物料名称
  19 + MaterialName string `cname:"物料名称" json:"materialName"`
  20 + // 物料类别
  21 + MaterialCategory string `cname:"物料类别" json:"materialCategory"`
  22 + CompanyId int
  23 +}
  24 +
  25 +func (listProductMaterialQuery *ListProductMaterialQuery) Valid(validation *validation.Validation) {
  26 + //validation.SetError("CustomValid", "未实现的自定义认证")
  27 +}
  28 +
  29 +func (listProductMaterialQuery *ListProductMaterialQuery) ValidateQuery() error {
  30 + valid := validation.Validation{}
  31 + b, err := valid.Valid(listProductMaterialQuery)
  32 + if err != nil {
  33 + return err
  34 + }
  35 + if !b {
  36 + elem := reflect.TypeOf(listProductMaterialQuery).Elem()
  37 + for _, validErr := range valid.Errors {
  38 + field, isExist := elem.FieldByName(validErr.Field)
  39 + if isExist {
  40 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  41 + } else {
  42 + return fmt.Errorf(validErr.Message)
  43 + }
  44 + }
  45 + }
  46 + return nil
  47 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type SearchProductMaterialQuery struct {
  12 + PageNumber int64 `json:"pageNumber"`
  13 + PageSize int64 `json:"pageSize"`
  14 + // 物料分组ID
  15 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
  16 + // 物料分组ID数组
  17 + ProductMaterialGroupIds []int
  18 + // 物料名称
  19 + MaterialName string `cname:"物料名称" json:"materialName"`
  20 + // 物料类别
  21 + MaterialCategory string `cname:"物料类别" json:"materialCategory"`
  22 + CompanyId int
  23 +}
  24 +
  25 +func (listProductMaterialQuery *SearchProductMaterialQuery) Valid(validation *validation.Validation) {
  26 + //validation.SetError("CustomValid", "未实现的自定义认证")
  27 +}
  28 +
  29 +func (listProductMaterialQuery *SearchProductMaterialQuery) ValidateQuery() error {
  30 + valid := validation.Validation{}
  31 + b, err := valid.Valid(listProductMaterialQuery)
  32 + if err != nil {
  33 + return err
  34 + }
  35 + if !b {
  36 + elem := reflect.TypeOf(listProductMaterialQuery).Elem()
  37 + for _, validErr := range valid.Errors {
  38 + field, isExist := elem.FieldByName(validErr.Field)
  39 + if isExist {
  40 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  41 + } else {
  42 + return fmt.Errorf(validErr.Message)
  43 + }
  44 + }
  45 + }
  46 + return nil
  47 +}
  1 +package service
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/linmadan/egglib-go/core/application"
  6 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  7 + "github.com/linmadan/egglib-go/utils/tool_funs"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/command"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/dto"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/query"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  13 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
  14 + "time"
  15 +)
  16 +
  17 +// 生产物料服务
  18 +type ProductMaterialService struct {
  19 +}
  20 +
  21 +// 创建生产物料服务
  22 +func (productMaterialService *ProductMaterialService) CreateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.CreateProductMaterialCommand) (interface{}, error) {
  23 + if err := cmd.ValidateCommand(); err != nil {
  24 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  25 + }
  26 + transactionContext, err := factory.CreateTransactionContext(nil)
  27 + if err != nil {
  28 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  29 + }
  30 + if err := transactionContext.StartTransaction(); err != nil {
  31 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  32 + }
  33 + defer func() {
  34 + transactionContext.RollbackTransaction()
  35 + }()
  36 +
  37 + newProductMaterial := &domain.ProductMaterial{
  38 + CompanyId: cmd.CompanyId,
  39 + OrgId: cmd.OrgId,
  40 + ProductMaterialGroupId: cmd.ProductMaterialGroupId,
  41 + MaterialNumber: cmd.MaterialNumber,
  42 + MaterialName: cmd.MaterialName,
  43 + MaterialAttribute: &domain.MaterialAttribute{Attribute: cmd.MaterialAttribute},
  44 + MaterialCategory: &domain.MaterialCategory{Category: cmd.MaterialCategory},
  45 + ProductMaterialExt: &domain.MaterialExt{
  46 + Specification: cmd.Specification,
  47 + Unit: cmd.Unit,
  48 + ExpiredDay: cmd.ExpiredDay,
  49 + Remark: cmd.Remark,
  50 + },
  51 + }
  52 + //var productMaterial *domain.ProductMaterial
  53 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  54 + if _, err := materialService.AddMaterial(operateInfo, newProductMaterial); err != nil {
  55 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  56 + }
  57 + if err := transactionContext.CommitTransaction(); err != nil {
  58 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  59 + }
  60 + return struct{}{}, nil
  61 +}
  62 +
  63 +// 返回生产物料服务单个
  64 +func (productMaterialService *ProductMaterialService) GetProductMaterial(operateInfo *domain.OperateInfo, getProductMaterialQuery *query.GetProductMaterialQuery) (interface{}, error) {
  65 + if err := getProductMaterialQuery.ValidateQuery(); err != nil {
  66 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  67 + }
  68 + transactionContext, err := factory.CreateTransactionContext(nil)
  69 + if err != nil {
  70 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  71 + }
  72 + if err := transactionContext.StartTransaction(); err != nil {
  73 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  74 + }
  75 + defer func() {
  76 + transactionContext.RollbackTransaction()
  77 + }()
  78 + var productMaterialRepository domain.ProductMaterialRepository
  79 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  80 + "transactionContext": transactionContext,
  81 + }); err != nil {
  82 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  83 + } else {
  84 + productMaterialRepository = value
  85 + }
  86 + productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"productMaterialId": getProductMaterialQuery.ProductMaterialId})
  87 + if err != nil {
  88 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  89 + }
  90 + if productMaterial == nil {
  91 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialQuery.ProductMaterialId)))
  92 + } else {
  93 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  94 + productMaterialGroupIdNames, _, err := materialService.AllMaterialGroupParentByBacktracking(operateInfo, productMaterial.ProductMaterialGroupId)
  95 + if err != nil {
  96 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  97 + }
  98 + if len(productMaterialGroupIdNames) == 0 {
  99 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  100 + }
  101 + var productMaterialGroups []int
  102 + for _, productMaterialGroupIdName := range productMaterialGroupIdNames {
  103 + productMaterialGroups = append(productMaterialGroups, productMaterialGroupIdName.ProductMaterialGroupId)
  104 + }
  105 + one := dto.DtoProductMaterial(productMaterial)
  106 + one.ProductMaterialGroups = productMaterialGroups
  107 + if err := transactionContext.CommitTransaction(); err != nil {
  108 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  109 + }
  110 + return one, nil
  111 + }
  112 +}
  113 +
  114 +// 返回生产物料服务列表,未用
  115 +func (productMaterialService *ProductMaterialService) ListProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.ListProductMaterialQuery) (interface{}, error) {
  116 + if err := listProductMaterialQuery.ValidateQuery(); err != nil {
  117 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  118 + }
  119 + transactionContext, err := factory.CreateTransactionContext(nil)
  120 + if err != nil {
  121 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  122 + }
  123 + if err := transactionContext.StartTransaction(); err != nil {
  124 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  125 + }
  126 + defer func() {
  127 + transactionContext.RollbackTransaction()
  128 + }()
  129 + var productMaterialRepository domain.ProductMaterialRepository
  130 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  131 + "transactionContext": transactionContext,
  132 + }); err != nil {
  133 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  134 + } else {
  135 + productMaterialRepository = value
  136 + }
  137 + var results []*dto.DtoMaterial
  138 + if listProductMaterialQuery.ProductMaterialGroupId != 0 {
  139 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  140 + _, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
  141 + if err != nil {
  142 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  143 + }
  144 + listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
  145 + }
  146 + listProductMaterialQuery.CompanyId = operateInfo.CompanyId
  147 + if count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery)); err != nil {
  148 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  149 + } else {
  150 + for _, productMaterial := range productMaterials {
  151 + results = append(results, dto.DtoProductMaterial(productMaterial))
  152 + }
  153 + if err := transactionContext.CommitTransaction(); err != nil {
  154 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  155 + }
  156 + return map[string]interface{}{
  157 + "count": count,
  158 + "productMaterials": results,
  159 + }, nil
  160 + }
  161 +}
  162 +
  163 +// 返回生产物料服务列表
  164 +func (productMaterialService *ProductMaterialService) SearchProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.SearchProductMaterialQuery) (int64, []*dto.DtoMaterial, error) {
  165 + if err := listProductMaterialQuery.ValidateQuery(); err != nil {
  166 + return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
  167 + }
  168 + transactionContext, err := factory.CreateTransactionContext(nil)
  169 + if err != nil {
  170 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  171 + }
  172 + if err := transactionContext.StartTransaction(); err != nil {
  173 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  174 + }
  175 + defer func() {
  176 + transactionContext.RollbackTransaction()
  177 + }()
  178 + var productMaterialRepository domain.ProductMaterialRepository
  179 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  180 + "transactionContext": transactionContext,
  181 + }); err != nil {
  182 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  183 + } else {
  184 + productMaterialRepository = value
  185 + }
  186 + results := make([]*dto.DtoMaterial, 0)
  187 + if listProductMaterialQuery.ProductMaterialGroupId != 0 {
  188 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  189 + _, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
  190 + if err != nil {
  191 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  192 + }
  193 + listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
  194 + }
  195 + listProductMaterialQuery.CompanyId = operateInfo.CompanyId
  196 + count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery))
  197 + if err != nil {
  198 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  199 + }
  200 + for _, productMaterial := range productMaterials {
  201 + results = append(results, dto.DtoProductMaterial(productMaterial))
  202 + }
  203 + if err := transactionContext.CommitTransaction(); err != nil {
  204 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  205 + }
  206 + return count, results, err
  207 +}
  208 +
  209 +// 移除生产物料服务
  210 +func (productMaterialService *ProductMaterialService) RemoveProductMaterial(operateInfo *domain.OperateInfo, removeProductMaterialCommand *command.RemoveProductMaterialCommand) (interface{}, error) {
  211 + if err := removeProductMaterialCommand.ValidateCommand(); err != nil {
  212 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  213 + }
  214 + transactionContext, err := factory.CreateTransactionContext(nil)
  215 + if err != nil {
  216 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  217 + }
  218 + if err := transactionContext.StartTransaction(); err != nil {
  219 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  220 + }
  221 + defer func() {
  222 + transactionContext.RollbackTransaction()
  223 + }()
  224 + var productMaterialRepository domain.ProductMaterialRepository
  225 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  226 + "transactionContext": transactionContext,
  227 + }); err != nil {
  228 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  229 + } else {
  230 + productMaterialRepository = value
  231 + }
  232 + productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": removeProductMaterialCommand.ProductMaterialId})
  233 + if err != nil {
  234 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  235 + }
  236 + if productMaterial == nil {
  237 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeProductMaterialCommand.ProductMaterialId)))
  238 + }
  239 + if productMaterial, err := productMaterialRepository.Remove(productMaterial); err != nil {
  240 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  241 + } else {
  242 + if err := transactionContext.CommitTransaction(); err != nil {
  243 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  244 + }
  245 + return productMaterial, nil
  246 + }
  247 +}
  248 +
  249 +// 更新生产物料服务
  250 +func (productMaterialService *ProductMaterialService) UpdateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialCommand) (interface{}, error) {
  251 + if err := cmd.ValidateCommand(); err != nil {
  252 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  253 + }
  254 + transactionContext, err := factory.CreateTransactionContext(nil)
  255 + if err != nil {
  256 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  257 + }
  258 + if err := transactionContext.StartTransaction(); err != nil {
  259 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  260 + }
  261 + defer func() {
  262 + transactionContext.RollbackTransaction()
  263 + }()
  264 +
  265 + var productMaterialRepository domain.ProductMaterialRepository
  266 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  267 + "transactionContext": transactionContext,
  268 + }); err != nil {
  269 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  270 + } else {
  271 + productMaterialRepository = value
  272 + }
  273 + productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": cmd.ProductMaterialId})
  274 + if err != nil {
  275 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  276 + }
  277 + productMaterial.ProductMaterialGroupId = cmd.ProductMaterialGroupId
  278 + productMaterial.MaterialName = cmd.MaterialName
  279 + productMaterial.MaterialAttribute.Attribute = cmd.MaterialAttribute
  280 + productMaterial.MaterialCategory.Category = cmd.MaterialCategory
  281 + productMaterial.ProductMaterialExt = &domain.MaterialExt{
  282 + Specification: cmd.Specification,
  283 + Unit: cmd.Unit,
  284 + ExpiredDay: cmd.ExpiredDay,
  285 + Remark: cmd.Remark,
  286 + }
  287 + productMaterial.UpdatedAt = time.Now()
  288 +
  289 + if _, err := productMaterialRepository.Save(productMaterial); err != nil {
  290 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  291 + }
  292 + if err := transactionContext.CommitTransaction(); err != nil {
  293 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  294 + }
  295 + return struct{}{}, nil
  296 +}
  297 +
  298 +// 批量移除生产物料服务
  299 +func (productMaterialService *ProductMaterialService) BatchRemoveProductMaterial(operateInfo *domain.OperateInfo, batchRemoveProductMaterialCommand *command.BatchRemoveProductMaterialCommand) (interface{}, error) {
  300 + if err := batchRemoveProductMaterialCommand.ValidateCommand(); err != nil {
  301 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  302 + }
  303 + transactionContext, err := factory.CreateTransactionContext(nil)
  304 + if err != nil {
  305 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  306 + }
  307 + if err := transactionContext.StartTransaction(); err != nil {
  308 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  309 + }
  310 + defer func() {
  311 + transactionContext.RollbackTransaction()
  312 + }()
  313 + var productMaterialRepository domain.ProductMaterialRepository
  314 + if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
  315 + "transactionContext": transactionContext,
  316 + }); err != nil {
  317 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  318 + } else {
  319 + productMaterialRepository = value
  320 + }
  321 + for i := range batchRemoveProductMaterialCommand.ProductMaterialIds {
  322 + ProductMaterialId := batchRemoveProductMaterialCommand.ProductMaterialIds[i]
  323 + productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": ProductMaterialId})
  324 + if err != nil {
  325 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  326 + }
  327 + if productMaterial == nil {
  328 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(ProductMaterialId)))
  329 + }
  330 + if _, err := productMaterialRepository.Remove(productMaterial); err != nil {
  331 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  332 + }
  333 + }
  334 + if err := transactionContext.CommitTransaction(); err != nil {
  335 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  336 + }
  337 + return struct{}{}, nil
  338 +
  339 +}
  340 +
  341 +func NewProductMaterialService(options map[string]interface{}) *ProductMaterialService {
  342 + newProductMaterialService := &ProductMaterialService{}
  343 + return newProductMaterialService
  344 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type CreateProductMaterialGroupCommand struct {
  12 + // 企业id
  13 + CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
  14 + // 组织ID
  15 + OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
  16 + // 父级ID
  17 + Pid int `cname:"父级ID" json:"pid"`
  18 + // 物料分组名称
  19 + MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
  20 + // 物料分组编码
  21 + MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber,omitempty"`
  22 +}
  23 +
  24 +func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
  25 +
  26 +}
  27 +
  28 +func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) ValidateCommand() error {
  29 + valid := validation.Validation{}
  30 + b, err := valid.Valid(createProductMaterialGroupCommand)
  31 + if err != nil {
  32 + return err
  33 + }
  34 + if !b {
  35 + elem := reflect.TypeOf(createProductMaterialGroupCommand).Elem()
  36 + for _, validErr := range valid.Errors {
  37 + field, isExist := elem.FieldByName(validErr.Field)
  38 + if isExist {
  39 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  40 + } else {
  41 + return fmt.Errorf(validErr.Message)
  42 + }
  43 + }
  44 + }
  45 + return nil
  46 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type RemoveProductMaterialGroupCommand struct {
  12 + // 物料分组ID
  13 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
  14 +}
  15 +
  16 +func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) Valid(validation *validation.Validation) {
  17 +
  18 +}
  19 +
  20 +func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) ValidateCommand() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(removeProductMaterialGroupCommand)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(removeProductMaterialGroupCommand).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type UpdateProductMaterialGroupCommand struct {
  12 + // 物料分组ID
  13 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
  14 + // 物料分组名称
  15 + MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
  16 + // 物料分组编码
  17 + MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber"`
  18 +}
  19 +
  20 +func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
  21 +
  22 +}
  23 +
  24 +func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) ValidateCommand() error {
  25 + valid := validation.Validation{}
  26 + b, err := valid.Valid(updateProductMaterialGroupCommand)
  27 + if err != nil {
  28 + return err
  29 + }
  30 + if !b {
  31 + elem := reflect.TypeOf(updateProductMaterialGroupCommand).Elem()
  32 + for _, validErr := range valid.Errors {
  33 + field, isExist := elem.FieldByName(validErr.Field)
  34 + if isExist {
  35 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  36 + } else {
  37 + return fmt.Errorf(validErr.Message)
  38 + }
  39 + }
  40 + }
  41 + return nil
  42 +}
  1 +package dto
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  6 +)
  7 +
  8 +type MaterialGroupDto struct {
  9 + // 物料分组ID
  10 + ProductMaterialGroupId int `json:"id"`
  11 + // 企业id
  12 + //CompanyId int `json:"companyId"`
  13 + // 组织ID
  14 + //OrgId int `json:"orgId"`
  15 + // 父级ID
  16 + Pid int `json:"pid"`
  17 + // 路径 (不使用,如果父级改变的话,子级的Path要做更新)
  18 + //Path string `json:"path"`
  19 + // 物料分组名称
  20 + MaterialGroupName string `json:"materialGroupName"`
  21 + // 物料分组编码
  22 + MaterialGroupNumber string `json:"materialGroupNumber"`
  23 +}
  24 +
  25 +func (d *MaterialGroupDto) LoadDto(m *domain.ProductMaterialGroup, orgId int) *MaterialGroupDto {
  26 + d.ProductMaterialGroupId = m.ProductMaterialGroupId
  27 + d.Pid = m.Pid
  28 + d.MaterialGroupName = m.MaterialGroupName
  29 + d.MaterialGroupNumber = m.MaterialGroupNumber
  30 + return d
  31 +}
  32 +
  33 +func (productMaterialGroup *MaterialGroupDto) PID() string {
  34 + return fmt.Sprintf("%d", productMaterialGroup.Pid)
  35 +}
  36 +func (productMaterialGroup *MaterialGroupDto) ID() string {
  37 + return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
  38 +}
  39 +
  40 +type MaterialGroupDtos []*MaterialGroupDto
  41 +
  42 +func (tree MaterialGroupDtos) Len() int {
  43 + return len(tree)
  44 +}
  45 +
  46 +func (tree MaterialGroupDtos) Less(i, j int) bool {
  47 + if tree[i].Pid < tree[j].Pid {
  48 + return true
  49 + }
  50 + if tree[i].Pid == tree[j].Pid {
  51 + return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
  52 + }
  53 + return false
  54 +}
  55 +
  56 +func (tree MaterialGroupDtos) Swap(i, j int) {
  57 + tree[i], tree[j] = tree[j], tree[i]
  58 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type GetProductMaterialGroupQuery struct {
  12 + // 物料分组ID
  13 + ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
  14 +}
  15 +
  16 +func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) Valid(validation *validation.Validation) {
  17 +
  18 +}
  19 +
  20 +func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) ValidateQuery() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(getProductMaterialGroupQuery)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(getProductMaterialGroupQuery).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type ListProductMaterialGroupQuery struct {
  12 + // 查询偏离量
  13 + Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
  14 + // 查询限制
  15 + Limit int `cname:"查询限制" json:"limit" valid:"Required"`
  16 +}
  17 +
  18 +func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) Valid(validation *validation.Validation) {
  19 +
  20 +}
  21 +
  22 +func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) ValidateQuery() error {
  23 + valid := validation.Validation{}
  24 + b, err := valid.Valid(listProductMaterialGroupQuery)
  25 + if err != nil {
  26 + return err
  27 + }
  28 + if !b {
  29 + elem := reflect.TypeOf(listProductMaterialGroupQuery).Elem()
  30 + for _, validErr := range valid.Errors {
  31 + field, isExist := elem.FieldByName(validErr.Field)
  32 + if isExist {
  33 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  34 + } else {
  35 + return fmt.Errorf(validErr.Message)
  36 + }
  37 + }
  38 + }
  39 + return nil
  40 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  6 + "reflect"
  7 + "strings"
  8 +
  9 + "github.com/beego/beego/v2/core/validation"
  10 +)
  11 +
  12 +type SearchProductMaterialGroupQuery struct {
  13 + // 查询偏离量
  14 + Offset int `cname:"查询偏离量" json:"offset"`
  15 + // 查询限制
  16 + Limit int `cname:"查询限制" json:"limit"`
  17 +
  18 + // 当前公司
  19 + CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
  20 + // 当前登录的组织
  21 + //OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
  22 + // 匹配多个组织
  23 + //InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty" valid:"Required"`
  24 + // 页码
  25 + PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
  26 + // 页数
  27 + PageSize int `cname:"页数" json:"pageSize,omitempty"`
  28 +}
  29 +
  30 +func (cmd *SearchProductMaterialGroupQuery) Valid(validation *validation.Validation) {
  31 + cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
  32 +}
  33 +
  34 +func (cmd *SearchProductMaterialGroupQuery) ValidateQuery() error {
  35 + valid := validation.Validation{}
  36 + b, err := valid.Valid(cmd)
  37 + if err != nil {
  38 + return err
  39 + }
  40 + if !b {
  41 + elem := reflect.TypeOf(cmd).Elem()
  42 + for _, validErr := range valid.Errors {
  43 + field, isExist := elem.FieldByName(validErr.Field)
  44 + if isExist {
  45 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  46 + } else {
  47 + return fmt.Errorf(validErr.Message)
  48 + }
  49 + }
  50 + }
  51 + return nil
  52 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type SelectorProductMaterialGroupQuery struct {
  12 + // 查询偏离量
  13 + //Offset int `cname:"查询偏离量" json:"offset"`
  14 + // 查询限制
  15 + //Limit int `cname:"查询限制" json:"limit"`
  16 + // options 'tree' 'list' default tree
  17 + Style string `json:"style"`
  18 + // 当前公司
  19 + CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
  20 + // 页码
  21 + //PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
  22 + // 页数
  23 + //PageSize int `cname:"页数" json:"pageSize,omitempty"`
  24 +}
  25 +
  26 +func (cmd *SelectorProductMaterialGroupQuery) Valid(validation *validation.Validation) {
  27 + //cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
  28 + cmd.Style = "tree"
  29 +}
  30 +
  31 +func (cmd *SelectorProductMaterialGroupQuery) ValidateQuery() error {
  32 + valid := validation.Validation{}
  33 + b, err := valid.Valid(cmd)
  34 + if err != nil {
  35 + return err
  36 + }
  37 + if !b {
  38 + elem := reflect.TypeOf(cmd).Elem()
  39 + for _, validErr := range valid.Errors {
  40 + field, isExist := elem.FieldByName(validErr.Field)
  41 + if isExist {
  42 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  43 + } else {
  44 + return fmt.Errorf(validErr.Message)
  45 + }
  46 + }
  47 + }
  48 + return nil
  49 +}
  1 +package service
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/linmadan/egglib-go/core/application"
  6 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  7 + "github.com/linmadan/egglib-go/utils/tool_funs"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/command"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/dto"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/query"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  13 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  15 + "sort"
  16 +)
  17 +
  18 +// 物料分组服务
  19 +type ProductMaterialGroupService struct {
  20 +}
  21 +
  22 +// 创建物料分组服务
  23 +func (productMaterialGroupService *ProductMaterialGroupService) CreateProductMaterialGroup(operateInfo *domain.OperateInfo, createProductMaterialGroupCommand *command.CreateProductMaterialGroupCommand) (interface{}, error) {
  24 + if err := createProductMaterialGroupCommand.ValidateCommand(); err != nil {
  25 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  26 + }
  27 + transactionContext, err := factory.CreateTransactionContext(nil)
  28 + if err != nil {
  29 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  30 + }
  31 + if err := transactionContext.StartTransaction(); err != nil {
  32 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  33 + }
  34 + defer func() {
  35 + transactionContext.RollbackTransaction()
  36 + }()
  37 + newProductMaterialGroup := &domain.ProductMaterialGroup{
  38 + Pid: createProductMaterialGroupCommand.Pid,
  39 + MaterialGroupName: createProductMaterialGroupCommand.MaterialGroupName,
  40 + MaterialGroupNumber: createProductMaterialGroupCommand.MaterialGroupNumber,
  41 + }
  42 +
  43 + var productMaterialGroup *domain.ProductMaterialGroup
  44 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  45 + if productMaterialGroup, err = materialService.AddMaterialGroup(operateInfo, newProductMaterialGroup); err != nil {
  46 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  47 + }
  48 + if err := transactionContext.CommitTransaction(); err != nil {
  49 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  50 + }
  51 + return productMaterialGroup, nil
  52 +}
  53 +
  54 +// 返回物料分组服务
  55 +func (productMaterialGroupService *ProductMaterialGroupService) GetProductMaterialGroup(getProductMaterialGroupQuery *query.GetProductMaterialGroupQuery) (interface{}, error) {
  56 + if err := getProductMaterialGroupQuery.ValidateQuery(); err != nil {
  57 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  58 + }
  59 + transactionContext, err := factory.CreateTransactionContext(nil)
  60 + if err != nil {
  61 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  62 + }
  63 + if err := transactionContext.StartTransaction(); err != nil {
  64 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  65 + }
  66 + defer func() {
  67 + transactionContext.RollbackTransaction()
  68 + }()
  69 + var productMaterialGroupRepository domain.ProductMaterialGroupRepository
  70 + if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
  71 + "transactionContext": transactionContext,
  72 + }); err != nil {
  73 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  74 + } else {
  75 + productMaterialGroupRepository = value
  76 + }
  77 + productMaterialGroup, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"productMaterialGroupId": getProductMaterialGroupQuery.ProductMaterialGroupId})
  78 + if err != nil {
  79 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  80 + }
  81 + if productMaterialGroup == nil {
  82 + return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialGroupQuery.ProductMaterialGroupId)))
  83 + }
  84 + //测试
  85 + //materialService,_:= domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  86 + //nodes,child,_:=materialService.AllMaterialGroupChild(&domain.OperateInfo{CompanyId: productMaterialGroup.CompanyId},productMaterialGroup.ProductMaterialGroupId)
  87 + //log.Logger.Debug("节点的Child", map[string]interface{}{"data":child,"nodes":nodes})
  88 + if err := transactionContext.CommitTransaction(); err != nil {
  89 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  90 + }
  91 + materialGroupDto := dto.MaterialGroupDto{}
  92 + return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
  93 +
  94 +}
  95 +
  96 +// 返回物料分组服务列表
  97 +func (productMaterialGroupService *ProductMaterialGroupService) ListProductMaterialGroup(listProductMaterialGroupQuery *query.ListProductMaterialGroupQuery) (interface{}, error) {
  98 + if err := listProductMaterialGroupQuery.ValidateQuery(); err != nil {
  99 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  100 + }
  101 + transactionContext, err := factory.CreateTransactionContext(nil)
  102 + if err != nil {
  103 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  104 + }
  105 + if err := transactionContext.StartTransaction(); err != nil {
  106 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  107 + }
  108 + defer func() {
  109 + transactionContext.RollbackTransaction()
  110 + }()
  111 + var productMaterialGroupRepository domain.ProductMaterialGroupRepository
  112 + if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
  113 + "transactionContext": transactionContext,
  114 + }); err != nil {
  115 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  116 + } else {
  117 + productMaterialGroupRepository = value
  118 + }
  119 + if count, productMaterialGroups, err := productMaterialGroupRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialGroupQuery)); err != nil {
  120 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  121 + } else {
  122 + if err := transactionContext.CommitTransaction(); err != nil {
  123 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  124 + }
  125 + return map[string]interface{}{
  126 + "count": count,
  127 + "productMaterialGroups": productMaterialGroups,
  128 + }, nil
  129 + }
  130 +}
  131 +
  132 +// 移除物料分组服务
  133 +func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.RemoveProductMaterialGroupCommand) (interface{}, error) {
  134 + if err := cmd.ValidateCommand(); err != nil {
  135 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  136 + }
  137 + transactionContext, err := factory.CreateTransactionContext(nil)
  138 + if err != nil {
  139 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  140 + }
  141 + if err := transactionContext.StartTransaction(); err != nil {
  142 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  143 + }
  144 + defer func() {
  145 + transactionContext.RollbackTransaction()
  146 + }()
  147 +
  148 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  149 + _, ids, err := materialService.AllMaterialGroupChild(operateInfo, cmd.ProductMaterialGroupId)
  150 + if err != nil {
  151 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  152 + }
  153 + if len(ids) == 0 {
  154 + return nil, nil
  155 + }
  156 + productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
  157 + count, _, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialGroupIds": ids, "limit": 1})
  158 + if err != nil {
  159 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  160 + }
  161 + if count >= 1 {
  162 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "请处理当前分组下存在的物料信息")
  163 + }
  164 +
  165 + for _, id := range ids {
  166 + productMaterialGroupRepository, productMaterialGroup, err := factory.FastProductMaterialGroup(transactionContext, id)
  167 + if err != nil {
  168 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  169 + }
  170 + if _, err = productMaterialGroupRepository.Remove(productMaterialGroup); err != nil {
  171 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  172 + }
  173 + }
  174 + if err := transactionContext.CommitTransaction(); err != nil {
  175 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  176 + }
  177 + return nil, nil
  178 +}
  179 +
  180 +// 更新物料分组服务
  181 +func (productMaterialGroupService *ProductMaterialGroupService) UpdateProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialGroupCommand) (interface{}, error) {
  182 + if err := cmd.ValidateCommand(); err != nil {
  183 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  184 + }
  185 + transactionContext, err := factory.CreateTransactionContext(nil)
  186 + if err != nil {
  187 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  188 + }
  189 + if err := transactionContext.StartTransaction(); err != nil {
  190 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  191 + }
  192 + defer func() {
  193 + transactionContext.RollbackTransaction()
  194 + }()
  195 + productMaterialGroup := &domain.ProductMaterialGroup{
  196 + ProductMaterialGroupId: cmd.ProductMaterialGroupId,
  197 + MaterialGroupName: cmd.MaterialGroupName,
  198 + //MaterialGroupNumber: cmd.MaterialGroupNumber,
  199 + }
  200 + materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
  201 + if productMaterialGroup, err := materialService.UpdateMaterialGroup(operateInfo, productMaterialGroup); err != nil {
  202 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  203 + } else {
  204 + if err := transactionContext.CommitTransaction(); err != nil {
  205 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  206 + }
  207 + materialGroupDto := dto.MaterialGroupDto{}
  208 + return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
  209 + }
  210 +}
  211 +
  212 +// 搜索物料分组服务列表
  213 +func (productMaterialGroupService *ProductMaterialGroupService) SearchProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SearchProductMaterialGroupQuery) (int64, interface{}, error) {
  214 + if err := cmd.ValidateQuery(); err != nil {
  215 + return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
  216 + }
  217 + transactionContext, err := factory.CreateTransactionContext(nil)
  218 + if err != nil {
  219 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  220 + }
  221 + if err := transactionContext.StartTransaction(); err != nil {
  222 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  223 + }
  224 + defer func() {
  225 + transactionContext.RollbackTransaction()
  226 + }()
  227 + var productMaterialGroupRepository domain.ProductMaterialGroupRepository
  228 + productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
  229 + queryOptions := utils.ObjectToMap(cmd)
  230 + count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
  231 + if err != nil {
  232 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  233 + }
  234 + var results = make([]*dto.MaterialGroupDto, 0)
  235 + for i := range productGroups {
  236 + newItem := &dto.MaterialGroupDto{}
  237 + newItem.LoadDto(productGroups[i], operateInfo.OrgId)
  238 + results = append(results, newItem)
  239 + }
  240 + if err := transactionContext.CommitTransaction(); err != nil {
  241 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  242 + }
  243 + return count, results, nil
  244 +}
  245 +
  246 +func (productMaterialGroupService *ProductMaterialGroupService) SelectorProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SelectorProductMaterialGroupQuery) (int64, interface{}, error) {
  247 + if err := cmd.ValidateQuery(); err != nil {
  248 + return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
  249 + }
  250 + transactionContext, err := factory.CreateTransactionContext(nil)
  251 + if err != nil {
  252 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  253 + }
  254 + if err := transactionContext.StartTransaction(); err != nil {
  255 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  256 + }
  257 + defer func() {
  258 + transactionContext.RollbackTransaction()
  259 + }()
  260 + var productMaterialGroupRepository domain.ProductMaterialGroupRepository
  261 + productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
  262 + queryOptions := utils.ObjectToMap(cmd)
  263 + count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
  264 + if err != nil {
  265 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  266 + }
  267 + var results = make([]*dto.MaterialGroupDto, 0)
  268 + for i := range productGroups {
  269 + newItem := &dto.MaterialGroupDto{}
  270 + newItem.LoadDto(productGroups[i], operateInfo.OrgId)
  271 + results = append(results, newItem)
  272 + }
  273 + if err := transactionContext.CommitTransaction(); err != nil {
  274 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  275 + }
  276 + if cmd.Style == "tree" {
  277 + sort.Stable(dto.MaterialGroupDtos(results))
  278 + nodes := make([]utils.TreeNode, 0)
  279 + for i := range results {
  280 + nodes = append(nodes, results[i])
  281 + }
  282 + tree := utils.NewTree(nodes)
  283 + return count, tree.Nodes, nil
  284 + }
  285 + return count, results, nil
  286 +}
  287 +
  288 +func NewProductMaterialGroupService(options map[string]interface{}) *ProductMaterialGroupService {
  289 + newProductMaterialGroupService := &ProductMaterialGroupService{}
  290 + return newProductMaterialGroupService
  291 +}
@@ -5,11 +5,13 @@ import ( @@ -5,11 +5,13 @@ import (
5 "github.com/linmadan/egglib-go/core/application" 5 "github.com/linmadan/egglib-go/core/application"
6 "github.com/linmadan/egglib-go/transaction/pg" 6 "github.com/linmadan/egglib-go/transaction/pg"
7 "github.com/linmadan/egglib-go/utils/tool_funs" 7 "github.com/linmadan/egglib-go/utils/tool_funs"
  8 + "github.com/linmadan/egglib-go/utils/xtime"
8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory" 9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command" 10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command"
10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto"
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query" 12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query"
12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService" 15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
14 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis" 16 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 17 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
@@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma @@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma
514 516
515 productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext)) 517 productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext))
516 518
  519 + productRecordDao, _ := dao.NewProductRecordDao(transactionContext.(*pg.TransactionContext))
  520 + begin := xtime.BeginningOfDay()
  521 + end := time.Now()
  522 + workstationId := domain.WorkstationKey(returnMaterialCommand.WorkshopId, returnMaterialCommand.LineId, returnMaterialCommand.SectionId)
  523 + totalReceive, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReceiveMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
  524 + if err != nil {
  525 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  526 + }
  527 + totalReturn, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReturnMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
  528 + if err != nil {
  529 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  530 + }
  531 + allowReturn := totalReceive - totalReturn
  532 + if totalReturn+returnMaterialCommand.Weigh > totalReceive {
  533 + if allowReturn > 0 {
  534 + return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料,当前只允许退料 %v kg", totalReceive-totalReturn))
  535 + }
  536 + return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料"))
  537 + }
  538 +
517 _, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand)) 539 _, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand))
518 if err != nil { 540 if err != nil {
519 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 541 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "reflect"
  6 + "strings"
  7 +
  8 + "github.com/beego/beego/v2/core/validation"
  9 +)
  10 +
  11 +type CancelProductRecordCommand struct {
  12 + // 生产记录ID
  13 + ProductRecordId int `cname:"生产记录ID" json:"productRecordId" valid:"Required"`
  14 +}
  15 +
  16 +func (cancelProductRecordCommand *CancelProductRecordCommand) Valid(validation *validation.Validation) {
  17 + //validation.SetError("CustomValid", "未实现的自定义认证")
  18 +}
  19 +
  20 +func (cancelProductRecordCommand *CancelProductRecordCommand) ValidateCommand() error {
  21 + valid := validation.Validation{}
  22 + b, err := valid.Valid(cancelProductRecordCommand)
  23 + if err != nil {
  24 + return err
  25 + }
  26 + if !b {
  27 + elem := reflect.TypeOf(cancelProductRecordCommand).Elem()
  28 + for _, validErr := range valid.Errors {
  29 + field, isExist := elem.FieldByName(validErr.Field)
  30 + if isExist {
  31 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  32 + } else {
  33 + return fmt.Errorf(validErr.Message)
  34 + }
  35 + }
  36 + }
  37 + return nil
  38 +}
  1 +package dto
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/utils/xtime"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  7 +)
  8 +
  9 +// HistoryProductRecord 历史生成记录
  10 +type HistoryProductRecord struct {
  11 + // 生产记录ID
  12 + ProductRecordId int `json:"productRecordId,omitempty"`
  13 + // 批号
  14 + BatchNumber string `json:"batchNumber,omitempty"`
  15 + // 计划的产品名称
  16 + PlanProductName string `json:"planProductName,omitempty"`
  17 + // 创建时间
  18 + CreatedAt string `json:"createdAt,omitempty"`
  19 + // 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
  20 + ProductRecordType int `json:"productRecordType"`
  21 + // 生产工人
  22 + ProductWorker *domain.User `json:"productWorker,omitempty"`
  23 + // 产能 - 审核前
  24 + Weight float64 `json:"weight"`
  25 + // 状态 1:未审核 2:已审核 3:已撤回 4:已记录
  26 + Status int `json:"status"`
  27 +}
  28 +
  29 +func (d *HistoryProductRecord) LoadDto(m *domain.ProductRecord) *HistoryProductRecord {
  30 + d.ProductRecordId = m.ProductRecordId
  31 + d.ProductWorker = m.ProductWorker
  32 + d.Weight = utils.Round(m.ProductRecordInfo.Original, 1)
  33 + d.Status = m.ProductRecordInfo.ApproveStatus
  34 + d.PlanProductName = m.ProductRecordInfo.PlanProductName
  35 + d.BatchNumber = m.ProductRecordInfo.BatchNumber
  36 + d.CreatedAt = m.CreatedAt.Local().Format("2006-01-02 15:04:05")
  37 + d.ProductRecordType = m.ProductRecordType
  38 + if m.ProductRecordType != domain.RecordTypeSecondLevelWeigh &&
  39 + m.ProductRecordInfo.ApproveStatus == domain.ProductRecordNotApprove &&
  40 + !(xtime.BeginningOfDay().Equal(xtime.New(m.CreatedAt.Local()).BeginningOfDay())) {
  41 + //log.Logger.Debug("not equal", map[string]interface{}{"t1": xtime.BeginningOfDay(), "t2": xtime.New(m.CreatedAt.Local()).BeginningOfDay()})
  42 + d.Status = domain.ProductRecordLogged
  43 + }
  44 + return d
  45 +}
  1 +package query
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/linmadan/egglib-go/utils/xtime"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  8 + "reflect"
  9 + "strings"
  10 + "time"
  11 +
  12 + "github.com/beego/beego/v2/core/validation"
  13 +)
  14 +
  15 +type HistoryProductRecordQuery struct {
  16 + // 查询偏离量
  17 + Offset int `cname:"查询偏离量" json:"offset"`
  18 + // 查询限制
  19 + Limit int `cname:"查询限制" json:"limit"`
  20 + // 当前公司
  21 + CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
  22 + // 当前登录的组织
  23 + OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
  24 + // 匹配多个组织
  25 + InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty"`
  26 + // 页码
  27 + PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
  28 + // 页数
  29 + PageSize int `cname:"页数" json:"pageSize,omitempty"`
  30 + // 车间ID
  31 + WorkshopId int `cname:"车间ID" json:"workshopId,omitempty"`
  32 + // 生产线ID
  33 + LineId int `cname:"生产线ID" json:"lineId,omitempty"`
  34 + // 工段ID
  35 + SectionId int `json:"sectionId,omitempty"`
  36 + // 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
  37 + ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重" json:"productRecordType"`
  38 + // 生产线名称
  39 + //LineName string `cname:"生产线名称" json:"lineName,omitempty"`
  40 + // 工段名称
  41 + //SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
  42 + // 员工类型 1:固定 2:派遣 3.临时
  43 + //EmployeeType int `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
  44 + // 开始时间
  45 + //BeginTime string `cname:"开始时间" json:"beginTime"`
  46 + // 结束时间
  47 + //EndTime string `cname:"结束时间" json:"endTime"`
  48 +
  49 + // 上一次记录ID
  50 + LastProductRecordId int `cname:"上一次记录ID" json:"lastProductRecordId"`
  51 + // 日期
  52 + Date string `cname:"日期" json:"date"`
  53 + // 生产员工ID
  54 + ProductWorkerId int `cname:"生产员工ID" json:"productWorkerId"`
  55 + // 状态 0:全部 1:未审核 2:已审核 3:已撤回 4:已记录
  56 + Status int `cname:"状态" json:"status"`
  57 +
  58 + // 开始时间
  59 + ProductBeginTime time.Time `cname:"开始时间" json:"productBeginTime"`
  60 + // 结束时间
  61 + ProductEndTime time.Time `cname:"结束时间" json:"productEndTime"`
  62 +}
  63 +
  64 +func (cmd *HistoryProductRecordQuery) Valid(validation *validation.Validation) {
  65 + cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
  66 +
  67 + //var err error
  68 + //if len(cmd.BeginTime) > 0 {
  69 + // if cmd.ProductBeginTime, err = time.Parse("2006-01-02 15:04:05", cmd.BeginTime); err != nil {
  70 + // log.Logger.Error(err.Error())
  71 + // validation.Error("开始时间有误")
  72 + // return
  73 + // }
  74 + //}
  75 + //if len(cmd.EndTime) > 0 {
  76 + // if cmd.ProductEndTime, err = time.Parse("2006-01-02 15:04:05", cmd.EndTime); err != nil {
  77 + // log.Logger.Error(err.Error())
  78 + // validation.Error("结束时间有误")
  79 + // return
  80 + // }
  81 + // if cmd.ProductEndTime.Equal(cmd.ProductBeginTime) {
  82 + // cmd.ProductEndTime = cmd.ProductEndTime.Add(time.Hour * 24)
  83 + // }
  84 + //}
  85 + if len(cmd.Date) > 0 {
  86 + t, err := xtime.Parse(cmd.Date)
  87 + if err != nil {
  88 + log.Logger.Error(err.Error())
  89 + validation.Error("日期有误")
  90 + return
  91 + }
  92 + cmd.ProductBeginTime = t
  93 + cmd.ProductEndTime = t.AddDate(0, 0, 1)
  94 + }
  95 + if cmd.ProductRecordType == domain.RecordTypeReceiveMaterial || cmd.ProductRecordType == domain.RecordTypeReturnMaterial {
  96 + if cmd.Status == domain.ProductRecordNotApprove {
  97 + cmd.Status = domain.ProductRecordNotApprove
  98 + if xtime.IsZero(cmd.ProductBeginTime) || xtime.BeforeEqual(cmd.ProductBeginTime, xtime.BeginningOfDay()) {
  99 + cmd.ProductBeginTime = xtime.BeginningOfDay()
  100 + }
  101 + } else if cmd.Status == domain.ProductRecordLogged {
  102 + cmd.Status = domain.ProductRecordNotApprove
  103 + if len(cmd.Date) == 0 && xtime.IsZero(cmd.ProductEndTime) {
  104 + cmd.ProductEndTime = xtime.BeginningOfDay()
  105 + }
  106 + if len(cmd.Date) > 0 && !xtime.BeforeEqual(cmd.ProductEndTime, xtime.BeginningOfDay()) {
  107 + cmd.Status = domain.ProductRecordLogged
  108 + }
  109 + }
  110 + }
  111 +}
  112 +
  113 +func (cmd *HistoryProductRecordQuery) ValidateQuery() error {
  114 + valid := validation.Validation{}
  115 + b, err := valid.Valid(cmd)
  116 + if err != nil {
  117 + return err
  118 + }
  119 + if !b {
  120 + elem := reflect.TypeOf(cmd).Elem()
  121 + for _, validErr := range valid.Errors {
  122 + field, isExist := elem.FieldByName(validErr.Field)
  123 + if isExist {
  124 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  125 + } else {
  126 + return fmt.Errorf(validErr.Message)
  127 + }
  128 + }
  129 + }
  130 + return nil
  131 +}
@@ -274,6 +274,41 @@ func (productRecordService *ProductRecordService) SearchProductRecord(operateInf @@ -274,6 +274,41 @@ func (productRecordService *ProductRecordService) SearchProductRecord(operateInf
274 return count, result, nil 274 return count, result, nil
275 } 275 }
276 276
  277 +// 返回生产记录服务列表
  278 +func (productRecordService *ProductRecordService) HistoryProductRecord(operateInfo *domain.OperateInfo, query *query.HistoryProductRecordQuery) (int64, interface{}, error) {
  279 + if err := query.ValidateQuery(); err != nil {
  280 + return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
  281 + }
  282 + transactionContext, err := factory.CreateTransactionContext(nil)
  283 + if err != nil {
  284 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  285 + }
  286 + if err := transactionContext.StartTransaction(); err != nil {
  287 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  288 + }
  289 + defer func() {
  290 + transactionContext.RollbackTransaction()
  291 + }()
  292 + var productRecordRepository domain.ProductRecordRepository
  293 + productRecordRepository, _, _ = factory.FastPgProductRecord(transactionContext, 0)
  294 +
  295 + count, productRecords, err := productRecordRepository.Find(utils.ObjectToMap(query))
  296 + if err != nil {
  297 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  298 + }
  299 + if err := transactionContext.CommitTransaction(); err != nil {
  300 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  301 + }
  302 + var result = make([]*dto.HistoryProductRecord, 0)
  303 + for i := range productRecords {
  304 + item := productRecords[i]
  305 + newItem := &dto.HistoryProductRecord{}
  306 + newItem.LoadDto(item)
  307 + result = append(result, newItem)
  308 + }
  309 + return count, result, nil
  310 +}
  311 +
277 // 生产记录统计 312 // 生产记录统计
278 func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *command.ProductRecordStaticsCommand) (interface{}, error) { 313 func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *command.ProductRecordStaticsCommand) (interface{}, error) {
279 if err := cmd.ValidateCommand(); err != nil { 314 if err := cmd.ValidateCommand(); err != nil {
@@ -308,6 +343,33 @@ func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *comm @@ -308,6 +343,33 @@ func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *comm
308 return nil, nil 343 return nil, nil
309 } 344 }
310 345
  346 +// 生产记录审核
  347 +func (productRecordService *ProductRecordService) CancelProductRecord(cmd *command.CancelProductRecordCommand) (interface{}, error) {
  348 + if err := cmd.ValidateCommand(); err != nil {
  349 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  350 + }
  351 + transactionContext, err := factory.CreateTransactionContext(nil)
  352 + if err != nil {
  353 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  354 + }
  355 + if err := transactionContext.StartTransaction(); err != nil {
  356 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  357 + }
  358 + defer func() {
  359 + transactionContext.RollbackTransaction()
  360 + }()
  361 +
  362 + svr, err := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
  363 + if _, err = svr.Cancel(cmd.ProductRecordId); err != nil {
  364 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  365 + }
  366 +
  367 + if err := transactionContext.CommitTransaction(); err != nil {
  368 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  369 + }
  370 + return struct{}{}, nil
  371 +}
  372 +
311 func NewProductRecordService(options map[string]interface{}) *ProductRecordService { 373 func NewProductRecordService(options map[string]interface{}) *ProductRecordService {
312 newProductRecordService := &ProductRecordService{} 374 newProductRecordService := &ProductRecordService{}
313 return newProductRecordService 375 return newProductRecordService
1 package syncdata 1 package syncdata
2 2
3 import ( 3 import (
  4 + "fmt"
4 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant" 5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService" 7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
@@ -209,6 +210,101 @@ func (srv *PullDataK3CloudService) PullMaterial(timeFilter time.Time) error { @@ -209,6 +210,101 @@ func (srv *PullDataK3CloudService) PullMaterial(timeFilter time.Time) error {
209 return nil 210 return nil
210 } 211 }
211 212
  213 +func (srv *PullDataK3CloudService) pullMaterial(timeFilter time.Time) ([]models.MaterialK3cloud, error) {
  214 + //拉取数据
  215 + var filterString []string
  216 + if !timeFilter.IsZero() {
  217 + str := timeFilter.Format("2006-01-02T15:04:05")
  218 + filterString = append(filterString, "FModifyDate>='"+str+"'")
  219 + }
  220 + client, err := newK3cloudClient()
  221 + if err != nil {
  222 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  223 + }
  224 + fieldKeys := []string{
  225 + "FMATERIALID", "FSpecification", "FName", "FNumber",
  226 + "FDocumentStatus", "FForbidStatus", "FErpClsID",
  227 + "FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
  228 + "FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
  229 + "FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName", "FCategoryID",
  230 + }
  231 + var (
  232 + startRow int
  233 + allResult []map[string]string
  234 + queryErr error
  235 + )
  236 + for {
  237 + result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
  238 + FormId: "BD_MATERIAL",
  239 + Data: k3cloud.ExecuteBillQueryData{
  240 + FormId: "BD_MATERIAL",
  241 + FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
  242 + StartRow: startRow,
  243 + Limit: 1000,
  244 + FilterString: strings.Join(filterString, " and "),
  245 + },
  246 + })
  247 + if err != nil {
  248 + queryErr = err
  249 + break
  250 + }
  251 + mp := result.ToMapString()
  252 + if len(mp) == 0 {
  253 + break
  254 + }
  255 + allResult = append(allResult, mp...)
  256 + startRow += 1000
  257 + }
  258 + if queryErr != nil {
  259 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  260 + }
  261 + var (
  262 + materialModels []models.MaterialK3cloud
  263 + materialTemp models.MaterialK3cloud
  264 + )
  265 + nowTime := time.Now()
  266 + for _, item := range allResult {
  267 + materialId, err := strconv.Atoi(item["FMATERIALID"])
  268 + if err != nil {
  269 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  270 + }
  271 + fErpClsID, _ := strconv.Atoi(item["FErpClsID"])
  272 + fBaseUnitId, _ := strconv.Atoi(item["FBaseUnitId"])
  273 + materialGroup, _ := strconv.Atoi(item["MaterialGroup"])
  274 + fUseOrgId, _ := strconv.Atoi(item["FUseOrgId"])
  275 + refStatus, _ := strconv.Atoi(item["RefStatus"])
  276 + fCreateDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FCreateDate"])
  277 + fModifyDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FModifyDate"])
  278 + fForbidDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FForbidDate"])
  279 + fApproveDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FApproveDate"])
  280 + materialTemp = models.MaterialK3cloud{
  281 + MaterialId: materialId,
  282 + Name: item["FName"],
  283 + Number: item["FNumber"],
  284 + Specification: item["FSpecification"],
  285 + ForbidStatus: item["FForbidStatus"],
  286 + ErpClsId: fErpClsID,
  287 + BaseUnitId: fBaseUnitId,
  288 + BaseUnitName: item["FBaseUnitId.FName"],
  289 + CreateDate: fCreateDate,
  290 + ModifyDate: fModifyDate,
  291 + ForbidDate: fForbidDate,
  292 + ApproveDate: fApproveDate,
  293 + MaterialGroup: materialGroup,
  294 + MaterialGroupNumber: item["FMaterialGroup.FNumber"],
  295 + MaterialGroupName: item["FMaterialGroup.FName"],
  296 + RefStatus: refStatus,
  297 + UseOrgId: fUseOrgId,
  298 + UseOrgName: item["FUseOrgId.FName"],
  299 + JoinProductId: 0,
  300 + DataVersion: nowTime.Unix(),
  301 + FCategoryID: item["FCategoryID"],
  302 + }
  303 + materialModels = append(materialModels, materialTemp)
  304 + }
  305 + return materialModels, nil
  306 +}
  307 +
212 //PullMaterialGroup 拉取物料分组 308 //PullMaterialGroup 拉取物料分组
213 func (srv *PullDataK3CloudService) PullMaterialGroup() error { 309 func (srv *PullDataK3CloudService) PullMaterialGroup() error {
214 client, err := newK3cloudClient() 310 client, err := newK3cloudClient()
@@ -462,6 +558,33 @@ func (srv *PullDataK3CloudService) PullPrdMo(timeFilter time.Time) error { @@ -462,6 +558,33 @@ func (srv *PullDataK3CloudService) PullPrdMo(timeFilter time.Time) error {
462 return nil 558 return nil
463 } 559 }
464 560
  561 +// PullMaterialCategory 拉取物料分类
  562 +func (srv *PullDataK3CloudService) PullMaterialCategory() (map[string]string, error) {
  563 + client, err := newK3cloudClient()
  564 + if err != nil {
  565 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  566 + }
  567 + fieldKeys := []string{
  568 + "FName", "FNUMBER", "FMasterId",
  569 + }
  570 + result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
  571 + FormId: "BD_MATERIALCATEGORY",
  572 + Data: k3cloud.ExecuteBillQueryData{
  573 + FormId: "BD_MATERIALCATEGORY",
  574 + FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
  575 + //TopRowCount: 4,
  576 +
  577 + FilterString: "",
  578 + },
  579 + })
  580 + categorys := result.ToMapString()
  581 + var categorysById = make(map[string]string)
  582 + for _, v := range categorys {
  583 + categorysById[v["FMasterId"]] = v["FName"]
  584 + }
  585 + return categorysById, nil
  586 +}
  587 +
465 // 同步产品 588 // 同步产品
466 func (srv *PullDataK3CloudService) SyncDataProduct(ptr *pgTransaction.TransactionContext, fromTime time.Time) error { 589 func (srv *PullDataK3CloudService) SyncDataProduct(ptr *pgTransaction.TransactionContext, fromTime time.Time) error {
467 prdMoDao, err := dao.NewMaterialK3cloudDao(ptr) 590 prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
@@ -612,3 +735,165 @@ func (srv *PullDataK3CloudService) SyncDataProductPlan(ptr *pgTransaction.Transa @@ -612,3 +735,165 @@ func (srv *PullDataK3CloudService) SyncDataProductPlan(ptr *pgTransaction.Transa
612 } 735 }
613 return nil 736 return nil
614 } 737 }
  738 +
  739 +// 同步产品
  740 +func (srv *PullDataK3CloudService) SyncDataMaterialGroup(ptr *pgTransaction.TransactionContext) error {
  741 + prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
  742 + if err != nil {
  743 + return err
  744 + }
  745 + var userService = domainService.NewUserService()
  746 + org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
  747 + if err != nil {
  748 + return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  749 + }
  750 + fromMaterialGroups, err := prdMoDao.SearchMaterialGroup() // 默认企业名称素天下、或者使用组织ID
  751 + if err != nil {
  752 + return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  753 + }
  754 + var (
  755 + cid = constant.MANUFACTURE_DEFAULT_COMPANYID
  756 + oid = constant.MANUFACTURE_DEFAULT_ORGID
  757 + )
  758 + productMaterialGroupRepository, _, _ := factory.FastProductMaterialGroup(ptr, 0)
  759 + _, materialGroups, err := productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
  760 + if err != nil {
  761 + return err
  762 + }
  763 + mapMaterialGroups := domain.ProductMaterialGroups(materialGroups).ToMapByGroupNumber()
  764 + mapFromMaterialGroups := models.MaterialGroupK3clouds(fromMaterialGroups).ToMapId()
  765 + for _, from := range fromMaterialGroups {
  766 + to, ok := mapMaterialGroups[from.Number]
  767 + if ok {
  768 + // 更新
  769 + if to.MaterialGroupName != from.Name {
  770 + log.Logger.Info(fmt.Sprintf("更新物料分组 old:%v new:%v", to.MaterialGroupName, from.Name), map[string]interface{}{"material": to})
  771 + to.MaterialGroupName = from.Name
  772 + }
  773 + continue
  774 + }
  775 + var parentId int
  776 + if from.ParentId > 0 {
  777 + parent, ok := mapFromMaterialGroups[from.ParentId]
  778 + if !ok {
  779 + log.Logger.Warn("parent node not exits", map[string]interface{}{"material": to})
  780 + continue
  781 + }
  782 + toParent, ok := mapMaterialGroups[parent.Number]
  783 + if !ok {
  784 + log.Logger.Warn("to parent node not exits", map[string]interface{}{"material": to})
  785 + continue
  786 + }
  787 + parentId = toParent.ProductMaterialGroupId
  788 + }
  789 + productMaterialGroup := &domain.ProductMaterialGroup{
  790 + CompanyId: cid,
  791 + OrgId: oid,
  792 + Pid: parentId,
  793 + MaterialGroupName: from.Name,
  794 + MaterialGroupNumber: from.Number,
  795 + CreatedAt: time.Now(),
  796 + UpdatedAt: time.Now(),
  797 + Ext: domain.NewExt(org.OrgName),
  798 + }
  799 + if productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup); err != nil {
  800 + return err
  801 + }
  802 + mapMaterialGroups[productMaterialGroup.MaterialGroupNumber] = productMaterialGroup
  803 + }
  804 + return nil
  805 +}
  806 +
  807 +// SyncDataMaterial 同步物料数据
  808 +// pullType 拉取数据方式 full:全量 其他:增量
  809 +func (srv *PullDataK3CloudService) SyncDataMaterial(ptr *pgTransaction.TransactionContext, pullType string, fromTime time.Time) error {
  810 + var (
  811 + lastTime = utils.GetZeroTime(time.Now()).Add(-time.Hour * 24) //前一天有修改的记录
  812 + org *domain.Org
  813 + err error
  814 + )
  815 + if pullType == "full" {
  816 + lastTime = time.Time{}
  817 + }
  818 +
  819 + var userService = domainService.NewUserService()
  820 + org, err = userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
  821 + if err != nil {
  822 + return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  823 + }
  824 +
  825 + var (
  826 + cid = constant.MANUFACTURE_DEFAULT_COMPANYID
  827 + oid = constant.MANUFACTURE_DEFAULT_ORGID
  828 + productMaterialRepository, _, _ = factory.FastProductMaterial(ptr, 0)
  829 + productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(ptr, 0)
  830 + materialGroups domain.ProductMaterialGroups
  831 + )
  832 +
  833 + _, materialGroups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
  834 + if err != nil {
  835 + return err
  836 + }
  837 + mapMaterialGroup := materialGroups.ToMapByGroupNumber()
  838 +
  839 + records, err := srv.pullMaterial(lastTime)
  840 + if err != nil {
  841 + return err
  842 + }
  843 +
  844 + mapMaterialCategory, err := srv.PullMaterialCategory()
  845 + if err != nil {
  846 + return err
  847 + }
  848 + log.Logger.Debug(fmt.Sprintf("【同步物料数据】查询数据条数:%v", len(records)))
  849 + _, materialsFromDb, _ := productMaterialRepository.Find(map[string]interface{}{"companyId": cid, "limit": 20000})
  850 + mapMaterialsFromDb := domain.ProductMaterials(materialsFromDb).ToMapByNumber()
  851 + for index, item := range records {
  852 + var (
  853 + material *domain.ProductMaterial
  854 + materialGroup *domain.ProductMaterialGroup
  855 + ok bool
  856 + attribute string //物料属性
  857 + category string //物料类别
  858 + )
  859 + if item.UseOrgName != "素天下" {
  860 + continue
  861 + }
  862 + if materialGroup, ok = mapMaterialGroup[item.MaterialGroupNumber]; !ok {
  863 + continue
  864 + }
  865 + if _, ok := mapMaterialsFromDb[item.Number]; ok {
  866 + continue
  867 + }
  868 + if v, ok := mapMaterialCategory[item.FCategoryID]; ok {
  869 + category = v
  870 + }
  871 + attribute = domain.MaterialAttributeDescription(item.ErpClsId)
  872 +
  873 + material = &domain.ProductMaterial{
  874 + CompanyId: cid,
  875 + OrgId: oid,
  876 + ProductMaterialGroupId: materialGroup.ProductMaterialGroupId,
  877 + MaterialName: item.Name,
  878 + MaterialNumber: item.Number,
  879 + MaterialAttribute: &domain.MaterialAttribute{Attribute: attribute},
  880 + MaterialCategory: &domain.MaterialCategory{Category: category},
  881 + ProductMaterialExt: &domain.MaterialExt{
  882 + Specification: item.Specification,
  883 + Unit: item.BaseUnitName,
  884 + ExpiredDay: 0,
  885 + Remark: "",
  886 + Source: "k3cloud",
  887 + },
  888 + CreatedAt: time.Now(),
  889 + UpdatedAt: time.Now(),
  890 + Ext: domain.NewExt(org.OrgName),
  891 + }
  892 + if material, err = productMaterialRepository.Save(material); err != nil {
  893 + log.Logger.Debug(fmt.Sprintf("同步失败 序号:%v 物料数据 id:%v number:%v name:%v 错误:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName, err.Error()))
  894 + continue
  895 + }
  896 + log.Logger.Debug(fmt.Sprintf("同步 序号:%v 物料数据 id:%v number:%v name:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName))
  897 + }
  898 + return nil
  899 +}
@@ -13,10 +13,13 @@ type MaterialUnitConversionDto struct { @@ -13,10 +13,13 @@ type MaterialUnitConversionDto struct {
13 ToUnitQuantity *domain.UnitQuantity `json:"toUnitQuantity,omitempty"` 13 ToUnitQuantity *domain.UnitQuantity `json:"toUnitQuantity,omitempty"`
14 } 14 }
15 15
16 -func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion) *MaterialUnitConversionDto { 16 +func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion, material *domain.ProductMaterial) *MaterialUnitConversionDto {
17 d.UnitConversionId = m.UnitConversionId 17 d.UnitConversionId = m.UnitConversionId
18 d.MaterialName = m.Material.MaterialName 18 d.MaterialName = m.Material.MaterialName
19 d.FromUnitQuantity = m.FromUnitQuantity 19 d.FromUnitQuantity = m.FromUnitQuantity
20 d.ToUnitQuantity = m.ToUnitQuantity 20 d.ToUnitQuantity = m.ToUnitQuantity
  21 + if material != nil {
  22 + d.MaterialName = material.MaterialName
  23 + }
21 return d 24 return d
22 } 25 }
@@ -25,7 +25,7 @@ type UnitConversionDto struct { @@ -25,7 +25,7 @@ type UnitConversionDto struct {
25 AuthFlag bool `json:"authFlag"` 25 AuthFlag bool `json:"authFlag"`
26 } 26 }
27 27
28 -func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitConversionDto { 28 +func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int, productMaterial *domain.ProductMaterial) *UnitConversionDto {
29 d.UnitConversionId = m.UnitConversionId 29 d.UnitConversionId = m.UnitConversionId
30 d.WorkStation = m.WorkStation 30 d.WorkStation = m.WorkStation
31 d.Material = m.Material 31 d.Material = m.Material
@@ -36,5 +36,8 @@ func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitCo @@ -36,5 +36,8 @@ func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitCo
36 if m.Ext != nil { 36 if m.Ext != nil {
37 d.OrgName = m.Ext.OrgName 37 d.OrgName = m.Ext.OrgName
38 } 38 }
  39 + if productMaterial != nil {
  40 + d.Material.MaterialName = productMaterial.MaterialName
  41 + }
39 return d 42 return d
40 } 43 }
@@ -91,12 +91,21 @@ func (unitConversionService *UnitConversionService) GetUnitConversion(getUnitCon @@ -91,12 +91,21 @@ func (unitConversionService *UnitConversionService) GetUnitConversion(getUnitCon
91 //var unitConversionRepository domain.UnitConversionRepository 91 //var unitConversionRepository domain.UnitConversionRepository
92 var unitConversion *domain.UnitConversion 92 var unitConversion *domain.UnitConversion
93 _, unitConversion, err = factory.FastPgUnitConversion(transactionContext, getUnitConversionQuery.UnitConversionId) 93 _, unitConversion, err = factory.FastPgUnitConversion(transactionContext, getUnitConversionQuery.UnitConversionId)
94 - 94 + if err != nil {
  95 + return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
  96 + }
  97 + var productMaterial *domain.ProductMaterial
  98 + if unitConversion.Material.ProductMaterialId > 0 {
  99 + _, productMaterial, err = factory.FastProductMaterial(transactionContext, unitConversion.Material.ProductMaterialId)
  100 + if err != nil {
  101 + return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
  102 + }
  103 + }
95 if err := transactionContext.CommitTransaction(); err != nil { 104 if err := transactionContext.CommitTransaction(); err != nil {
96 return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error()) 105 return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
97 } 106 }
98 result := &dto.UnitConversionDto{} 107 result := &dto.UnitConversionDto{}
99 - result.LoadDto(unitConversion, 0) 108 + result.LoadDto(unitConversion, 0, productMaterial)
100 return result, nil 109 return result, nil
101 110
102 } 111 }
@@ -293,17 +302,29 @@ func (unitConversionService *UnitConversionService) SearchUnitConversion(operate @@ -293,17 +302,29 @@ func (unitConversionService *UnitConversionService) SearchUnitConversion(operate
293 if err != nil { 302 if err != nil {
294 return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 303 return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
295 } 304 }
296 - if err := transactionContext.CommitTransaction(); err != nil {  
297 - return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error()) 305 +
  306 + var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
  307 + productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
  308 + if len(productMaterialIds) > 0 {
  309 + productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
  310 + _, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
  311 + if err != nil {
  312 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  313 + }
  314 + mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
298 } 315 }
299 316
300 var result = make([]*dto.UnitConversionDto, 0) 317 var result = make([]*dto.UnitConversionDto, 0)
301 for i := range unitConversions { 318 for i := range unitConversions {
302 item := unitConversions[i] 319 item := unitConversions[i]
303 newItem := &dto.UnitConversionDto{} 320 newItem := &dto.UnitConversionDto{}
304 - newItem.LoadDto(item, operateInfo.OrgId) 321 + newItem.LoadDto(item, operateInfo.OrgId, mapProductMaterial[item.Material.ProductMaterialId])
305 result = append(result, newItem) 322 result = append(result, newItem)
306 } 323 }
  324 +
  325 + if err := transactionContext.CommitTransaction(); err != nil {
  326 + return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  327 + }
307 return count, result, nil 328 return count, result, nil
308 } 329 }
309 330
@@ -331,11 +352,22 @@ func (unitConversionService *UnitConversionService) SearchMaterial(operateInfo * @@ -331,11 +352,22 @@ func (unitConversionService *UnitConversionService) SearchMaterial(operateInfo *
331 return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error()) 352 return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
332 } 353 }
333 354
  355 + var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
  356 + productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
  357 + if len(productMaterialIds) > 0 {
  358 + productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
  359 + _, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
  360 + if err != nil {
  361 + return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  362 + }
  363 + mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
  364 + }
  365 +
334 var result = make([]*dto.MaterialUnitConversionDto, 0) 366 var result = make([]*dto.MaterialUnitConversionDto, 0)
335 for i := range unitConversions { 367 for i := range unitConversions {
336 item := unitConversions[i] 368 item := unitConversions[i]
337 newItem := &dto.MaterialUnitConversionDto{} 369 newItem := &dto.MaterialUnitConversionDto{}
338 - newItem.LoadDto(item) 370 + newItem.LoadDto(item, mapProductMaterial[item.Material.ProductMaterialId])
339 result = append(result, newItem) 371 result = append(result, newItem)
340 } 372 }
341 return count, map[string]interface{}{ 373 return count, map[string]interface{}{
@@ -14,6 +14,7 @@ var HTTP_PORT int = 8081 @@ -14,6 +14,7 @@ var HTTP_PORT int = 8081
14 var CACHE_PREFIX = "allied-creation-manufacture-dev" 14 var CACHE_PREFIX = "allied-creation-manufacture-dev"
15 var LOG_LEVEL = "debug" 15 var LOG_LEVEL = "debug"
16 var LOG_FILE = "app.log" 16 var LOG_FILE = "app.log"
  17 +var PPROF_ON = true
17 18
18 //天联共创基础模块 19 //天联共创基础模块
19 var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com" 20 var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com"
@@ -45,5 +46,6 @@ func init() { @@ -45,5 +46,6 @@ func init() {
45 SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV) 46 SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV)
46 HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT) 47 HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT)
47 SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV) 48 SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
  49 + PPROF_ON = Configurator.DefaultBool("PPROF_ON", PPROF_ON)
48 CACHE_PREFIX = SERVICE_NAME 50 CACHE_PREFIX = SERVICE_NAME
49 } 51 }
@@ -28,10 +28,12 @@ var MQTT_HOST = "47.97.5.102" @@ -28,10 +28,12 @@ var MQTT_HOST = "47.97.5.102"
28 var MQTT_PORT = "6000" 28 var MQTT_PORT = "6000"
29 var MQTT_USER = "admin" 29 var MQTT_USER = "admin"
30 var MQTT_PASSWORD = "123456" 30 var MQTT_PASSWORD = "123456"
  31 +var MQTT_UP = true
31 32
32 func init() { 33 func init() {
33 MQTT_HOST = Configurator.DefaultString("MQTT_HOST", MQTT_HOST) 34 MQTT_HOST = Configurator.DefaultString("MQTT_HOST", MQTT_HOST)
34 MQTT_PORT = Configurator.DefaultString("MQTT_PORT", MQTT_PORT) 35 MQTT_PORT = Configurator.DefaultString("MQTT_PORT", MQTT_PORT)
35 MQTT_USER = Configurator.DefaultString("MQTT_USER", MQTT_USER) 36 MQTT_USER = Configurator.DefaultString("MQTT_USER", MQTT_USER)
36 MQTT_PASSWORD = Configurator.DefaultString("MQTT_PASSWORD", MQTT_PASSWORD) 37 MQTT_PASSWORD = Configurator.DefaultString("MQTT_PASSWORD", MQTT_PASSWORD)
  38 + MQTT_UP = Configurator.DefaultBool("MQTT_UP", MQTT_UP)
37 } 39 }
@@ -7,6 +7,8 @@ import ( @@ -7,6 +7,8 @@ import (
7 7
8 const MaxQueryRow = 10000 8 const MaxQueryRow = 10000
9 9
  10 +const PathSegment = ","
  11 +
10 // 班次 12 // 班次
11 const ( 13 const (
12 WorkOnFullDay = 1 //全天 14 WorkOnFullDay = 1 //全天
@@ -2,6 +2,9 @@ package domain @@ -2,6 +2,9 @@ package domain
2 2
3 // 冗余附加数据 3 // 冗余附加数据
4 type Ext struct { 4 type Ext struct {
  5 + // 操作人
  6 + Operator *User `json:"operator,omitempty"`
  7 +
5 // 组织名称 8 // 组织名称
6 OrgName string `json:"orgName,omitempty"` 9 OrgName string `json:"orgName,omitempty"`
7 10
@@ -35,3 +38,8 @@ func (e *Ext) WithProductPlanExt(ext *ProductPlanExt) *Ext { @@ -35,3 +38,8 @@ func (e *Ext) WithProductPlanExt(ext *ProductPlanExt) *Ext {
35 e.ProductPlanExt = ext 38 e.ProductPlanExt = ext
36 return e 39 return e
37 } 40 }
  41 +
  42 +func (e *Ext) WithOperator(ext *User) *Ext {
  43 + e.Operator = ext
  44 + return e
  45 +}
@@ -2,8 +2,36 @@ package domain @@ -2,8 +2,36 @@ package domain
2 2
3 // 物料 3 // 物料
4 type Material struct { 4 type Material struct {
5 - // 物料名称 5 + // 物料ID
  6 + ProductMaterialId int `json:"productMaterialId"`
  7 + // 物料名称 (最新数据需要查询物料表)
6 MaterialName string `json:"materialName,omitempty"` 8 MaterialName string `json:"materialName,omitempty"`
7 - // 物料类别 9 + // 物料类别 ‘南瓜饼串’、‘ 包装袋(空)’、‘包装袋(件数)’、装箱(件数)
8 MaterialCategory string `json:"materialCategory,omitempty"` 10 MaterialCategory string `json:"materialCategory,omitempty"`
9 } 11 }
  12 +
  13 +// 物料类别
  14 +type MaterialCategory struct {
  15 + //Id int `json:"id"`
  16 + Category string `json:"category"`
  17 +}
  18 +
  19 +// 物料属性
  20 +type MaterialAttribute struct {
  21 + //Id int `json:"id"`
  22 + Attribute string `json:"attribute"`
  23 +}
  24 +
  25 +// 物料扩展数据
  26 +type MaterialExt struct {
  27 + // 规格
  28 + Specification string `json:"specification"`
  29 + // 单位
  30 + Unit string `json:"unit"`
  31 + // 保质期 单位:天
  32 + ExpiredDay int `json:"expiredDay"`
  33 + // 备注
  34 + Remark string `json:"remark"`
  35 + // 来源 k3cloud
  36 + Source string `json:"source"`
  37 +}
@@ -2,6 +2,7 @@ package domain @@ -2,6 +2,7 @@ package domain
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
5 "strconv" 6 "strconv"
6 "time" 7 "time"
7 ) 8 )
@@ -99,15 +100,18 @@ type ImportProductItem struct { @@ -99,15 +100,18 @@ type ImportProductItem struct {
99 } 100 }
100 101
101 func (item *ImportProductItem) Valid() error { 102 func (item *ImportProductItem) Valid() error {
102 - if len(item.ProductName) == 0 {  
103 - return fmt.Errorf("品名不能为空")  
104 - }  
105 - if len(item.Unit) == 0 {  
106 - return fmt.Errorf("规格不能为空")  
107 - }  
108 - if len(item.ProductCategory) == 0 {  
109 - return fmt.Errorf("类别不能为空") 103 + if len(item.ProductCode) == 0 {
  104 + return fmt.Errorf("产品编号不能为空")
110 } 105 }
  106 + //if len(item.ProductName) == 0 {
  107 + // return fmt.Errorf("品名不能为空")
  108 + //}
  109 + //if len(item.Unit) == 0 {
  110 + // return fmt.Errorf("规格不能为空")
  111 + //}
  112 + //if len(item.ProductCategory) == 0 {
  113 + // return fmt.Errorf("类别不能为空")
  114 + //}
111 if len(item.UnitWeight) == 0 { 115 if len(item.UnitWeight) == 0 {
112 item.UnitWeight = "0" 116 item.UnitWeight = "0"
113 } 117 }
@@ -116,3 +120,13 @@ func (item *ImportProductItem) Valid() error { @@ -116,3 +120,13 @@ func (item *ImportProductItem) Valid() error {
116 } 120 }
117 return nil 121 return nil
118 } 122 }
  123 +
  124 +type Products []*Product
  125 +
  126 +func (products Products) ProductCodes() []string {
  127 + var result = utils.NewSet()
  128 + for _, v := range products {
  129 + result.Add(v.ProductCode)
  130 + }
  131 + return result.KeysStr()
  132 +}
@@ -80,15 +80,48 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr @@ -80,15 +80,48 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr
80 if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) { 80 if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) {
81 return 0 81 return 0
82 } 82 }
83 - wt := utils.Round(productAttendanceRecord.SignOut.Sub(productAttendanceRecord.SignIn).Hours(), 1) 83 + signIn := roundTime(productAttendanceRecord.SignIn)
  84 + signOut := roundTime(productAttendanceRecord.SignOut)
  85 + wt := utils.Round(signOut.Sub(signIn).Hours(), 2)
84 if productCalendar == nil { 86 if productCalendar == nil {
85 - return wt 87 + return roundWorkTime(wt)
86 } 88 }
87 wt = wt - productAttendanceRecord.AttendanceBreakTime(productCalendar) 89 wt = wt - productAttendanceRecord.AttendanceBreakTime(productCalendar)
88 if wt < 0 { 90 if wt < 0 {
89 return 0 91 return 0
90 } 92 }
91 - return wt 93 + return roundWorkTime(wt)
  94 +}
  95 +
  96 +// roundWorkTime 工时取整[0:0.167]=> 0 \ [0.167,0.667]=> 0.5 \ [0.667,1]=>1
  97 +// 10/60 = 0.167 40/60 = 0.667
  98 +func roundWorkTime(wt float64) float64 {
  99 + i := float64(int(wt))
  100 + f := wt - i
  101 + if f < 0.167 {
  102 + return i
  103 + }
  104 + if f >= 0.167 && f < 0.667 {
  105 + return i + 0.5
  106 + }
  107 + if f >= 0.667 {
  108 + return i + 1
  109 + }
  110 + return i
  111 +}
  112 +
  113 +func roundTime(t time.Time) time.Time {
  114 + hour, min, _ := t.Local().Clock()
  115 + y, m, d := t.Local().Date()
  116 + newTime := time.Date(y, m, d, hour, 0, 0, 0, time.Local)
  117 + if min < 11 {
  118 + min = 0
  119 + } else if min >= 11 && min < 41 {
  120 + min = 30
  121 + } else {
  122 + min = 60
  123 + }
  124 + return newTime.Add(time.Minute * time.Duration(min))
92 } 125 }
93 126
94 func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error { 127 func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error {
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 生产物料
  6 +type ProductMaterial struct {
  7 + // 物料ID
  8 + ProductMaterialId int `json:"productMaterialId"`
  9 + // 企业id
  10 + CompanyId int `json:"companyId"`
  11 + // 组织ID
  12 + OrgId int `json:"orgId"`
  13 + // 物料分组ID
  14 + ProductMaterialGroupId int `json:"productMaterialGroupId"`
  15 + // 物料编码
  16 + MaterialNumber string `json:"materialNumber"`
  17 + // 物料名称
  18 + MaterialName string `json:"materialName"`
  19 + // 物料属性
  20 + MaterialAttribute *MaterialAttribute `json:"materialAttribute"`
  21 + // 物料类别
  22 + MaterialCategory *MaterialCategory `json:"materialCategory"`
  23 + // 物料扩展
  24 + ProductMaterialExt *MaterialExt `json:"productMaterialExt"`
  25 + // 创建时间
  26 + CreatedAt time.Time `json:"createdAt"`
  27 + // 更新时间
  28 + UpdatedAt time.Time `json:"updatedAt"`
  29 + // 删除时间
  30 + DeletedAt time.Time `json:"deletedAt"`
  31 + // 扩展
  32 + Ext *Ext `json:"ext"`
  33 +}
  34 +
  35 +type ProductMaterialRepository interface {
  36 + Save(productMaterial *ProductMaterial) (*ProductMaterial, error)
  37 + Remove(productMaterial *ProductMaterial) (*ProductMaterial, error)
  38 + FindOne(queryOptions map[string]interface{}) (*ProductMaterial, error)
  39 + Find(queryOptions map[string]interface{}) (int64, []*ProductMaterial, error)
  40 +}
  41 +
  42 +func (productMaterial *ProductMaterial) Identify() interface{} {
  43 + if productMaterial.ProductMaterialId == 0 {
  44 + return nil
  45 + }
  46 + return productMaterial.ProductMaterialId
  47 +}
  48 +
  49 +func (productMaterial *ProductMaterial) Update(data map[string]interface{}) error {
  50 + return nil
  51 +}
  52 +
  53 +type ProductMaterials []*ProductMaterial
  54 +
  55 +func (productMaterials ProductMaterials) ToMapById() map[int]*ProductMaterial {
  56 + var mapProductMaterial = make(map[int]*ProductMaterial, 0)
  57 + for _, v := range productMaterials {
  58 + mapProductMaterial[v.ProductMaterialId] = v
  59 + }
  60 + return mapProductMaterial
  61 +}
  62 +
  63 +func (productMaterials ProductMaterials) ToMapByNumber() map[string]*ProductMaterial {
  64 + var mapProductMaterial = make(map[string]*ProductMaterial, 0)
  65 + for _, v := range productMaterials {
  66 + mapProductMaterial[v.MaterialNumber] = v
  67 + }
  68 + return mapProductMaterial
  69 +}
  70 +
  71 +// 10:资产,9:配置,2:自制,11:费用,12:模型,5:虚拟,7:一次性,13:产品系列 12:模型,3:委外,4:特征,6:服务,1:外购
  72 +var mapMaterialCategory = map[int]string{
  73 + 1: "外购",
  74 + 2: "自制",
  75 + 3: "委外",
  76 + 4: "特征",
  77 + 5: "虚拟",
  78 + 6: "服务",
  79 + 7: "一次性",
  80 + 8: "",
  81 + 9: "配置",
  82 + 10: "资产",
  83 + 11: "费用",
  84 + 12: "模型",
  85 + 13: "产品系列",
  86 +}
  87 +
  88 +func MaterialAttributeDescription(code int) string {
  89 + if v, ok := mapMaterialCategory[code]; ok {
  90 + return v
  91 + }
  92 + return ""
  93 +}
  1 +package domain
  2 +
  3 +import (
  4 + "fmt"
  5 + "strconv"
  6 + "time"
  7 +)
  8 +
  9 +// 物料分组
  10 +type ProductMaterialGroup struct {
  11 + // 物料分组ID
  12 + ProductMaterialGroupId int `json:"productMaterialGroupId"`
  13 + // 企业id
  14 + CompanyId int `json:"companyId"`
  15 + // 组织ID
  16 + OrgId int `json:"orgId"`
  17 + // 父级ID
  18 + Pid int `json:"pid"`
  19 + // 路径 (不使用,如果父级改变的话,子级的Path要做更新)
  20 + //Path string `json:"path"`
  21 + // 物料分组名称
  22 + MaterialGroupName string `json:"materialGroupName"`
  23 + // 物料分组编码
  24 + MaterialGroupNumber string `json:"materialGroupNumber"`
  25 + // 创建时间
  26 + CreatedAt time.Time `json:"createdAt"`
  27 + // 更新时间
  28 + UpdatedAt time.Time `json:"updatedAt"`
  29 + // 删除时间
  30 + DeletedAt time.Time `json:"deletedAt"`
  31 + // 扩展数据
  32 + Ext *Ext `json:"ext,omitempty"`
  33 +}
  34 +
  35 +type ProductMaterialGroupRepository interface {
  36 + Save(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
  37 + Remove(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
  38 + FindOne(queryOptions map[string]interface{}) (*ProductMaterialGroup, error)
  39 + Find(queryOptions map[string]interface{}) (int64, []*ProductMaterialGroup, error)
  40 +}
  41 +
  42 +func (productMaterialGroup *ProductMaterialGroup) Identify() interface{} {
  43 + if productMaterialGroup.ProductMaterialGroupId == 0 {
  44 + return nil
  45 + }
  46 + return productMaterialGroup.ProductMaterialGroupId
  47 +}
  48 +
  49 +func (productMaterialGroup *ProductMaterialGroup) Update(data map[string]interface{}) error {
  50 + return nil
  51 +}
  52 +
  53 +func (productMaterialGroup *ProductMaterialGroup) GroupNumberComposeUp(parent *ProductMaterialGroup, latestNumber string, total int) string {
  54 + iNumber, err := strconv.ParseInt(latestNumber, 10, 64)
  55 +
  56 + if err == nil {
  57 + iNumber += 1
  58 + return formatFunc(iNumber)
  59 + }
  60 + if parent != nil {
  61 + return parent.MaterialGroupNumber + formatFunc(int64(total+1))
  62 + }
  63 + return formatFunc(int64(total + 1))
  64 +}
  65 +
  66 +func formatFunc(iNumber int64) string {
  67 + sNumber := fmt.Sprintf("%d", iNumber)
  68 + if len(sNumber)%2 == 1 {
  69 + return "0" + sNumber
  70 + }
  71 + return sNumber
  72 +}
  73 +
  74 +/***** 1.实现树 *****/
  75 +
  76 +func (productMaterialGroup *ProductMaterialGroup) PID() string {
  77 + return fmt.Sprintf("%d", productMaterialGroup.Pid)
  78 +}
  79 +func (productMaterialGroup *ProductMaterialGroup) ID() string {
  80 + return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
  81 +}
  82 +
  83 +type ProductMaterialGroups []*ProductMaterialGroup
  84 +
  85 +func (tree ProductMaterialGroups) Len() int {
  86 + return len(tree)
  87 +}
  88 +
  89 +func (tree ProductMaterialGroups) Less(i, j int) bool {
  90 + if tree[i].Pid < tree[j].Pid {
  91 + return true
  92 + }
  93 + if tree[i].Pid == tree[j].Pid {
  94 + return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
  95 + }
  96 + return false
  97 +}
  98 +
  99 +func (tree ProductMaterialGroups) Swap(i, j int) {
  100 + tree[i], tree[j] = tree[j], tree[i]
  101 +}
  102 +
  103 +func (tree ProductMaterialGroups) ToMapByGroupNumber() map[string]*ProductMaterialGroup {
  104 + var result = make(map[string]*ProductMaterialGroup)
  105 + for i := range tree {
  106 + result[tree[i].MaterialGroupNumber] = tree[i]
  107 + }
  108 + return result
  109 +}
@@ -15,8 +15,11 @@ const ( @@ -15,8 +15,11 @@ const (
15 ) 15 )
16 16
17 const ( 17 const (
18 - ProductRecordNotApprove = 1 // 未审核  
19 - ProductRecordApproved = 2 // 已审核 18 + ProductRecordNotApprove = 1 // 未审核
  19 + ProductRecordApproved = 2 // 已审核
  20 + ProductRecordWithdraw = 3 // 已撤回
  21 + ProductRecordLogged = 4 // 已记录
  22 + ProductRecordAutoApproved = 5 // 自动审核
20 ) 23 )
21 24
22 // 生产记录 25 // 生产记录
@@ -82,6 +85,21 @@ func (productRecord *ProductRecord) Approve(approveUser *User, weighAfter float6 @@ -82,6 +85,21 @@ func (productRecord *ProductRecord) Approve(approveUser *User, weighAfter float6
82 return nil 85 return nil
83 } 86 }
84 87
  88 +func (productRecord *ProductRecord) Cancel() error {
  89 + if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordApproved {
  90 + return errors.New("已审核")
  91 + }
  92 + if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordWithdraw {
  93 + return errors.New("已撤销")
  94 + }
  95 + //if xtime.BeforeEqual(productRecord.CreatedAt, xtime.BeginningOfDay()) {
  96 + // return errors.New("已记录")
  97 + //}
  98 + productRecord.ProductRecordInfo.ApproveStatus = ProductRecordWithdraw
  99 + productRecord.UpdatedAt = time.Now()
  100 + return nil
  101 +}
  102 +
85 func TaskKeyPatternProductRecordStatics() string { 103 func TaskKeyPatternProductRecordStatics() string {
86 return fmt.Sprintf("%v:task:product-record:statics", constant.CACHE_PREFIX) 104 return fmt.Sprintf("%v:task:product-record:statics", constant.CACHE_PREFIX)
87 } 105 }
@@ -11,7 +11,7 @@ const ( @@ -11,7 +11,7 @@ const (
11 ) 11 )
12 12
13 const ( 13 const (
14 - ProductSection1 = "打料" 14 + ProductSection1 = "制模"
15 ProductSection2 = "成型" 15 ProductSection2 = "成型"
16 ProductSection3 = "穿串" 16 ProductSection3 = "穿串"
17 ProductSection4 = "包装" 17 ProductSection4 = "包装"
@@ -12,7 +12,7 @@ type ProductRecordInfo struct { @@ -12,7 +12,7 @@ type ProductRecordInfo struct {
12 WeighBefore float64 `json:"weighBefore"` 12 WeighBefore float64 `json:"weighBefore"`
13 // 产能-审核后 13 // 产能-审核后
14 WeighAfter float64 `json:"weighAfter"` 14 WeighAfter float64 `json:"weighAfter"`
15 - // 审核状态 1:未审核 2:已审核 15 + // 审核状态 1:未审核 2:已审核 3.已撤回 4.已记录 5.自动审核
16 ApproveStatus int `json:"approveStatus"` 16 ApproveStatus int `json:"approveStatus"`
17 // 审核时间 17 // 审核时间
18 ApproveAt int64 `json:"approveAt"` 18 ApproveAt int64 `json:"approveAt"`
1 package domain 1 package domain
2 2
3 -import "time" 3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  5 + "time"
  6 +)
4 7
5 // 单位换算 8 // 单位换算
6 type UnitConversion struct { 9 type UnitConversion struct {
@@ -57,3 +60,16 @@ func (unitConversion *UnitConversion) Update(data map[string]interface{}) error @@ -57,3 +60,16 @@ func (unitConversion *UnitConversion) Update(data map[string]interface{}) error
57 unitConversion.UpdatedAt = time.Now() 60 unitConversion.UpdatedAt = time.Now()
58 return nil 61 return nil
59 } 62 }
  63 +
  64 +type UnitConversions []*UnitConversion
  65 +
  66 +func (unitConversions UnitConversions) ProductMaterialIds() []int {
  67 + set := utils.NewSet()
  68 + for i := range unitConversions {
  69 + if unitConversions[i].Material.ProductMaterialId == 0 {
  70 + continue
  71 + }
  72 + set.Add(unitConversions[i].Material.ProductMaterialId)
  73 + }
  74 + return set.KeysInt()
  75 +}
@@ -6,6 +6,15 @@ const ( @@ -6,6 +6,15 @@ const (
6 EmployeePartTime = 3 // 临时 6 EmployeePartTime = 3 // 临时
7 ) 7 )
8 8
  9 +// 用户状态
  10 +const (
  11 + UserStatusEnable UserStatus = 1
  12 + UserStatusDisable UserStatus = 2
  13 + UserStatusDestroy UserStatus = 3
  14 +)
  15 +
  16 +type UserStatus int
  17 +
9 // 用户对象 18 // 用户对象
10 type User struct { 19 type User struct {
11 // 用户Id 用户唯一标识 20 // 用户Id 用户唯一标识
@@ -21,6 +30,8 @@ type User struct { @@ -21,6 +30,8 @@ type User struct {
21 // 手机号码 30 // 手机号码
22 Phone string `json:"phone,omitempty"` 31 Phone string `json:"phone,omitempty"`
23 32
  33 + // 启用状态
  34 + EnableStatus int `json:"-"`
24 // 额外扩展的参数 35 // 额外扩展的参数
25 GroupId int `json:"-"` 36 GroupId int `json:"-"`
26 GroupName string `json:"-"` 37 GroupName string `json:"-"`
@@ -176,3 +176,12 @@ func (gateway HttpLibAlliedCreationUser) OrgSearch(param ReqOrgSearch) (int, []* @@ -176,3 +176,12 @@ func (gateway HttpLibAlliedCreationUser) OrgSearch(param ReqOrgSearch) (int, []*
176 err := gateway.FastDoRequest(url, method, param, &data) 176 err := gateway.FastDoRequest(url, method, param, &data)
177 return data.Count, data.Orgs, err 177 return data.Count, data.Orgs, err
178 } 178 }
  179 +
  180 +// TerminalReport 终端汇报
  181 +func (gateway HttpLibAlliedCreationUser) TerminalReport(param ReqTerminalReport) (DataTerminalReport, error) {
  182 + url := gateway.Host() + "/terminal/report"
  183 + method := "post"
  184 + var data DataTerminalReport
  185 + err := gateway.FastDoRequest(url, method, param, &data)
  186 + return data, err
  187 +}
@@ -163,3 +163,21 @@ type ( @@ -163,3 +163,21 @@ type (
163 Orgs []*models.Organization `json:"orgs"` 163 Orgs []*models.Organization `json:"orgs"`
164 } 164 }
165 ) 165 )
  166 +
  167 +//返回组织列表
  168 +type (
  169 + ReqTerminalReport struct {
  170 + TerminalType string `json:"terminalType"`
  171 + TerminalId string `json:"terminalId"`
  172 + Command string `json:"command"`
  173 + Content string `json:"content"`
  174 + Table string `json:"table"`
  175 +
  176 + CompanyId int64 `json:"companyId"`
  177 + OrgId int64 `json:"orgId"`
  178 + }
  179 +
  180 + DataTerminalReport struct {
  181 + Response string `json:"response"`
  182 + }
  183 +)
@@ -25,7 +25,6 @@ func (dao *DeviceDailyRunningRecordDao) TimeSectionRunningRecord(companyId, orgI @@ -25,7 +25,6 @@ func (dao *DeviceDailyRunningRecordDao) TimeSectionRunningRecord(companyId, orgI
25 25
26 tx := dao.transactionContext.PgTx 26 tx := dao.transactionContext.PgTx
27 sql := fmt.Sprintf(` 27 sql := fmt.Sprintf(`
28 -  
29 WITH ts_product as( 28 WITH ts_product as(
30 select sum(a.weight) total,a.ts from ( 29 select sum(a.weight) total,a.ts from (
31 select 30 select
@@ -38,7 +37,7 @@ WITH ts_product as( @@ -38,7 +37,7 @@ WITH ts_product as(
38 and work_station->>'workshopId'='?' 37 and work_station->>'workshopId'='?'
39 and work_station->>'lineId'='?' 38 and work_station->>'lineId'='?'
40 and work_station->>'sectionName'=? 39 and work_station->>'sectionName'=?
41 - and created_at >? 40 + and created_at >=?
42 and created_at <? 41 and created_at <?
43 ) a 42 ) a
44 group by a.ts 43 group by a.ts
@@ -47,14 +46,14 @@ WITH ts_product as( @@ -47,14 +46,14 @@ WITH ts_product as(
47 -- select * from ts_product 46 -- select * from ts_product
48 , ts_product_list as ( 47 , ts_product_list as (
49 select d.ts,ts_product.total from ( 48 select d.ts,ts_product.total from (
50 - select to_char(c.ts::timestamp,'mm-dd') ts from (  
51 - select generate_series(to_timestamp(?),to_timestamp(?),'1 day') ts 49 + select to_char(c.ts,'mm-dd') ts from (
  50 + 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
52 ) c ) d left join ts_product on d.ts = ts_product.ts 51 ) c ) d left join ts_product on d.ts = ts_product.ts
53 ) 52 )
54 SELECT ts, coalesce(total,0) total 53 SELECT ts, coalesce(total,0) total
55 from ts_product_list 54 from ts_product_list
56 `) 55 `)
57 - if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime.Unix(), endTime.Unix()); err != nil { 56 + if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime); err != nil {
58 return err 57 return err
59 } 58 }
60 return nil 59 return nil
@@ -120,7 +119,7 @@ select * from device_running_oee @@ -120,7 +119,7 @@ select * from device_running_oee
120 } 119 }
121 120
122 // 时段产能 121 // 时段产能
123 -func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, result interface{}) error { 122 +func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, endTime time.Time, result interface{}) error {
124 123
125 tx := dao.transactionContext.PgTx 124 tx := dao.transactionContext.PgTx
126 sql := fmt.Sprintf(` 125 sql := fmt.Sprintf(`
@@ -137,7 +136,8 @@ WITH ts_product as( @@ -137,7 +136,8 @@ WITH ts_product as(
137 and work_station->>'lineId'='?' 136 and work_station->>'lineId'='?'
138 and work_station->>'sectionName'=? 137 and work_station->>'sectionName'=?
139 and device_running_record_info->>'deviceType'='CCJ' 138 and device_running_record_info->>'deviceType'='CCJ'
140 - and created_at >? 139 + and created_at >=?
  140 + and created_at < ?
141 ) a 141 ) a
142 group by a.ts 142 group by a.ts
143 order by ts 143 order by ts
@@ -145,19 +145,15 @@ WITH ts_product as( @@ -145,19 +145,15 @@ WITH ts_product as(
145 -- select * from ts_product 145 -- select * from ts_product
146 , ts_product_list as ( 146 , ts_product_list as (
147 select d.ts,ts_product.total from ( 147 select d.ts,ts_product.total from (
148 - select to_char(c.ts::timestamp,'HH24:MI') ts from (  
149 - select generate_series(a.end - interval '5 hour',  
150 - "replace"(to_char(a.end, 'yyyy-mm-dd HH24:') || cast(date_part('minute',a.end) as integer)/30*30+30, ':0', ':00')::timestamp,  
151 - '30 minute') ts from (  
152 - select to_timestamp(to_char(now() at time ZONE 'Asia/shanghai','yyyy-mm-dd HH24'),'yyyy-mm-dd HH24') as end  
153 - ) a  
154 - ) c 148 + 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 (
  149 + select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),'30 minute') created_at
  150 + ) a
155 ) d left join ts_product on d.ts = ts_product.ts 151 ) d left join ts_product on d.ts = ts_product.ts
156 ) 152 )
157 SELECT ts, coalesce(total,0) total 153 SELECT ts, coalesce(total,0) total
158 from ts_product_list 154 from ts_product_list
159 `) 155 `)
160 - if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime); err != nil { 156 + if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime.Add(-time.Minute*1)); err != nil {
161 return err 157 return err
162 } 158 }
163 return nil 159 return nil
@@ -178,3 +178,13 @@ func (d *MaterialK3cloudDao) GetLastVersion() (int64, error) { @@ -178,3 +178,13 @@ func (d *MaterialK3cloudDao) GetLastVersion() (int64, error) {
178 } 178 }
179 return materialData[0].DataVersion, nil 179 return materialData[0].DataVersion, nil
180 } 180 }
  181 +
  182 +func (d *MaterialK3cloudDao) SearchMaterialGroup() ([]*models.MaterialGroupK3cloud, error) {
  183 + var materialData []*models.MaterialGroupK3cloud
  184 + query := d.transactionContext.PgTx.Model(&materialData)
  185 + query.OrderExpr("number asc")
  186 + if err := query.Select(); err != nil {
  187 + return nil, err
  188 + }
  189 + return materialData, nil
  190 +}
@@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC @@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC
29 // 日期 29 // 日期
30 // 产品编号 30 // 产品编号
31 // 调度状态 status 31 // 调度状态 status
32 -func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) { 32 +func (dao *ProductPlanDispatchRecordDao) ProductPlanDispatchRecord(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
33 tx := dao.transactionContext.PgTx 33 tx := dao.transactionContext.PgTx
34 productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord) 34 productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord)
35 query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{}) 35 query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{})
@@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, @@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
37 query.Where("org_id = ?", orgId) 37 query.Where("org_id = ?", orgId)
38 query.Where("work_station->>'workStationId'=?", workStationId) 38 query.Where("work_station->>'workStationId'=?", workStationId)
39 query.Where("product_date = ?", date) 39 query.Where("product_date = ?", date)
40 - query.Where("plan_dispatch_status = ?", status) 40 + if status > 0 {
  41 + query.Where("plan_dispatch_status = ?", status)
  42 + }
41 query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode) 43 query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode)
42 query.Order("updated_at desc") 44 query.Order("updated_at desc")
43 if err := query.First(); err != nil { 45 if err := query.First(); err != nil {
@@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, @@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
53 return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel) 55 return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel)
54 } 56 }
55 } 57 }
  58 +
  59 +func (dao *ProductPlanDispatchRecordDao) ProductPlan(companyId, orgId int, workshopId int, date time.Time, productCode string) (*domain.ProductPlan, error) {
  60 + tx := dao.transactionContext.PgTx
  61 + productPlan := new(models.ProductPlan)
  62 + query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
  63 + query.Where("company_id = ?", companyId)
  64 + query.Where("org_id = ?", orgId)
  65 + query.Where("workshop->>'workshopId'='?'", workshopId)
  66 + query.Where("product_date = ?", date)
  67 + if len(productCode) > 0 {
  68 + query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
  69 + }
  70 + query.Order("updated_at desc")
  71 + if err := query.First(); err != nil {
  72 + if err.Error() == "pg: no rows in result set" {
  73 + return nil, domain.ErrorNotFound
  74 + } else {
  75 + return nil, err
  76 + }
  77 + }
  78 + if productPlan.ProductPlanId == 0 {
  79 + return nil, nil
  80 + } else {
  81 + return transform.TransformToProductPlanDomainModelFromPgModels(productPlan)
  82 + }
  83 +}
  84 +
  85 +func (dao *ProductPlanDispatchRecordDao) ProductPlans(companyId, orgId int, workshopId int, date time.Time, productCode string) ([]*domain.ProductPlan, error) {
  86 + tx := dao.transactionContext.PgTx
  87 + productPlan := new(models.ProductPlan)
  88 + query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
  89 + query.Where("company_id = ?", companyId)
  90 + query.Where("org_id = ?", orgId)
  91 + query.Where("workshop->>'workshopId'='?'", workshopId)
  92 + query.Where("product_date = ?", date)
  93 + if len(productCode) > 0 {
  94 + query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
  95 + }
  96 + query.Order("updated_at desc")
  97 + var productPlanModels = make([]*models.ProductPlan, 0)
  98 + var productPlans = make([]*domain.ProductPlan, 0)
  99 + if err := query.Select(&productPlanModels); err != nil {
  100 + return productPlans, err
  101 + } else {
  102 + for _, productPlanModel := range productPlanModels {
  103 + if productPlan, err := transform.TransformToProductPlanDomainModelFromPgModels(productPlanModel); err != nil {
  104 + return productPlans, err
  105 + } else {
  106 + productPlans = append(productPlans, productPlan)
  107 + }
  108 + }
  109 + return productPlans, nil
  110 + }
  111 +}
@@ -170,3 +170,18 @@ func (d *PrdMoK3cloudDao) GetLatestData(fromTime time.Time) ([]*models.PrdMoK3cl @@ -170,3 +170,18 @@ func (d *PrdMoK3cloudDao) GetLatestData(fromTime time.Time) ([]*models.PrdMoK3cl
170 } 170 }
171 return result, nil 171 return result, nil
172 } 172 }
  173 +
  174 +// GetLatestMaterialData 增量获取物料数据
  175 +func (d *PrdMoK3cloudDao) GetLatestMaterialData(fromTime time.Time, offset, limit int) ([]*models.MaterialK3cloud, int, error) {
  176 + m := new(models.MaterialK3cloud)
  177 + result := make([]*models.MaterialK3cloud, 0)
  178 + query := d.transactionContext.PgTx.Model(m)
  179 + if !fromTime.IsZero() {
  180 + query.Where("modify_date>=?", fromTime)
  181 + }
  182 + err := query.Select(&result)
  183 + if err != nil {
  184 + return nil, 0, err
  185 + }
  186 + return result, len(result), nil
  187 +}
  1 +package dao
  2 +
  3 +import (
  4 + "fmt"
  5 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
  7 +)
  8 +
  9 +type ProductMaterialGroupDao struct {
  10 + transactionContext *pgTransaction.TransactionContext
  11 +}
  12 +
  13 +func (dao *ProductMaterialGroupDao) CurrentGroupLatestNumber(companyId int, productMaterialGroupId int) (string, int, error) {
  14 + m := new(models.ProductMaterialGroup)
  15 + var result string
  16 + var total int
  17 + query := dao.transactionContext.PgTx.Model(m).Where("company_id = ?", companyId)
  18 + query.Where("pid = ?", productMaterialGroupId)
  19 + query.ColumnExpr("max(material_group_number) number")
  20 + query.ColumnExpr("count(material_group_number) total")
  21 + query.AllWithDeleted()
  22 + err := query.Select(&result, &total)
  23 + return result, total, err
  24 +}
  25 +
  26 +func NewProductMaterialGroupDao(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupDao, error) {
  27 + if transactionContext == nil {
  28 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  29 + } else {
  30 + return &ProductMaterialGroupDao{
  31 + transactionContext: transactionContext,
  32 + }, nil
  33 + }
  34 +}
@@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from ( @@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from (
117 and product_record_info->>'approveStatus'='2' 117 and product_record_info->>'approveStatus'='2'
118 and created_at >=? 118 and created_at >=?
119 and created_at <? 119 and created_at <?
120 - and work_station->>'sectionName' in ('打料','成型','穿串','包装') 120 + and work_station->>'sectionName' in ('制模','成型','穿串','包装')
121 ) a 121 ) a
122 group by a.workStationId 122 group by a.workStationId
123 ) 123 )
@@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0) @@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0)
127 ) 127 )
128 --select * from item_product_rate 128 --select * from item_product_rate
129 select a.sname, coalesce(b.rate,0) rate from ( 129 select a.sname, coalesce(b.rate,0) rate from (
130 - select unnest(ARRAY ['打料','成型','穿串','包装']) sname 130 + select unnest(ARRAY ['制模','成型','穿串','包装']) sname
131 ) a left join item_product_rate b on a.sname=b.sname`) 131 ) a left join item_product_rate b on a.sname=b.sname`)
132 if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil { 132 if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil {
133 return err 133 return err
134 } 134 }
135 return nil 135 return nil
136 } 136 }
  137 +
  138 +// ProductWeightStatics 产能统计
  139 +func (dao *ProductRecordDao) ProductWeightStatics(companyId, orgId, productRecordType, productPlanId int, workstationId string, beginTime time.Time, endTime time.Time) (float64, error) {
  140 +
  141 + tx := dao.transactionContext.PgTx
  142 + var result = struct {
  143 + Total float64
  144 + }{}
  145 + sql := fmt.Sprintf(`
  146 +select coalesce(sum(cast(product_record_info->>'original' as DECIMAL)),0) total
  147 +from manufacture.product_records
  148 +where company_id = ? and org_id = ? and product_record_type = ?
  149 +and work_station->>'workStationId' = ?
  150 +and product_record_info->>'productPlanId' = '?'
  151 +and created_at >= ? and created_at < ?
  152 +`)
  153 + if _, err := tx.QueryOne(&result, sql, companyId, orgId, productRecordType, workstationId, productPlanId, beginTime, endTime); err != nil {
  154 + return 0, err
  155 + }
  156 + return result.Total, nil
  157 +}
@@ -3,6 +3,6 @@ package domainService @@ -3,6 +3,6 @@ package domainService
3 import "testing" 3 import "testing"
4 4
5 func TestSectionProductive(t *testing.T) { 5 func TestSectionProductive(t *testing.T) {
6 - svr := NewByteBankService()  
7 - svr.SectionProductive() 6 + //svr := NewByteBankService()
  7 + //svr.SectionProductive()
8 } 8 }
@@ -63,6 +63,7 @@ func (svr *UserService) ToUser(from *models.User) *domain.User { @@ -63,6 +63,7 @@ func (svr *UserService) ToUser(from *models.User) *domain.User {
63 IcCardNumber: from.IcCardNumber, 63 IcCardNumber: from.IcCardNumber,
64 Avatar: from.UserInfo.Avatar, 64 Avatar: from.UserInfo.Avatar,
65 Phone: from.UserInfo.Phone, 65 Phone: from.UserInfo.Phone,
  66 + EnableStatus: from.EnableStatus,
66 } 67 }
67 if user.EmployeeType == 0 { 68 if user.EmployeeType == 0 {
68 user.EmployeeType = 1 //默认正式员工 69 user.EmployeeType = 1 //默认正式员工
@@ -6,8 +6,8 @@ import ( @@ -6,8 +6,8 @@ import (
6 pgTransaction "github.com/linmadan/egglib-go/transaction/pg" 6 pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
7 "github.com/linmadan/egglib-go/utils/tool_funs" 7 "github.com/linmadan/egglib-go/utils/tool_funs"
8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
9 - "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"  
10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository" 9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
12 "strconv" 12 "strconv"
13 "time" 13 "time"
@@ -36,10 +36,22 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li @@ -36,10 +36,22 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
36 if err != nil { 36 if err != nil {
37 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 37 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
38 } 38 }
39 -  
40 - var generator = redis.NewProductCodeCache(opt.CompanyId) 39 + var materials domain.ProductMaterials
  40 + if materials, err = ptr.GetProductMaterialByImportItems(opt.CompanyId, list); err != nil {
  41 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  42 + }
  43 + mapMaterials := materials.ToMapByNumber()
41 for i := range list { 44 for i := range list {
42 item := list[i] 45 item := list[i]
  46 + if v, ok := mapMaterials[item.ProductCode]; !ok {
  47 + item.FailReason = "导入的产品编号不存在"
  48 + failRows = append(failRows, item)
  49 + continue
  50 + } else {
  51 + item.Unit = v.ProductMaterialExt.Unit
  52 + item.ProductName = v.MaterialName
  53 + item.ProductCategory = v.MaterialCategory.Category
  54 + }
43 if err := item.Valid(); err != nil { 55 if err := item.Valid(); err != nil {
44 item.FailReason = err.Error() 56 item.FailReason = err.Error()
45 failRows = append(failRows, item) 57 failRows = append(failRows, item)
@@ -69,14 +81,6 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li @@ -69,14 +81,6 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
69 continue 81 continue
70 } 82 }
71 } 83 }
72 - if len(newItem.ProductCode) == 0 {  
73 - code, err := redis.GenCode(generator)  
74 - if err != nil {  
75 - log.Logger.Error(err.Error())  
76 - return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")  
77 - }  
78 - newItem.ProductCode = code  
79 - }  
80 84
81 if _, ok := mapProduct[newItem.ProductCode]; !ok { 85 if _, ok := mapProduct[newItem.ProductCode]; !ok {
82 mapProduct[newItem.ProductCode] = newItem 86 mapProduct[newItem.ProductCode] = newItem
@@ -105,6 +109,28 @@ func (ptr *PGBatchAddProductService) updateProduct(opt *domain.OperateInfo, item @@ -105,6 +109,28 @@ func (ptr *PGBatchAddProductService) updateProduct(opt *domain.OperateInfo, item
105 return nil 109 return nil
106 } 110 }
107 111
  112 +func (ptr *PGBatchAddProductService) GetProductMaterialByProductCodes(companyId int, productCodes []string) ([]*domain.ProductMaterial, error) {
  113 + productMaterialRepository, _ := repository.NewProductMaterialRepository(ptr.transactionContext)
  114 + _, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"companyId": companyId, "materialNumbers": productCodes})
  115 + return productMaterials, err
  116 +}
  117 +
  118 +func (ptr *PGBatchAddProductService) GetProductMaterialByImportItems(companyId int, list []*domain.ImportProductItem) ([]*domain.ProductMaterial, error) {
  119 + productCodes := ptr.GetProductCodesByImportItems(list)
  120 + if len(productCodes) == 0 {
  121 + return []*domain.ProductMaterial{}, nil
  122 + }
  123 + return ptr.GetProductMaterialByProductCodes(companyId, productCodes)
  124 +}
  125 +
  126 +func (ptr *PGBatchAddProductService) GetProductCodesByImportItems(list []*domain.ImportProductItem) []string {
  127 + var result = utils.NewSet()
  128 + for _, v := range list {
  129 + result.Add(v.ProductCode)
  130 + }
  131 + return result.KeysStr()
  132 +}
  133 +
108 func NewPGBatchAddProductService(transactionContext *pgTransaction.TransactionContext) (*PGBatchAddProductService, error) { 134 func NewPGBatchAddProductService(transactionContext *pgTransaction.TransactionContext) (*PGBatchAddProductService, error) {
109 if transactionContext == nil { 135 if transactionContext == nil {
110 return nil, fmt.Errorf("transactionContext参数不能为nil") 136 return nil, fmt.Errorf("transactionContext参数不能为nil")
@@ -94,11 +94,19 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[ @@ -94,11 +94,19 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
94 } 94 }
95 productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext) 95 productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
96 96
97 - var response = make([]interface{}, 0)  
98 - var tmpXData = make([]string, 0) 97 + var (
  98 + response = make([]interface{}, 0)
  99 + tmpXData = make([]string, 0)
  100 + beginTime = xtime.BeginningOfDay() //time.Now().Add(-time.Hour*5)
  101 + endTime = time.Now()
  102 + )
  103 + if !xtime.IsZero(request.Date.Time()) && !request.Date.Time().Equal(beginTime) {
  104 + beginTime = request.Date.Time()
  105 + endTime = request.Date.Time().AddDate(0, 0, 1)
  106 + }
99 for _, v := range workshop.GetProductLines(domain.NotDeleted) { 107 for _, v := range workshop.GetProductLines(domain.NotDeleted) {
100 var result = make([]*record, 0) 108 var result = make([]*record, 0)
101 - if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, time.Now().Add(-time.Hour*5), &result); err != nil { 109 + if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beginTime, endTime, &result); err != nil {
102 log.Logger.Error(err.Error()) 110 log.Logger.Error(err.Error())
103 continue 111 continue
104 } 112 }
@@ -123,10 +131,10 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[ @@ -123,10 +131,10 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
123 } 131 }
124 132
125 type HourProductiveStatisticsRequest struct { 133 type HourProductiveStatisticsRequest struct {
126 - CompanyId int `json:"companyId" valid:"Required"`  
127 - OrgId int `json:"orgId" valid:"Required"`  
128 - WorkshopId int `json:"workshopId" valid:"Required"`  
129 - Date time.Time `json:"date"` 134 + CompanyId int `json:"companyId" valid:"Required"`
  135 + OrgId int `json:"orgId" valid:"Required"`
  136 + WorkshopId int `json:"workshopId" valid:"Required"`
  137 + Date utils.TimeString `json:"date"`
130 } 138 }
131 139
132 func NewXYData(xData []string, values interface{}) interface{} { 140 func NewXYData(xData []string, values interface{}) interface{} {
@@ -141,7 +149,7 @@ func NewXYData(xData []string, values interface{}) interface{} { @@ -141,7 +149,7 @@ func NewXYData(xData []string, values interface{}) interface{} {
141 return values 149 return values
142 } 150 }
143 151
144 -// 时段产能-统计 (传串设备) 152 +// DailyProductiveStatistics 每日产能-统计 (传串设备)
145 func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) { 153 func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) {
146 var request = &HourProductiveStatisticsRequest{} 154 var request = &HourProductiveStatisticsRequest{}
147 if err := utils.LoadQueryObject(queryOptions, request); err != nil { 155 if err := utils.LoadQueryObject(queryOptions, request); err != nil {
@@ -153,9 +161,13 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map @@ -153,9 +161,13 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
153 Ts string `json:"ts"` 161 Ts string `json:"ts"`
154 Total float64 `json:"total"` 162 Total float64 `json:"total"`
155 } 163 }
156 - var date = time.Now()  
157 - if !xtime.IsZero(request.Date) {  
158 - date = request.Date 164 + var (
  165 + beingTime = xtime.BeginningOfDay().AddDate(0, 0, -6)
  166 + endTime = xtime.BeginningOfDay().AddDate(0, 0, 1).Add(-time.Second)
  167 + )
  168 + if !xtime.IsZero(time.Time(request.Date)) {
  169 + beingTime = request.Date.Time().AddDate(0, 0, -6)
  170 + endTime = request.Date.Time().AddDate(0, 0, 1).Add(-time.Second)
159 } 171 }
160 workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId}) 172 workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
161 if err != nil || workshop == nil { 173 if err != nil || workshop == nil {
@@ -168,7 +180,7 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map @@ -168,7 +180,7 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
168 180
169 for _, v := range workshop.GetProductLines(domain.NotDeleted) { 181 for _, v := range workshop.GetProductLines(domain.NotDeleted) {
170 var result = make([]*record, 0) 182 var result = make([]*record, 0)
171 - if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, date.Add(-time.Hour*24*7), date, &result); err != nil { 183 + if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beingTime, endTime, &result); err != nil {
172 log.Logger.Error(err.Error()) 184 log.Logger.Error(err.Error())
173 continue 185 continue
174 } 186 }
@@ -213,8 +225,8 @@ func (ptr *PGCommonStatisticsService) ProportionOfSecondLevelStatistics(queryOpt @@ -213,8 +225,8 @@ func (ptr *PGCommonStatisticsService) ProportionOfSecondLevelStatistics(queryOpt
213 } 225 }
214 productRecordDao, _ := dao.NewProductRecordDao(ptr.transactionContext) 226 productRecordDao, _ := dao.NewProductRecordDao(ptr.transactionContext)
215 var date = time.Now() 227 var date = time.Now()
216 - if !xtime.IsZero(request.Date) {  
217 - date = request.Date 228 + if !xtime.IsZero(time.Time(request.Date)) {
  229 + date = request.Date.Time()
218 } 230 }
219 var input = []struct { 231 var input = []struct {
220 name string 232 name string
@@ -262,8 +274,8 @@ func (ptr *PGCommonStatisticsService) WorkshopProductionEfficiencyStatistics(que @@ -262,8 +274,8 @@ func (ptr *PGCommonStatisticsService) WorkshopProductionEfficiencyStatistics(que
262 } 274 }
263 productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext) 275 productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
264 var date = time.Now() 276 var date = time.Now()
265 - if !xtime.IsZero(request.Date) {  
266 - date = request.Date 277 + if !xtime.IsZero(time.Time(request.Date)) {
  278 + date = time.Time(request.Date)
267 } 279 }
268 var input = []struct { 280 var input = []struct {
269 name string 281 name string
  1 +package domainService
  2 +
  3 +import (
  4 + "fmt"
  5 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  10 + "sort"
  11 + "time"
  12 +)
  13 +
  14 +type PGMaterialService struct {
  15 + transactionContext *pgTransaction.TransactionContext
  16 +}
  17 +
  18 +// 物料
  19 +
  20 +func (ptr *PGMaterialService) AddMaterial(opt *domain.OperateInfo, item *domain.ProductMaterial) (*domain.ProductMaterial, error) {
  21 + var (
  22 + user *domain.User
  23 + org *domain.Org
  24 + err error
  25 + newProductMaterial *domain.ProductMaterial
  26 + productMaterialRepository, _ = repository.NewProductMaterialRepository(ptr.transactionContext)
  27 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  28 + )
  29 + if user, err = NewUserService().User(opt.UserId); err != nil {
  30 + return nil, err
  31 + }
  32 + if org, err = NewUserService().Organization(opt.OrgId); err != nil {
  33 + return nil, err
  34 + }
  35 + _, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId})
  36 + if err != nil {
  37 + return nil, err
  38 + }
  39 +
  40 + if newProductMaterial, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialNumber": item.MaterialNumber}); err == nil || newProductMaterial != nil {
  41 + return nil, fmt.Errorf("物料编码已存在")
  42 + }
  43 + newProductMaterial = &domain.ProductMaterial{
  44 + CompanyId: item.CompanyId,
  45 + OrgId: item.OrgId,
  46 + ProductMaterialGroupId: item.ProductMaterialGroupId,
  47 + MaterialName: item.MaterialName,
  48 + MaterialNumber: item.MaterialNumber,
  49 + MaterialAttribute: item.MaterialAttribute,
  50 + MaterialCategory: item.MaterialCategory,
  51 + ProductMaterialExt: item.ProductMaterialExt,
  52 + CreatedAt: time.Now(),
  53 + UpdatedAt: time.Now(),
  54 + Ext: domain.NewExt(org.OrgName).WithOperator(user),
  55 + }
  56 + return productMaterialRepository.Save(newProductMaterial)
  57 +}
  58 +
  59 +// 物料分组
  60 +
  61 +func (ptr *PGMaterialService) AddMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
  62 + var (
  63 + user *domain.User
  64 + org *domain.Org
  65 + err error
  66 + parent *domain.ProductMaterialGroup
  67 + newProductMaterialGroup *domain.ProductMaterialGroup
  68 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  69 +
  70 + productMaterialGroupDao *dao.ProductMaterialGroupDao
  71 + latestNumber string
  72 + total int
  73 + )
  74 + if user, err = NewUserService().User(opt.UserId); err != nil {
  75 + return nil, err
  76 + }
  77 + if org, err = NewUserService().Organization(opt.OrgId); err != nil {
  78 + return nil, err
  79 + }
  80 + if item.Pid != 0 {
  81 + if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
  82 + return nil, fmt.Errorf("上级物料分组不存在")
  83 + }
  84 + }
  85 + if newProductMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || newProductMaterialGroup != nil {
  86 + return nil, fmt.Errorf("物料分组编码已存在")
  87 + }
  88 + productMaterialGroupDao, _ = dao.NewProductMaterialGroupDao(ptr.transactionContext)
  89 + latestNumber, total, err = productMaterialGroupDao.CurrentGroupLatestNumber(opt.CompanyId, item.Pid)
  90 + if err != nil {
  91 + return nil, err
  92 + }
  93 +
  94 + newProductMaterialGroup = &domain.ProductMaterialGroup{
  95 + CompanyId: opt.CompanyId,
  96 + OrgId: opt.OrgId,
  97 + Pid: item.Pid,
  98 + //Path: item.GetPath(parent),
  99 + MaterialGroupName: item.MaterialGroupName,
  100 + MaterialGroupNumber: item.MaterialGroupNumber,
  101 + CreatedAt: time.Now(),
  102 + UpdatedAt: time.Now(),
  103 + Ext: domain.NewExt(org.OrgName).WithOperator(user),
  104 + }
  105 + newProductMaterialGroup.MaterialGroupNumber = newProductMaterialGroup.GroupNumberComposeUp(parent, latestNumber, total)
  106 + newProductMaterialGroup, err = productMaterialGroupRepository.Save(newProductMaterialGroup)
  107 + return newProductMaterialGroup, err
  108 +}
  109 +
  110 +func (ptr *PGMaterialService) UpdateMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
  111 + var (
  112 + user *domain.User
  113 + org *domain.Org
  114 + err error
  115 + //parent *domain.ProductMaterialGroup
  116 + productMaterialGroup *domain.ProductMaterialGroup
  117 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  118 + )
  119 + if user, err = NewUserService().User(opt.UserId); err != nil {
  120 + return nil, err
  121 + }
  122 + if org, err = NewUserService().Organization(opt.OrgId); err != nil {
  123 + return nil, err
  124 + }
  125 + //if item.ProductMaterialGroupId == item.Pid {
  126 + // return nil, fmt.Errorf("当前物料分组不能做为自己上级")
  127 + //}
  128 + if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId}); err != nil || productMaterialGroup == nil {
  129 + return nil, fmt.Errorf("物料分组不存在")
  130 + }
  131 +
  132 + //if item.Pid != productMaterialGroup.ProductMaterialGroupId && item.Pid != 0 {
  133 + // if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
  134 + // return nil, fmt.Errorf("上级物料分组不存在")
  135 + // }
  136 + //}
  137 + //if productMaterialGroup.MaterialGroupNumber != item.MaterialGroupNumber {
  138 + // if group, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || group != nil {
  139 + // return nil, fmt.Errorf("物料分组编码已存在")
  140 + // }
  141 + //}
  142 + //productMaterialGroup.MaterialGroupNumber = item.MaterialGroupNumber
  143 +
  144 + productMaterialGroup.MaterialGroupName = item.MaterialGroupName
  145 + productMaterialGroup.UpdatedAt = item.UpdatedAt
  146 + productMaterialGroup.Ext = domain.NewExt(org.OrgName).WithOperator(user)
  147 +
  148 + productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup)
  149 + return productMaterialGroup, err
  150 +}
  151 +
  152 +func (ptr *PGMaterialService) AllMaterialGroupChild(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
  153 + var (
  154 + err error
  155 + listId []int
  156 + productMaterialGroup *domain.ProductMaterialGroup
  157 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  158 + groups domain.ProductMaterialGroups
  159 + )
  160 + if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
  161 + return nil, listId, fmt.Errorf("物料分组不存在")
  162 + }
  163 + _, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
  164 + if len(groups) == 0 || err != nil {
  165 + return nil, listId, err
  166 + }
  167 + // 先排序 sort pid,id asc
  168 + sort.Stable(groups)
  169 + var treeNodes = make([]utils.TreeNode, len(groups))
  170 + for i := 0; i < len(groups); i++ {
  171 + treeNodes[i] = groups[i]
  172 + }
  173 + tree := utils.NewTree(treeNodes)
  174 + child := tree.AllChildNode(productMaterialGroup)
  175 + var result = make([]*domain.ProductMaterialGroup, 0)
  176 + for i := range child {
  177 + if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
  178 + result = append(result, v)
  179 + listId = append(listId, v.ProductMaterialGroupId)
  180 + }
  181 + }
  182 + return result, listId, err
  183 +}
  184 +
  185 +func (ptr *PGMaterialService) AllMaterialGroupParent(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
  186 + var (
  187 + err error
  188 + listId []int
  189 + productMaterialGroup *domain.ProductMaterialGroup
  190 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  191 + groups domain.ProductMaterialGroups
  192 + )
  193 + if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
  194 + return nil, listId, fmt.Errorf("物料分组不存在")
  195 + }
  196 + _, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
  197 + if len(groups) == 0 || err != nil {
  198 + return nil, listId, err
  199 + }
  200 + // 先排序 sort pid,id asc
  201 + sort.Stable(groups)
  202 + var treeNodes = make([]utils.TreeNode, len(groups))
  203 + for i := 0; i < len(groups); i++ {
  204 + treeNodes[i] = groups[i]
  205 + }
  206 + tree := utils.NewTree(treeNodes)
  207 + child := tree.TreeNodePaths(productMaterialGroup)
  208 + var result = make([]*domain.ProductMaterialGroup, 0)
  209 + for i := range child {
  210 + if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
  211 + result = append(result, v)
  212 + listId = append(listId, v.ProductMaterialGroupId)
  213 + }
  214 + }
  215 + return result, listId, err
  216 +}
  217 +
  218 +func (ptr *PGMaterialService) AllMaterialGroupParentByBacktracking(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
  219 + var (
  220 + err error
  221 + listId []int
  222 + productMaterialGroup *domain.ProductMaterialGroup
  223 + productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
  224 + pid = productMaterialGroupId
  225 + mapExists = make(map[int]int)
  226 + )
  227 + var result = make([]*domain.ProductMaterialGroup, 0)
  228 + for {
  229 + if pid == 0 {
  230 + break
  231 + }
  232 + if _, exists := mapExists[pid]; exists {
  233 + break
  234 + }
  235 + mapExists[pid] = pid
  236 + productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": pid, "allWithDeleted": "1"})
  237 + if err != nil || productMaterialGroup == nil {
  238 + return nil, listId, fmt.Errorf("物料分组不存在")
  239 + }
  240 + pid = productMaterialGroup.Pid
  241 + result = append([]*domain.ProductMaterialGroup{productMaterialGroup}, result...)
  242 + }
  243 + return result, listId, err
  244 +}
  245 +
  246 +func NewPGMaterialService(transactionContext *pgTransaction.TransactionContext) (*PGMaterialService, error) {
  247 + if transactionContext == nil {
  248 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  249 + } else {
  250 + return &PGMaterialService{
  251 + transactionContext: transactionContext,
  252 + }, nil
  253 + }
  254 +}
@@ -180,7 +180,31 @@ func (ptr *PGProductRecordService) Approve(productRecordId int, approveUserId in @@ -180,7 +180,31 @@ func (ptr *PGProductRecordService) Approve(productRecordId int, approveUserId in
180 return struct{}{}, nil 180 return struct{}{}, nil
181 } 181 }
182 182
183 -func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, approveUserId int, weight float64, status int) (interface{}, error) { 183 +// Approve 审核生产记录 (二级品审核)
  184 +func (ptr *PGProductRecordService) Cancel(productRecordId int) (interface{}, error) {
  185 + productRecordRepository, err := repository.NewProductRecordRepository(ptr.transactionContext)
  186 +
  187 + var productRecord *domain.ProductRecord
  188 + productRecord, err = productRecordRepository.FindOne(map[string]interface{}{"productRecordId": productRecordId})
  189 + if err != nil {
  190 + return nil, err
  191 + }
  192 +
  193 + if err = productRecord.Cancel(); err != nil {
  194 + return nil, err
  195 + }
  196 + if _, err = productRecordRepository.Save(productRecord); err != nil {
  197 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  198 + }
  199 + // 发送Job
  200 + productRecord.ProductRecordInfo.Weigh = -productRecord.ProductRecordInfo.Weigh
  201 + if err = SendProductRecordStaticsJob(productRecord); err != nil {
  202 + return nil, err
  203 + }
  204 + return struct{}{}, nil
  205 +}
  206 +
  207 +func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, approveUserId int, weightAfter float64, status int) (interface{}, error) {
184 var productRecordRepository, _ = repository.NewProductRecordRepository(ptr.transactionContext) 208 var productRecordRepository, _ = repository.NewProductRecordRepository(ptr.transactionContext)
185 var record *domain.ProductRecord 209 var record *domain.ProductRecord
186 var err error 210 var err error
@@ -196,26 +220,19 @@ func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, ap @@ -196,26 +220,19 @@ func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, ap
196 220
197 for i := range list { 221 for i := range list {
198 record = list[i] 222 record = list[i]
199 - t := record.ProductRecordInfo.WeighBefore  
200 - if weight > 0 {  
201 - t = weight 223 + weighBefore := record.ProductRecordInfo.WeighBefore
  224 + if weightAfter > 0 {
  225 + weighBefore = weightAfter
202 } 226 }
203 - if t <= 0 && status == domain.AttendanceAutoApproved { 227 + if weighBefore <= 0 || record.ProductRecordInfo.ApproveStatus != domain.ProductRecordNotApprove {
204 continue 228 continue
205 } 229 }
206 - if err = record.Approve(user, t, time.Now(), status); err != nil { 230 + if err = record.Approve(user, weighBefore, time.Now(), status); err != nil {
207 return nil, err 231 return nil, err
208 } 232 }
209 if _, err := productRecordRepository.Save(record); err != nil { 233 if _, err := productRecordRepository.Save(record); err != nil {
210 return nil, err 234 return nil, err
211 } 235 }
212 - }  
213 -  
214 - for i := range list {  
215 - record = list[i]  
216 - if record.ProductRecordInfo.WeighBefore <= 0 && status == domain.AttendanceAutoApproved {  
217 - continue  
218 - }  
219 if e := SendProductRecordStaticsJob(record); e != nil { 236 if e := SendProductRecordStaticsJob(record); e != nil {
220 log.Logger.Error("【发送产量统计任务失败】" + e.Error()) 237 log.Logger.Error("【发送产量统计任务失败】" + e.Error())
221 } 238 }
@@ -11,7 +11,7 @@ import ( @@ -11,7 +11,7 @@ import (
11 ) 11 )
12 12
13 const ( 13 const (
14 - ProductSection1 = "打料" 14 + ProductSection1 = "制模" //打料更新为制模
15 ProductSection2 = "成型" 15 ProductSection2 = "成型"
16 ProductSection3 = "穿串" 16 ProductSection3 = "穿串"
17 ProductSection4 = "包装" 17 ProductSection4 = "包装"
@@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
298 workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext) 298 workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext)
299 workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt) 299 workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt)
300 if err == domain.ErrorNotFound { 300 if err == domain.ErrorNotFound {
301 - workshopProductRecord = newWorkshopProductRecord(productRecord, productPlan) 301 + workshopProductRecord = NewWorkshopProductRecord(productRecord, productPlan)
302 } else { 302 } else {
303 if err != nil { 303 if err != nil {
304 log.Logger.Error(err.Error()) 304 log.Logger.Error(err.Error())
@@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
310 workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original)) 310 workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original))
311 workshopProductRecord.UpdateProductWeigh(productRecord) 311 workshopProductRecord.UpdateProductWeigh(productRecord)
312 // 打料 跟 成型工段的初始产能是批次的产能 312 // 打料 跟 成型工段的初始产能是批次的产能
313 - if productRecord.WorkStation.SectionName == ProductSection1 && productRecord.WorkStation.SectionName == ProductSection2 {  
314 - workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)  
315 - } 313 + //if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
  314 + // workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
  315 + //}
316 316
317 if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil { 317 if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
318 // TODO:异常处理 318 // TODO:异常处理
@@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
321 return nil, nil 321 return nil, nil
322 } 322 }
323 323
324 -// newEmployeeProductRecord 员工生产记录  
325 -func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord { 324 +// NewWorkshopProductRecord 车间生产记录
  325 +func NewWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
326 record := &domain.WorkshopProductRecord{ 326 record := &domain.WorkshopProductRecord{
327 CompanyId: productRecord.CompanyId, 327 CompanyId: productRecord.CompanyId,
328 OrgId: productRecord.OrgId, 328 OrgId: productRecord.OrgId,
@@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan * @@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *
347 } 347 }
348 // 打料、成型有初始值 348 // 打料、成型有初始值
349 if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 { 349 if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
350 - record.ProductWeigh = productPlan.PlanDevoted.Weight 350 + record.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
351 } 351 }
352 return record 352 return record
353 } 353 }
@@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d @@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d
78 // 封箱机、串串机需要定位到批次 78 // 封箱机、串串机需要定位到批次
79 if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi || 79 if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi ||
80 datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local) 80 datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local)
81 - if plan, err = ptr.findDeviceProductPlan(companyId, orgId, workStation.WorkStationId, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil { 81 + if plan, err = ptr.findProductPlanAndActive(companyId, orgId, workStation, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
82 log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType}) 82 log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType})
83 } else { 83 } else {
84 planId = plan.PlanDispatchRecordExt.ProductPlanId 84 planId = plan.PlanDispatchRecordExt.ProductPlanId
@@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId, @@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId,
326 } 326 }
327 327
328 // 查找设备的生产计划,如果计划没有上线的话将他上线 328 // 查找设备的生产计划,如果计划没有上线的话将他上线
329 -func (ptr *PGWorkshopDataConsumeService) findDeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) { 329 +func (ptr *PGWorkshopDataConsumeService) findProductPlanAndActive(companyId, orgId int, workStation *domain.WorkStation, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
330 planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext) 330 planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext)
331 planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext) 331 planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext)
332 - var setPlanOnline = false  
333 - record, err := planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOnline) 332 + record, err := planDispatchRecordDao.ProductPlanDispatchRecord(companyId, orgId, workStation.WorkStationId, date, productCode, 0)
  333 + // 未找到当前工段的调度计划,从计划管理查询是否有匹配记录,如果有在调度计划中上线
  334 + var productPlan *domain.ProductPlan
334 if err == domain.ErrorNotFound { 335 if err == domain.ErrorNotFound {
335 - if record, err = planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOffline); err != nil {  
336 - return nil, err  
337 - } else {  
338 - setPlanOnline = true 336 + if productPlan, err = planDispatchRecordDao.ProductPlan(companyId, orgId, workStation.WorkshopId, date, productCode); err == nil && productPlan != nil {
  337 + var productPlanDispatch = domain.NewProductPlanDispatchRecord(productPlan, workStation)
  338 + if productPlanDispatch, err = planDispatchRecordRepository.Save(productPlanDispatch); err != nil {
  339 + return nil, err
  340 + }
  341 + return productPlanDispatch, nil
339 } 342 }
  343 + return nil, err
340 } 344 }
341 - if setPlanOnline {  
342 - record.ChangeStatus(domain.PlanOnline) 345 + if err != nil {
  346 + return nil, err
  347 + }
  348 + if record != nil && record.PlanDispatchStatus == domain.PlanOffline {
  349 + if err = record.ChangeStatus(domain.PlanOnline); err != nil {
  350 + return nil, err
  351 + }
343 if record, err = planDispatchRecordRepository.Save(record); err != nil { 352 if record, err = planDispatchRecordRepository.Save(record); err != nil {
344 return nil, err 353 return nil, err
345 } 354 }
@@ -48,6 +48,8 @@ func init() { @@ -48,6 +48,8 @@ func init() {
48 (*models.DeviceDailyRunningRecord)(nil), 48 (*models.DeviceDailyRunningRecord)(nil),
49 (*models.DeviceRunningRecord)(nil), 49 (*models.DeviceRunningRecord)(nil),
50 (*models.WorkshopPlanCompletionRecord)(nil), 50 (*models.WorkshopPlanCompletionRecord)(nil),
  51 + (*models.ProductMaterialGroup)(nil),
  52 + (*models.ProductMaterial)(nil),
51 } { 53 } {
52 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{ 54 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
53 Temp: false, 55 Temp: false,
@@ -9,3 +9,13 @@ type MaterialGroupK3cloud struct { @@ -9,3 +9,13 @@ type MaterialGroupK3cloud struct {
9 ParentId int `comment:"父级id" pg:"parent_id"` 9 ParentId int `comment:"父级id" pg:"parent_id"`
10 DataVersion int64 `comment:"数据版本" pg:"data_version"` 10 DataVersion int64 `comment:"数据版本" pg:"data_version"`
11 } 11 }
  12 +
  13 +type MaterialGroupK3clouds []*MaterialGroupK3cloud
  14 +
  15 +func (materialGroupK3clouds MaterialGroupK3clouds) ToMapId() map[int]*MaterialGroupK3cloud {
  16 + var result = make(map[int]*MaterialGroupK3cloud)
  17 + for i := range materialGroupK3clouds {
  18 + result[materialGroupK3clouds[i].Id] = materialGroupK3clouds[i]
  19 + }
  20 + return result
  21 +}
@@ -25,6 +25,7 @@ type MaterialK3cloud struct { @@ -25,6 +25,7 @@ type MaterialK3cloud struct {
25 UseOrgName string `comment:"使用组织" pg:"use_org_name"` 25 UseOrgName string `comment:"使用组织" pg:"use_org_name"`
26 JoinProductId int64 `comment:"关联的product表id" pg:"join_product_id"` 26 JoinProductId int64 `comment:"关联的product表id" pg:"join_product_id"`
27 DataVersion int64 `comment:"数据版本" pg:"data_version"` 27 DataVersion int64 `comment:"数据版本" pg:"data_version"`
  28 + FCategoryID string `pg:"-"`
28 } 29 }
29 30
30 //批量处理sql脚本样例 31 //批量处理sql脚本样例
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +type ProductMaterial struct {
  9 + tableName string `comment:"生产物料" pg:"manufacture.product_material"`
  10 + // 物料ID
  11 + ProductMaterialId int `comment:"物料ID" pg:"pk:product_material_id"`
  12 + // 企业id
  13 + CompanyId int `comment:"企业id"`
  14 + // 组织ID
  15 + OrgId int `comment:"组织ID"`
  16 + // 物料分组ID
  17 + ProductMaterialGroupId int `comment:"物料分组ID"`
  18 + // 物料编码
  19 + MaterialNumber string `comment:"物料编码"`
  20 + // 物料名称
  21 + MaterialName string `comment:"物料名称"`
  22 + // 物料属性
  23 + MaterialAttribute *domain.MaterialAttribute `comment:"物料属性"`
  24 + // 物料类别
  25 + MaterialCategory *domain.MaterialCategory `comment:"物料类别"`
  26 + // 物料扩展
  27 + ProductMaterialExt *domain.MaterialExt `comment:"物料扩展"`
  28 + // 创建时间
  29 + CreatedAt time.Time `comment:"创建时间"`
  30 + // 更新时间
  31 + UpdatedAt time.Time `comment:"更新时间"`
  32 + // 删除时间
  33 + DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
  34 + // 扩展
  35 + Ext *domain.Ext `comment:"扩展"`
  36 +}
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +type ProductMaterialGroup struct {
  9 + tableName string `comment:"物料分组" pg:"manufacture.product_material_group"`
  10 + // 物料分组ID
  11 + ProductMaterialGroupId int `comment:"物料分组ID" pg:"pk:product_material_group_id"`
  12 + // 企业id
  13 + CompanyId int `comment:"企业id"`
  14 + // 组织ID
  15 + OrgId int `comment:"组织ID"`
  16 + // 父级ID
  17 + Pid int `comment:"父级ID"`
  18 + // 路径
  19 + // Path string `comment:"路径"`
  20 + // 物料分组名称
  21 + MaterialGroupName string `comment:"物料分组名称"`
  22 + // 物料分组编码
  23 + MaterialGroupNumber string `comment:"物料分组编码"`
  24 + // 创建时间
  25 + CreatedAt time.Time `comment:"创建时间"`
  26 + // 更新时间
  27 + UpdatedAt time.Time `comment:"更新时间"`
  28 + // 删除时间
  29 + DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
  30 + // 扩展
  31 + Ext *domain.Ext `comment:"扩展"`
  32 +}
  1 +package transform
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
  6 +)
  7 +
  8 +func TransformToProductMaterialDomainModelFromPgModels(productMaterialModel *models.ProductMaterial) (*domain.ProductMaterial, error) {
  9 + return &domain.ProductMaterial{
  10 + ProductMaterialId: productMaterialModel.ProductMaterialId,
  11 + CompanyId: productMaterialModel.CompanyId,
  12 + OrgId: productMaterialModel.OrgId,
  13 + ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
  14 + MaterialNumber: productMaterialModel.MaterialNumber,
  15 + MaterialName: productMaterialModel.MaterialName,
  16 + MaterialAttribute: productMaterialModel.MaterialAttribute,
  17 + MaterialCategory: productMaterialModel.MaterialCategory,
  18 + ProductMaterialExt: productMaterialModel.ProductMaterialExt,
  19 + CreatedAt: productMaterialModel.CreatedAt,
  20 + UpdatedAt: productMaterialModel.UpdatedAt,
  21 + DeletedAt: productMaterialModel.DeletedAt,
  22 + Ext: productMaterialModel.Ext,
  23 + }, nil
  24 +}
  1 +package transform
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
  6 +)
  7 +
  8 +func TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel *models.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
  9 + return &domain.ProductMaterialGroup{
  10 + ProductMaterialGroupId: productMaterialGroupModel.ProductMaterialGroupId,
  11 + CompanyId: productMaterialGroupModel.CompanyId,
  12 + OrgId: productMaterialGroupModel.OrgId,
  13 + Pid: productMaterialGroupModel.Pid,
  14 + //Path: productMaterialGroupModel.Path,
  15 + MaterialGroupName: productMaterialGroupModel.MaterialGroupName,
  16 + MaterialGroupNumber: productMaterialGroupModel.MaterialGroupNumber,
  17 + CreatedAt: productMaterialGroupModel.CreatedAt,
  18 + UpdatedAt: productMaterialGroupModel.UpdatedAt,
  19 + DeletedAt: productMaterialGroupModel.DeletedAt,
  20 + Ext: productMaterialGroupModel.Ext,
  21 + }, nil
  22 +}
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 +
  7 + "github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
  8 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  9 + "github.com/linmadan/egglib-go/utils/snowflake"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
  13 +)
  14 +
  15 +type ProductMaterialGroupRepository struct {
  16 + transactionContext *pgTransaction.TransactionContext
  17 +}
  18 +
  19 +func (repository *ProductMaterialGroupRepository) nextIdentify() (int64, error) {
  20 + IdWorker, err := snowflake.NewIdWorker(1)
  21 + if err != nil {
  22 + return 0, err
  23 + }
  24 + id, err := IdWorker.NextId()
  25 + return id, err
  26 +}
  27 +func (repository *ProductMaterialGroupRepository) Save(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
  28 + sqlBuildFields := []string{
  29 + "product_material_group_id",
  30 + "company_id",
  31 + "org_id",
  32 + "pid",
  33 + //"path",
  34 + "material_group_name",
  35 + "material_group_number",
  36 + "created_at",
  37 + "updated_at",
  38 + "deleted_at",
  39 + "ext",
  40 + }
  41 + insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
  42 + insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
  43 + returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
  44 + updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at")
  45 + updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
  46 + tx := repository.transactionContext.PgTx
  47 + if productMaterialGroup.Identify() == nil {
  48 + if _, err := tx.QueryOne(
  49 + pg.Scan(
  50 + &productMaterialGroup.ProductMaterialGroupId,
  51 + &productMaterialGroup.CompanyId,
  52 + &productMaterialGroup.OrgId,
  53 + &productMaterialGroup.Pid,
  54 + //&productMaterialGroup.Path,
  55 + &productMaterialGroup.MaterialGroupName,
  56 + &productMaterialGroup.MaterialGroupNumber,
  57 + &productMaterialGroup.CreatedAt,
  58 + &productMaterialGroup.UpdatedAt,
  59 + &productMaterialGroup.DeletedAt,
  60 + &productMaterialGroup.Ext,
  61 + ),
  62 + fmt.Sprintf("INSERT INTO manufacture.product_material_group (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
  63 + productMaterialGroup.CompanyId,
  64 + productMaterialGroup.OrgId,
  65 + productMaterialGroup.Pid,
  66 + //productMaterialGroup.Path,
  67 + productMaterialGroup.MaterialGroupName,
  68 + productMaterialGroup.MaterialGroupNumber,
  69 + productMaterialGroup.CreatedAt,
  70 + productMaterialGroup.UpdatedAt,
  71 + productMaterialGroup.Ext,
  72 + ); err != nil {
  73 + return productMaterialGroup, err
  74 + }
  75 + } else {
  76 + if _, err := tx.QueryOne(
  77 + pg.Scan(
  78 + &productMaterialGroup.ProductMaterialGroupId,
  79 + &productMaterialGroup.CompanyId,
  80 + &productMaterialGroup.OrgId,
  81 + &productMaterialGroup.Pid,
  82 + //&productMaterialGroup.Path,
  83 + &productMaterialGroup.MaterialGroupName,
  84 + &productMaterialGroup.MaterialGroupNumber,
  85 + &productMaterialGroup.CreatedAt,
  86 + &productMaterialGroup.UpdatedAt,
  87 + &productMaterialGroup.DeletedAt,
  88 + &productMaterialGroup.Ext,
  89 + ),
  90 + fmt.Sprintf("UPDATE manufacture.product_material_group SET %s WHERE product_material_group_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
  91 + productMaterialGroup.CompanyId,
  92 + productMaterialGroup.OrgId,
  93 + productMaterialGroup.Pid,
  94 + //productMaterialGroup.Path,
  95 + productMaterialGroup.MaterialGroupName,
  96 + productMaterialGroup.MaterialGroupNumber,
  97 + productMaterialGroup.CreatedAt,
  98 + productMaterialGroup.UpdatedAt,
  99 + productMaterialGroup.Ext,
  100 + productMaterialGroup.Identify(),
  101 + ); err != nil {
  102 + return productMaterialGroup, err
  103 + }
  104 + }
  105 + return productMaterialGroup, nil
  106 +}
  107 +func (repository *ProductMaterialGroupRepository) Remove(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
  108 + tx := repository.transactionContext.PgTx
  109 + productMaterialGroupModel := new(models.ProductMaterialGroup)
  110 + productMaterialGroupModel.ProductMaterialGroupId = productMaterialGroup.Identify().(int)
  111 + if _, err := tx.Model(productMaterialGroupModel).WherePK().Delete(); err != nil {
  112 + return productMaterialGroup, err
  113 + }
  114 + return productMaterialGroup, nil
  115 +}
  116 +func (repository *ProductMaterialGroupRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductMaterialGroup, error) {
  117 + tx := repository.transactionContext.PgTx
  118 + productMaterialGroupModel := new(models.ProductMaterialGroup)
  119 + query := sqlbuilder.BuildQuery(tx.Model(productMaterialGroupModel), queryOptions)
  120 + query.SetWhereByQueryOption("product_material_group_id = ?", "productMaterialGroupId")
  121 + query.SetWhereByQueryOption("company_id = ?", "companyId")
  122 + query.SetWhereByQueryOption("material_group_number = ?", "materialGroupNumber")
  123 + if _, ok := queryOptions["allWithDeleted"]; ok {
  124 + query.AllWithDeleted()
  125 + }
  126 + if err := query.First(); err != nil {
  127 + if err.Error() == "pg: no rows in result set" {
  128 + return nil, domain.ErrorNotFound
  129 + } else {
  130 + return nil, err
  131 + }
  132 + }
  133 + if productMaterialGroupModel.ProductMaterialGroupId == 0 {
  134 + return nil, nil
  135 + } else {
  136 + return transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel)
  137 + }
  138 +}
  139 +func (repository *ProductMaterialGroupRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductMaterialGroup, error) {
  140 + tx := repository.transactionContext.PgTx
  141 + var productMaterialGroupModels []*models.ProductMaterialGroup
  142 + productMaterialGroups := make([]*domain.ProductMaterialGroup, 0)
  143 + query := sqlbuilder.BuildQuery(tx.Model(&productMaterialGroupModels), queryOptions)
  144 + query.SetOffsetAndLimit(domain.MaxQueryRow)
  145 + query.SetWhereByQueryOption("company_id = ?", "companyId")
  146 + if v, ok := queryOptions["orderByProductMaterialGroupId"]; ok {
  147 + query.SetOrderDirect("product_material_group_id", v.(string))
  148 + } else {
  149 + query.SetOrderDirect("product_material_group_id", "DESC")
  150 + }
  151 + if count, err := query.SelectAndCount(); err != nil {
  152 + return 0, productMaterialGroups, err
  153 + } else {
  154 + for _, productMaterialGroupModel := range productMaterialGroupModels {
  155 + if productMaterialGroup, err := transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel); err != nil {
  156 + return 0, productMaterialGroups, err
  157 + } else {
  158 + productMaterialGroups = append(productMaterialGroups, productMaterialGroup)
  159 + }
  160 + }
  161 + return int64(count), productMaterialGroups, nil
  162 + }
  163 +}
  164 +func NewProductMaterialGroupRepository(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupRepository, error) {
  165 + if transactionContext == nil {
  166 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  167 + } else {
  168 + return &ProductMaterialGroupRepository{
  169 + transactionContext: transactionContext,
  170 + }, nil
  171 + }
  172 +}