作者 liujunxiong

合并分支 'test' 到 'feature_material'

Test



查看合并请求 !9
正在显示 79 个修改的文件 包含 1555 行增加270 行删除
POSTGRESQL_DB_NAME = allied_creation_dev
POSTGRESQL_HOST = 114.55.200.59
POSTGRESQL_PORT = 31543
POSTGRESQL_USER = postgres
POSTGRESQL_PASSWORD = eagle1010
DISABLE_SQL_GENERATE_COMMENT = false
SERVICE_ENV = test
HTTP_PORT = 8081
ENABLE_KAFKA_LOG11 = true
HTTPS_PORT = 8143
ALLIED_CREATION_USER_HOST = http://allied-creation-user-dev.fjmaimaimai.com
... ...
POSTGRESQL_DB_NAME = allied_creation_test
POSTGRESQL_HOST = 114.55.200.59
POSTGRESQL_PORT = 31543
POSTGRESQL_USER = postgres
POSTGRESQL_PASSWORD = eagle1010
DISABLE_SQL_GENERATE_COMMENT = false
SERVICE_ENV = test
HTTP_PORT = 8081
ENABLE_KAFKA_LOG11 = true
HTTPS_PORT = 8143
ALLIED_CREATION_USER_HOST = http://allied-creation-user-test.fjmaimaimai.com
MANUFACTURE_DEFAULT_COMPANYID = 23
MANUFACTURE_DEFAULT_ORGID = 487
MANUFACTURE_DEFAULT_WORKSHOPID = 28
... ...
select count(*) from manufacture.device_running_record where device_running_record_id <=2000000
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
--1.备份设备运行数据-按数量
-- 备份数据 2000000
select * into table manufacture.device_running_record_0_2000
from manufacture.device_running_record
where device_running_record_id <=2000000
-- 删除数据
delete from manufacture.device_running_record where device_running_record_id <=2000000;
-- 重建索引
reindex table manufacture.device_running_record;
--2.备份设备采集数据-按时间
-- 备份数据 2000000
select * into table manufacture.device_collections_history
from manufacture.device_collections
where created_at <'2022-6-01 16:00:00'
-- 删除数据
delete from manufacture.device_collections where created_at <'2022-6-01 16:00:00';
-- 重建索引
reindex table manufacture.device_collections;
--3.查看备份情况
select count(*) from manufacture.device_running_record_0_2000
select count(*) from manufacture.device_collections_history
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
\ No newline at end of file
... ...
... ... @@ -5,3 +5,18 @@ ALTER TABLE manufacture.product_calendar ADD COLUMN break_time_periods jsonb;
-- 表product_attendance_record 增加字段 product_date
alter table manufacture.product_attendance_record add COLUMN product_date timestamptz;
update manufacture.product_attendance_record set product_date = sign_in where product_date is null ;
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (260, 174, '监控中心', 'BUSINESS_ALLIED-MANUFACTURING_MONITORING-CENTER', '', 'catalog', '', 5, '', '7', '38,174', 1, 0, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (261, 260, '生产设备监控', 'BUSINESS_ALLIED-MANUFACTURING_MONITORING-CENTER_DEVICE-MONITOR', '', 'menu', '', 1, '', '7', '38,174,233,244', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (262, 260, '生产管理看板', 'BUSINESS_ALLIED-MANUFACTURING_MONITORING-CENTER_PRODUCTION-MONITOR', '', 'menu', '', 2, '', '7', '38,174,260', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (263, 224, '新增工时', 'BUSINESS_ALLIED-MANUFACTURING_PRODUCTION_MAN-HOUR_ADD', '', 'button', '', 1, '', '7', '38,174,223,224', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (264, 174, '大屏看板', 'BUSINESS_ALLIED-MANUFACTURING_LARGE-SCREEN-SIGNAGE', '', 'catalog', '', 6, '', '7', '38,174', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (265, 264, '生产管理看板', 'BUSINESS_ALLIED-MANUFACTURING_LARGE-SCREEN-SIGNAGE_PRODUCTION', '', 'menu', 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220517/object/1652752760_w66QpzZTfxsmhbM5mmBrHjpytcydMNs2.png', 1, '', '7', '38,174,264', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (266, 264, '设备监控看板', 'BUSINESS_ALLIED-MANUFACTURING_LARGE-SCREEN-SIGNAGE_DEVICE', '', 'menu', 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220517/object/1652753144_XsBEXcRxJscRHCzQmxeseTAEQXTH7A7Z.png', 2, '', '7', '38,174,264', 1, 2, NULL);
\ No newline at end of file
... ...
... ... @@ -5,3 +5,24 @@ create UNIQUE INDEX idx_unq_product_material_group_company_id_org_id_material_gr
-- 表product_material 增加唯一索引 idx_unq_product_material_company_id_material_number
create UNIQUE INDEX idx_unq_product_material_company_id_material_number on manufacture.product_material using btree(company_id,material_number,deleted_at);
-- 菜单脚本
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (269, 175, '物料信息', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL', '', 'menu', 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211608_CH2pTwT56j6TXfRdYhGxBfKRNFfpzWKE.png', 3, '', '7', '38,174,175', 1, 0, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (270, 269, '删除', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_DEL', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (271, 269, '新增', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_ADD', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (272, 269, '编辑', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_EDIT', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
INSERT INTO "users"."menu"("menu_id", "parent_id", "menu_name", "code", "access_code", "menu_type", "icon", "sort", "remark", "category", "parent_path", "is_publish", "enable_status", "link") VALUES (273, 269, '查看', 'BUSINESS_ALLIED-MANUFACTURING_BASIC_MATERIAL_VIEW', '', 'button', '', 1, '', '7', '38,174,175,269', 1, 2, NULL);
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '产品管理', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_PRODUCT', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211429_wMrRfxYMyhBySwWkysZaXBbfDapSppBs.png', "sort" = 4, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 186;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '设备档案', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_DEVICE', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211439_WaAKb65X7wX2zjsMExDyy56XRnTRAmPD.png', "sort" = 5, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 193;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '工厂日历', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_CALENDAR', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211448_GBY3HhbPpNnNpnGPWGE6wETW6F6THfr4.png', "sort" = 6, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 199;
UPDATE "users"."menu" SET "parent_id" = 175, "menu_name" = '单位换算', "code" = 'BUSINESS_ALLIED-MANUFACTURING_BASIC_UNIT-CONVERSION', "access_code" = '', "menu_type" = 'menu', "icon" = 'https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20220302/object/1646211456_cKxKHHXHQnM3e7RZNxdkZ3n7ZXJjdKba.png', "sort" = 7, "remark" = '', "category" = '7', "parent_path" = '38,174,175', "is_publish" = 1, "enable_status" = 0, "link" = NULL WHERE "menu_id" = 203;
\ No newline at end of file
... ...
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);
... ...
apiVersion: v1
kind: Service
metadata:
name: allied-creation-manufacture
namespace: mmm-suplus-test
labels:
k8s-app: allied-creation-manufacture
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: allied-creation-manufacture
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: allied-creation-manufacture
namespace: mmm-suplus-test
labels:
k8s-app: allied-creation-manufacture
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: allied-creation-manufacture
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference: {}
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: allied-creation-manufacture
image: 192.168.0.243:5000/mmm/allied-creation-manufacture:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
env:
- name: POSTGRESQL_DB_NAME
valueFrom:
configMapKeyRef:
name: suplus-config
key: postgresqlalliedcreation.dbname
- name: POSTGRESQL_USER
valueFrom:
configMapKeyRef:
name: suplus-config
key: postgresql.user
- name: POSTGRESQL_PASSWORD
valueFrom:
configMapKeyRef:
name: suplus-config
key: postgresql.password
- name: POSTGRESQL_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: postgresql.host
- name: POSTGRESQL_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: postgresql.port
- name: REDIS_HOST
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.ip
- name: REDIS_PORT
valueFrom:
configMapKeyRef:
name: suplus-config
key: redis.port
- name: REDIS_AUTH
value: ""
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "2000"
- name: ENABLE_KAFKA_LOG
value: "true"
- name: HTTP_PORT
value: "8082"
- name: SERVICE_ENV
value: "test"
- name: SUPLUS_ADMIN_BASE_HOST
value: "http://suplus-admin-base-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_GATEWAY_HOST
value: "https://allied-creation-gateway-test.fjmaimaimai.com"
- name: ALLIED_CREATION_USER_HOST
value: "https://allied-creation-user-test.fjmaimaimai.com"
- name: ALLIED_CREATION_COOPERATION_HOST
value: "https://allied-creation-cooperation-test.fjmaimaimai.com"
- name: ALLIED_CREATION_BASIC_HOST
value: "https://allied-creation-basic-test.fjmaimaimai.com"
- name: ALLIED_CREATION_MANUFACTURE_HOST
value: "http://allied-creation-manufacture-test.fjmaimaimai.com"
- name: SMS_SERVE_HOST
value: "https://sms.fjmaimaimai.com:9897"
- name: SUPLUS_SALE_APP
value: "http://suplus-sale-app-gateway-test.fjmaimaimai.com"
- name: MANUFACTURE_DEFAULT_COMPANYID
value: "23"
- name: MANUFACTURE_DEFAULT_ORGID
value: "487"
- name: MANUFACTURE_DEFAULT_WORKSHOPID
value: "28"
- name: MANUFACTURE_PRODUCT_TYPE
value: "SG,SG"
- name: MQTT_HOST
value: "47.97.5.102"
- name: MQTT_PORT
value: "6000"
- name: MQTT_UP
value: "false"
\ No newline at end of file
... ...
... ... @@ -126,3 +126,5 @@ spec:
value: "47.97.5.102"
- name: MQTT_PORT
value: "6000"
- name: MQTT_UP
value: "false"
\ No newline at end of file
... ...
... ... @@ -3,9 +3,12 @@ package main
import (
"fmt"
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/mqtt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task"
"time"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
... ... @@ -26,12 +29,13 @@ func main() {
redis.InitRedis()
log.Logger.Info("server start ....")
log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG))
//go mqtt.Start(log.Logger)
//go task.Run()
//cron := crontab.NewCrontabService(nil)
//cron.StartCrontabTask()
//defer cron.StopCrontabTask()
if constant.MQTT_UP {
go mqtt.Start(log.Logger)
}
go task.Run()
cron := crontab.NewCrontabService(nil)
cron.StartCrontabTask()
defer cron.StopCrontabTask()
time.Sleep(time.Second)
log.Logger.Info("server start!")
web.Run()
... ...
... ... @@ -2,11 +2,10 @@ package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"reflect"
"strings"
"time"
"github.com/beego/beego/v2/core/validation"
)
type CreateAttendanceCommand struct {
... ... @@ -25,11 +24,11 @@ type CreateAttendanceCommand struct {
// 工段ID
SectionId int `cname:"工段ID" json:"sectionId" valid:"Required"`
// 生产日期
ProductDate time.Time `cname:"生产日期" json:"productDate,omitempty" valid:"Required"`
ProductDate string `cname:"生产日期" json:"productDate,omitempty" valid:"Required"`
// 签到
SignIn time.Time `cname:"上岗时间" json:"signIn,omitempty" valid:"Required"`
SignIn string `cname:"上岗时间" json:"signIn,omitempty" valid:"Required"`
// 签退
SignOut time.Time `cname:"下岗时间" json:"signOut,omitempty" valid:"Required"`
SignOut string `cname:"下岗时间" json:"signOut,omitempty" valid:"Required"`
// 考勤状态 1.未审核 2:审核
AttendanceStatus int `cname:"考勤状态" json:"attendanceStatus,omitempty"`
// 休息时长
... ... @@ -41,7 +40,14 @@ type CreateAttendanceCommand struct {
}
func (createAttendanceCommand *CreateAttendanceCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
if err := utils.ValidWorkTime(createAttendanceCommand.SignIn); err != nil {
validation.Error(err.Error())
return
}
if err := utils.ValidWorkTime(createAttendanceCommand.SignOut); err != nil {
validation.Error(err.Error())
return
}
validation.Range(createAttendanceCommand.AttendanceStatus, 1, 2, "attendanceStatus")
}
... ...
... ... @@ -31,6 +31,10 @@ type AttendanceRecordDto struct {
SignOut string `json:"signOut"`
// 考勤状态 1.未审核 2:已审核 3.自动审核
AttendanceStatus int `json:"attendanceStatus"`
// 打卡工时
WorkTime float64 `json:"workTime"`
// 休息工时
BreakTime float64 `json:"breakTime"`
// 工时(审核前)
WorkTimeBefore float64 `json:"workTimeBefore"`
// 工时(审核后)
... ... @@ -50,7 +54,7 @@ func (d *AttendanceRecordDto) LoadDto(m *domain.ProductAttendanceRecord, orgId i
d.WorkStation = m.WorkStation
if !m.SignIn.IsZero() {
d.SignIn = m.SignIn.Local().Format("15:04:05")
d.SignDate = m.ProductTime().Format("2006-01-02")
d.SignDate = m.ProductTime().Local().Format("2006-01-02")
}
if !m.SignOut.IsZero() {
d.SignOut = m.SignOut.Local().Format("15:04:05")
... ... @@ -67,6 +71,8 @@ func (d *AttendanceRecordDto) LoadDto(m *domain.ProductAttendanceRecord, orgId i
t := time.Unix(m.Ext.AttendanceExt.ApproveAt, 0)
d.ApproveAt = t.Local().Format("2006-01-02 15:04:05")
}
d.WorkTime = m.WorkTimeBefore + m.Ext.AttendanceExt.BreakTime
d.BreakTime = m.Ext.AttendanceExt.BreakTime
}
return d
}
... ...
... ... @@ -14,6 +14,12 @@ type WorkshopWorkTimeRecordDto struct {
//SignDate string `json:"signDate"`
// 记录信息
*domain.WorkshopWorkTimeRecordInfo
// 固定工时
EFTWorkTime float64 `json:"eftWorkTime"`
// 临时工时
EDWorkTime float64 `json:"edWorkTime"`
// 派遣工时
EPTWorkTime float64 `json:"eptWorkTime"`
// 记录日期
RecordDate string `json:"recordDate"`
// 组织名称
... ... @@ -30,6 +36,9 @@ func (d *WorkshopWorkTimeRecordDto) LoadDto(m *domain.WorkshopWorkTimeRecord, or
d.WorkshopWorkTimeRecordInfo.EPTWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EPTWorkTime, 1)
d.WorkshopWorkTimeRecordInfo.EDWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EDWorkTime, 1)
d.WorkshopWorkTimeRecordInfo.EFTWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EFTWorkTime, 1)
d.EPTWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EPTWorkTime, 1)
d.EDWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EDWorkTime, 1)
d.EFTWorkTime = utils.Round(m.WorkshopWorkTimeRecordInfo.EFTWorkTime, 1)
}
d.WorkStation = m.WorkStation
d.RecordDate = m.RecordDate.Local().Format("2006-01-02")
... ...
... ... @@ -55,21 +55,22 @@ func (cmd *SearchEmployeeAttendanceQuery) Valid(validation *validation.Validatio
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
var err error
if len(cmd.BeginTime) > 0 {
if cmd.SignBeginTime, err = time.ParseInLocation("2006-01-02 15:04:05", cmd.BeginTime, time.Local); err != nil {
if cmd.SignBeginTime, err = time.ParseInLocation("2006-01-02", cmd.BeginTime, time.Local); err != nil {
log.Logger.Error(err.Error())
validation.Error("开始时间有误")
return
}
}
if len(cmd.EndTime) > 0 {
if cmd.SignEndTime, err = time.ParseInLocation("2006-01-02 15:04:05", cmd.EndTime, time.Local); err != nil {
if cmd.SignEndTime, err = time.ParseInLocation("2006-01-02", cmd.EndTime, time.Local); err != nil {
log.Logger.Error(err.Error())
validation.Error("结束时间有误")
return
}
if cmd.SignBeginTime.Equal(cmd.SignEndTime) {
cmd.SignEndTime = cmd.SignEndTime.Add(time.Hour * 24)
}
cmd.SignEndTime = cmd.SignEndTime.AddDate(0, 0, 1)
//if cmd.SignBeginTime.Equal(cmd.SignEndTime) {
// cmd.SignEndTime = cmd.SignEndTime.Add(time.Hour * 24)
//}
}
//cmd.AttendanceStatus = 6 // 审核 + 自动审核
cmd.InAttendanceStatus = []int{2, 3}
... ...
... ... @@ -105,9 +105,24 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var workTime float64 = 0
if cmd.WorkTime-cmd.BreakTime > 0 {
workTime = cmd.WorkTime - cmd.BreakTime
//var workTime float64 = 0
//if cmd.WorkTime-cmd.BreakTime > 0 {
// workTime = cmd.WorkTime - cmd.BreakTime
//}
signIn, err := xtime.ParseInLocation(time.Local, fmt.Sprintf("%v %v:00", cmd.ProductDate, cmd.SignIn))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
signOut, err := xtime.ParseInLocation(time.Local, fmt.Sprintf("%v %v:00", cmd.ProductDate, cmd.SignOut))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
productDate, err := xtime.ParseInLocation(time.Local, cmd.ProductDate)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if !xtime.BeforeEqual(productDate, time.Now()) {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, fmt.Sprintf("日期需要小于等于%v", time.Now().Format("2006-01-02")))
}
newAttendance := &domain.ProductAttendanceRecord{
//ProductAttendanceId: cmd.ProductAttendanceId,
... ... @@ -116,23 +131,24 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
AttendanceType: cmd.AttendanceType,
ProductWorker: user,
WorkStation: workStation,
SignIn: cmd.SignIn,
SignOut: cmd.SignOut,
SignIn: signIn,
SignOut: signOut,
AttendanceStatus: cmd.AttendanceStatus,
WorkTimeBefore: workTime,
WorkTimeBefore: cmd.WorkTime,
WorkTimeAfter: 0,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithAttendanceExt(&domain.ProductAttendanceRecordExt{
GroupName: productGroup.GroupName,
ProductGroupId: productGroup.ProductGroupId,
BreakTime: cmd.BreakTime,
}),
ProductDate: xtime.New(cmd.ProductDate).BeginningOfDay(),
ProductDate: productDate,
}
if cmd.AttendanceStatus == domain.AttendanceApproved {
newAttendance.WorkTimeAfter = domain.AttendanceApproved
newAttendance.WorkTimeAfter = workTime
newAttendance.WorkTimeAfter = cmd.WorkTime
}
var (
attendanceRepository domain.ProductAttendanceRecordRepository
... ... @@ -142,12 +158,15 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
attendanceRepository, _, _ = factory.FastPgAttendance(transactionContext, 0)
if !cmd.Prepared {
// 检查时间段内是否有重复的打卡记录
count, _, err := attendanceRecordDao.WorkerAttendanceRecordsByProductDate(operateInfo.CompanyId, operateInfo.OrgId, cmd.ProductWorkerId, newAttendance.ProductDate, cmd.SignIn, cmd.SignIn)
count, _, err := attendanceRecordDao.WorkerAttendanceRecordsByProductDate(operateInfo.CompanyId, operateInfo.OrgId, cmd.ProductWorkerId, newAttendance.ProductDate, newAttendance.SignIn, newAttendance.SignIn)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if count > 0 {
return nil, &application.ServiceError{Code: 10040001, Message: fmt.Sprintf("已存在员工%v的工时记录,是否继续新增", user.UserName)}
return map[string]interface{}{
"message": fmt.Sprintf("已存在员工%v的工时记录,是否继续新增", user.UserName),
"needConfirm": true,
}, nil
}
}
if attendance, err := attendanceRepository.Save(newAttendance); err != nil {
... ... @@ -157,7 +176,7 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return attendance, nil
return struct{}{}, nil
}
}
... ...
... ... @@ -18,25 +18,28 @@ func NewCrontabService(options map[string]interface{}) *CrontabService {
}
func (crontabService *CrontabService) initTask() {
//拉取物料数据 每5分执行
pullMaterialK3cloud := task.NewTask("pullMaterialK3cloud", "0 */5 0 * * *", func(ctx context.Context) error {
//拉取物料数据 每4小时执行
pullMaterialK3cloud := task.NewTask("pullMaterialK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
srv := syncdata.PullDataK3CloudService{}
return srv.PullMaterialNewest()
})
task.AddTask("pullMaterialK3cloud", pullMaterialK3cloud)
//拉取物料分组数据 每5分执行
pullMaterialGroupK3cloud := task.NewTask("pullMaterialGroupK3cloud", "0 */5 0 * * *", func(ctx context.Context) error {
//拉取物料分组数据 每4小时执行
pullMaterialGroupK3cloud := task.NewTask("pullMaterialGroupK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
srv := syncdata.PullDataK3CloudService{}
return srv.PullMaterialGroup()
})
task.AddTask("pullMaterialGroupK3cloud", pullMaterialGroupK3cloud)
//拉取订生产订单数据 每5分执行
PullPrdMoK3cloud := task.NewTask("PullPrdMoK3cloud", "0 */5 0 * * *", func(ctx context.Context) error {
//拉取订生产订单数据 每4小时执行
PullPrdMoK3cloud := task.NewTask("PullPrdMoK3cloud", "0 0 */4 * * *", func(ctx context.Context) error {
srv := syncdata.PullDataK3CloudService{}
return srv.PullPrdMoNewest()
})
task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud)
autoInitWorkshopProductRecord := task.NewTask("AutoInitWorkshopProductRecord", "0 0 */4 * * *", AutoInitWorkshopProductRecord)
task.AddTask("AutoInitWorkshopProductRecord", autoInitWorkshopProductRecord)
autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord)
task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord)
... ...
... ... @@ -41,7 +41,7 @@ func AutoApproveProductRecord(ctx context.Context) error {
approveAttendanceRecordsService, _ := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
if _, err = approveAttendanceRecordsService.BatchApprove(records, 0, 0, domain.AttendanceAutoApproved); err != nil {
if _, err = approveAttendanceRecordsService.BatchApprove(records, 0, 0, domain.ProductRecordAutoApproved); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时审核生产记录"})
return err
}
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
// AutoInitWorkshopProductRecord 自动初始化车间生产记录
func AutoInitWorkshopProductRecord(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "自动初始化车间生产记录"})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【自动初始化车间生产记录】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【自动初始化车间生产记录】 启动")
_, workshop, err := factory.FastPgWorkshop(transactionContext, constant.MANUFACTURE_DEFAULT_WORKSHOPID)
if err != nil {
return err
}
productPlanDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(transactionContext.(*pg.TransactionContext))
productPlans, err := productPlanDispatchRecordDao.ProductPlans(constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
utils.GetZeroTimeWithLocal(time.Now(), time.UTC), "")
if err != nil {
return err
}
if len(productPlans) == 0 {
log.Logger.Debug("【自动初始化车间生产记录】 当天执行计划为空")
return nil
}
workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(transactionContext.(*pg.TransactionContext))
workshopProductRecordRepository, _ := repository.NewWorkshopProductRecordRepository(transactionContext.(*pg.TransactionContext))
lines := workshop.GetProductLines(domain.NotDeleted)
for _, line := range lines {
for _, section := range line.ProductSections {
if !(section.SectionName == domain.ProductSection1 || section.SectionName == domain.ProductSection2) {
continue
}
if section.Removed == domain.Deleted {
continue
}
workstation := domain.NewWorkStation(workshop, line, section)
cid := constant.MANUFACTURE_DEFAULT_COMPANYID
oid := constant.MANUFACTURE_DEFAULT_ORGID
for _, plan := range productPlans {
var workshopProductRecord *domain.WorkshopProductRecord
workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, workstation.WorkStationId, plan.ProductPlanId, time.Now())
if err == domain.ErrorNotFound {
productRecord := &domain.ProductRecord{
CompanyId: constant.MANUFACTURE_DEFAULT_COMPANYID,
OrgId: constant.MANUFACTURE_DEFAULT_ORGID,
WorkStation: workstation,
CreatedAt: time.Now(),
ProductRecordInfo: &domain.ProductRecordInfo{
ProductPlanId: plan.ProductPlanId,
PlanProductName: plan.PlanProductName,
BatchNumber: plan.BatchNumber,
},
}
workshopProductRecord = domainService.NewWorkshopProductRecord(productRecord, plan)
workshopProductRecord.UpdateProductWeigh(productRecord)
if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
return err
}
log.Logger.Debug(fmt.Sprintf("【自动初始化车间生产记录】 工位:%v(%v) 初始产能:%v kg 日期:%v ID:%v",
workshopProductRecord.WorkStation.WorkStationId, workshopProductRecord.WorkStation.SectionName,
workshopProductRecord.ProductWeigh, workshopProductRecord.ProductRecordInfo.ProductDate, workshopProductRecord.WorkshopProductRecordId))
continue
}
if err != nil {
log.Logger.Error(err.Error())
return nil
}
}
}
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
... ... @@ -24,7 +24,7 @@ type CreateProductCalendarCommand struct {
// 上班班次 1:全天 2:白班 4:中班 8:夜班
WorkOn int `cname:"上班班次 1:全天 2:白班 4:中班 8:夜班" json:"workOn" valid:"Required"`
// 日历选择
CalendarSelected []int `cname:"日历选择" json:"calendarSelected" valid:"Required"`
CalendarSelected []int `cname:"日历选择" json:"calendarSelected" ` // valid:"Required"
// 上岗时间
InWorkAt string `cname:"上岗时间" json:"inWorkAt" valid:"Required"`
// 下岗时间
... ...
... ... @@ -21,8 +21,8 @@ type UpdateProductCalendarCommand struct {
SectionId int `cname:"工段ID" json:"sectionId" valid:"Required"`
// 上班班次 1:全天 2:白班 4:中班 8:夜班
WorkOn int `cname:"上班班次 1:全天 2:白班 4:中班 8:夜班" json:"workOn" valid:"Required"`
// 日历选择
CalendarSelected []int `cname:"日历选择" json:"calendarSelected" valid:"Required"`
// 日历选择 valid:"Required"
CalendarSelected []int `cname:"日历选择" json:"calendarSelected" `
// 上岗时间
InWorkAt string `cname:"上岗时间" json:"inWorkAt" valid:"Required"`
// 下岗时间
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetProductGroupCalendarQuery struct {
// 生产班组ID
ProductGroupId int `cname:"工厂日历ID" json:"productGroupId" valid:"Required"`
}
func (getProductCalendarQuery *GetProductGroupCalendarQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getProductCalendarQuery *GetProductGroupCalendarQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getProductCalendarQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getProductCalendarQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
... ... @@ -372,6 +372,43 @@ func (productCalendarService *ProductCalendarService) SearchProductCalendar(oper
return count, result, nil
}
// 返回生产班组的工厂日历
func (productCalendarService *ProductCalendarService) GetProductGroupCalendar(getProductCalendarQuery *query.GetProductGroupCalendarQuery) (interface{}, error) {
if err := getProductCalendarQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
productCalendarRepository, _, _ := factory.FastPgProductCalendar(transactionContext, 0)
_, productGroup, err := factory.FastPgProductGroup(transactionContext, getProductCalendarQuery.ProductGroupId)
if err != nil {
return nil, nil
}
_, productCalendar, err := productCalendarRepository.Find(map[string]interface{}{"workStationId": productGroup.WorkStation.WorkStationId, "workOn": productGroup.WorkOn, "limit": 1})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(productCalendar) == 0 {
return nil, nil
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := &dto.ProductCalendarDto{}
result.LoadDto(productCalendar[0], 0)
return result, nil
}
func NewProductCalendarService(options map[string]interface{}) *ProductCalendarService {
newProductCalendarService := &ProductCalendarService{}
return newProductCalendarService
... ...
... ... @@ -21,6 +21,8 @@ type ProductGroupEmployeesDto struct {
// 工作位置键值 (车间ID+'.'+生产线ID+'.'+工段ID)
//WorkStationId string `json:"workStationId,omitempty"`
UserNamePinyin string `json:"pinyin"`
// 在线的
Online bool `json:"online"`
}
func NewProductGroupEmployeesDto(group *domain.ProductGroup) []*ProductGroupEmployeesDto {
... ... @@ -71,14 +73,19 @@ func (d *ProductGroupEmployeesDtos) LoadDto(groups ...*domain.ProductGroup) {
}
}
func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRecord, mapGroupUser map[string]*domain.User, keyFunc func(int) string) {
func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRecord, mapGroupUser map[string]*domain.User, keyFunc func(int) string, checkUserEnableFunc func(int) bool) {
var mapUser = make(map[int]int)
// 打卡的用户
for _, v := range list {
item := &ProductGroupEmployeesDto{}
item.UserId = v.ProductWorker.UserId
item.UserName = v.ProductWorker.UserName
item.ProductGroupId = 0
item.GroupName = ""
item.Online = true
if enable := checkUserEnableFunc(item.UserId); !enable {
continue
}
if v, ok := mapGroupUser[keyFunc(item.UserId)]; ok {
item.GroupName = v.GroupName
item.ProductGroupId = v.GroupId
... ... @@ -89,9 +96,24 @@ func (d *ProductGroupEmployeesDtos) LoadDtoV2(list []*domain.ProductAttendanceRe
}
if _, ok := mapUser[item.UserId]; ok {
continue
} else {
}
mapUser[item.UserId] = item.UserId
d.Append(item)
}
// 未打卡的用户
for _, v := range mapGroupUser {
if _, ok := mapUser[v.UserId]; ok {
continue
}
item := &ProductGroupEmployeesDto{}
item.UserId = v.UserId
item.UserName = v.UserName
item.ProductGroupId = v.GroupId
item.GroupName = v.GroupName
if enable := checkUserEnableFunc(item.UserId); !enable {
continue
}
mapUser[item.UserId] = item.UserId
d.Append(item)
}
}
... ...
... ... @@ -30,6 +30,12 @@ type SearchProductGroupQuery struct {
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 车间ID
WorkshopId int `cname:"车间ID" json: workshopId,omitempty"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId,omitempty"`
// 工段ID
SectionId int `json:"sectionId,omitempty"`
}
func (cmd *SearchProductGroupQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -11,6 +11,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"sort"
"strings"
"time"
... ... @@ -491,7 +492,20 @@ func (productGroupService *ProductGroupService) SearchProductGroupEmployeesV2(op
productGroupRepository, _, _ := factory.FastPgProductGroup(transactionContext, 0)
mapUser, keyFunc := domainService.FindGroupMembers(productGroupRepository, cmd.CompanyId, cmd.OrgId, domain.WorkstationKey(cmd.WorkshopId, cmd.LineId, cmd.SectionId))
var results = dto.NewProductGroupEmployeesDtos()
results.LoadDtoV2(productGroups, mapUser, keyFunc)
userService := domainService.NewUserService()
checkUserEnableFunc := func(userId int) bool {
user, err := userService.User(userId)
if err != nil {
return false
}
if user.EnableStatus == int(domain.UserStatusEnable) {
return true
}
log.Logger.Debug(fmt.Sprintf("ID:%d 用户:%s 状态:%d 已被禁用,过滤", user.UserId, user.UserName, user.EnableStatus))
return false
}
results.LoadDtoV2(productGroups, mapUser, keyFunc, checkUserEnableFunc)
sort.Stable(results)
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
... ... @@ -578,9 +592,7 @@ func (productGroupService *ProductGroupService) SelectorProductGroup(operateInfo
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"groups": results,
}, nil
return results, nil
}
func NewProductGroupService(options map[string]interface{}) *ProductGroupService {
... ...
... ... @@ -4,6 +4,7 @@ import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"reflect"
"regexp"
"strings"
)
... ... @@ -33,7 +34,20 @@ type CreateProductMaterialCommand struct {
}
func (createProductMaterialCommand *CreateProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
createProductMaterialCommand.MaterialNumber = strings.ToUpper(createProductMaterialCommand.MaterialNumber)
match, err := regexp.MatchString("^[A-Z0-9]+$", createProductMaterialCommand.MaterialNumber)
if !match {
validation.Error("物料编码只允许数字加大写字母组合")
return
}
if err != nil {
validation.Error(err.Error())
return
}
if len([]rune(createProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (createProductMaterialCommand *CreateProductMaterialCommand) ValidateCommand() error {
... ...
... ... @@ -36,7 +36,10 @@ type UpdateProductMaterialCommand struct {
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
if len([]rune(updateProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) ValidateCommand() error {
... ...
... ... @@ -91,7 +91,7 @@ func (productMaterialService *ProductMaterialService) GetProductMaterial(operate
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialQuery.ProductMaterialId)))
} else {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
productMaterialGroupIdNames, _, err := materialService.AllMaterialGroupParent(operateInfo, productMaterial.ProductMaterialGroupId)
productMaterialGroupIdNames, _, err := materialService.AllMaterialGroupParentByBacktracking(operateInfo, productMaterial.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
... ...
... ... @@ -130,8 +130,8 @@ func (productMaterialGroupService *ProductMaterialGroupService) ListProductMater
}
// 移除物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMaterialGroup(removeProductMaterialGroupCommand *command.RemoveProductMaterialGroupCommand) (interface{}, error) {
if err := removeProductMaterialGroupCommand.ValidateCommand(); err != nil {
func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.RemoveProductMaterialGroupCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
... ... @@ -144,29 +144,37 @@ func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMat
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ids, err := materialService.AllMaterialGroupChild(operateInfo, cmd.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
productMaterialGroup, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"productMaterialGroupId": removeProductMaterialGroupCommand.ProductMaterialGroupId})
if len(ids) == 0 {
return nil, nil
}
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
count, _, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialGroupIds": ids, "limit": 1})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterialGroup == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("已删除 %s", string(removeProductMaterialGroupCommand.ProductMaterialGroupId)))
if count >= 1 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "请处理当前分组下存在的物料信息")
}
if productMaterialGroup, err := productMaterialGroupRepository.Remove(productMaterialGroup); err != nil {
for _, id := range ids {
productMaterialGroupRepository, productMaterialGroup, err := factory.FastProductMaterialGroup(transactionContext, id)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
}
if _, err = productMaterialGroupRepository.Remove(productMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterialGroup, nil
}
return nil, nil
}
// 更新物料分组服务
... ...
... ... @@ -5,11 +5,13 @@ import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
... ... @@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma
productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext))
productRecordDao, _ := dao.NewProductRecordDao(transactionContext.(*pg.TransactionContext))
begin := xtime.BeginningOfDay()
end := time.Now()
workstationId := domain.WorkstationKey(returnMaterialCommand.WorkshopId, returnMaterialCommand.LineId, returnMaterialCommand.SectionId)
totalReceive, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReceiveMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
totalReturn, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReturnMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
allowReturn := totalReceive - totalReturn
if totalReturn+returnMaterialCommand.Weigh > totalReceive {
if allowReturn > 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料,当前只允许退料 %v kg", totalReceive-totalReturn))
}
return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料"))
}
_, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand))
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CancelProductRecordCommand struct {
// 生产记录ID
ProductRecordId int `cname:"生产记录ID" json:"productRecordId" valid:"Required"`
}
func (cancelProductRecordCommand *CancelProductRecordCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (cancelProductRecordCommand *CancelProductRecordCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(cancelProductRecordCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cancelProductRecordCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
import (
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
)
// HistoryProductRecord 历史生成记录
type HistoryProductRecord struct {
// 生产记录ID
ProductRecordId int `json:"productRecordId,omitempty"`
// 批号
BatchNumber string `json:"batchNumber,omitempty"`
// 计划的产品名称
PlanProductName string `json:"planProductName,omitempty"`
// 创建时间
CreatedAt string `json:"createdAt,omitempty"`
// 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
ProductRecordType int `json:"productRecordType"`
// 生产工人
ProductWorker *domain.User `json:"productWorker,omitempty"`
// 产能 - 审核前
Weight float64 `json:"weight"`
// 状态 1:未审核 2:已审核 3:已撤回 4:已记录
Status int `json:"status"`
}
func (d *HistoryProductRecord) LoadDto(m *domain.ProductRecord) *HistoryProductRecord {
d.ProductRecordId = m.ProductRecordId
d.ProductWorker = m.ProductWorker
d.Weight = utils.Round(m.ProductRecordInfo.Original, 1)
d.Status = m.ProductRecordInfo.ApproveStatus
d.PlanProductName = m.ProductRecordInfo.PlanProductName
d.BatchNumber = m.ProductRecordInfo.BatchNumber
d.CreatedAt = m.CreatedAt.Local().Format("2006-01-02 15:04:05")
d.ProductRecordType = m.ProductRecordType
if m.ProductRecordType != domain.RecordTypeSecondLevelWeigh &&
m.ProductRecordInfo.ApproveStatus == domain.ProductRecordNotApprove &&
!(xtime.BeginningOfDay().Equal(xtime.New(m.CreatedAt.Local()).BeginningOfDay())) {
//log.Logger.Debug("not equal", map[string]interface{}{"t1": xtime.BeginningOfDay(), "t2": xtime.New(m.CreatedAt.Local()).BeginningOfDay()})
d.Status = domain.ProductRecordLogged
}
if m.ProductRecordType == domain.RecordTypeSecondLevelWeigh && m.ProductRecordInfo.ApproveStatus == domain.ProductRecordAutoApproved {
d.Status = domain.ProductRecordApproved
}
return d
}
... ...
package query
import (
"fmt"
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"reflect"
"strings"
"time"
"github.com/beego/beego/v2/core/validation"
)
type HistoryProductRecordQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
Limit int `cname:"查询限制" json:"limit"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
// 匹配多个组织
InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId,omitempty"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId,omitempty"`
// 工段ID
SectionId int `json:"sectionId,omitempty"`
// 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重" json:"productRecordType"`
// 生产线名称
//LineName string `cname:"生产线名称" json:"lineName,omitempty"`
// 工段名称
//SectionName string `cname:"工段名称" json:"sectionName,omitempty"`
// 员工类型 1:固定 2:派遣 3.临时
//EmployeeType int `cname:"员工类型 1:固定 2:派遣 3.临时" json:"employeeType"`
// 开始时间
//BeginTime string `cname:"开始时间" json:"beginTime"`
// 结束时间
//EndTime string `cname:"结束时间" json:"endTime"`
// 上一次记录ID
LastProductRecordId int `cname:"上一次记录ID" json:"lastProductRecordId"`
// 日期
Date string `cname:"日期" json:"date"`
// 生产员工ID
ProductWorkerId int `cname:"生产员工ID" json:"productWorkerId"`
// 状态 0:全部 1:未审核 2:已审核 3:已撤回 4:已记录
Status int `cname:"状态" json:"status"`
// 状态 0:全部 1:未审核 2:已审核 3:已撤回 4:已记录
InStatus []int `cname:"匹配多个状态" json:"intStatus"`
// 开始时间
ProductBeginTime time.Time `cname:"开始时间" json:"productBeginTime"`
// 结束时间
ProductEndTime time.Time `cname:"结束时间" json:"productEndTime"`
}
func (cmd *HistoryProductRecordQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
//var err error
//if len(cmd.BeginTime) > 0 {
// if cmd.ProductBeginTime, err = time.Parse("2006-01-02 15:04:05", cmd.BeginTime); err != nil {
// log.Logger.Error(err.Error())
// validation.Error("开始时间有误")
// return
// }
//}
//if len(cmd.EndTime) > 0 {
// if cmd.ProductEndTime, err = time.Parse("2006-01-02 15:04:05", cmd.EndTime); err != nil {
// log.Logger.Error(err.Error())
// validation.Error("结束时间有误")
// return
// }
// if cmd.ProductEndTime.Equal(cmd.ProductBeginTime) {
// cmd.ProductEndTime = cmd.ProductEndTime.Add(time.Hour * 24)
// }
//}
if len(cmd.Date) > 0 {
t, err := xtime.Parse(cmd.Date)
if err != nil {
log.Logger.Error(err.Error())
validation.Error("日期有误")
return
}
cmd.ProductBeginTime = t
cmd.ProductEndTime = t.AddDate(0, 0, 1)
}
if cmd.ProductRecordType == domain.RecordTypeReceiveMaterial || cmd.ProductRecordType == domain.RecordTypeReturnMaterial {
if cmd.Status == domain.ProductRecordNotApprove {
cmd.Status = domain.ProductRecordNotApprove
if xtime.IsZero(cmd.ProductBeginTime) || xtime.BeforeEqual(cmd.ProductBeginTime, xtime.BeginningOfDay()) {
cmd.ProductBeginTime = xtime.BeginningOfDay()
}
} else if cmd.Status == domain.ProductRecordLogged {
cmd.Status = domain.ProductRecordNotApprove
if len(cmd.Date) == 0 && xtime.IsZero(cmd.ProductEndTime) {
cmd.ProductEndTime = xtime.BeginningOfDay()
}
if len(cmd.Date) > 0 && !xtime.BeforeEqual(cmd.ProductEndTime, xtime.BeginningOfDay()) {
cmd.Status = domain.ProductRecordLogged
}
}
}
if cmd.ProductRecordType == domain.RecordTypeSecondLevelWeigh && cmd.Status == domain.ProductRecordApproved {
cmd.Status = 0
cmd.InStatus = []int{domain.ProductRecordApproved, domain.ProductRecordAutoApproved}
}
}
func (cmd *HistoryProductRecordQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
... ... @@ -274,6 +274,41 @@ func (productRecordService *ProductRecordService) SearchProductRecord(operateInf
return count, result, nil
}
// 返回生产记录服务列表
func (productRecordService *ProductRecordService) HistoryProductRecord(operateInfo *domain.OperateInfo, query *query.HistoryProductRecordQuery) (int64, interface{}, error) {
if err := query.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productRecordRepository domain.ProductRecordRepository
productRecordRepository, _, _ = factory.FastPgProductRecord(transactionContext, 0)
count, productRecords, err := productRecordRepository.Find(utils.ObjectToMap(query))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var result = make([]*dto.HistoryProductRecord, 0)
for i := range productRecords {
item := productRecords[i]
newItem := &dto.HistoryProductRecord{}
newItem.LoadDto(item)
result = append(result, newItem)
}
return count, result, nil
}
// 生产记录统计
func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *command.ProductRecordStaticsCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
... ... @@ -308,6 +343,33 @@ func (productRecordService *ProductRecordService) ProductRecordStatics(cmd *comm
return nil, nil
}
// 生产记录审核
func (productRecordService *ProductRecordService) CancelProductRecord(cmd *command.CancelProductRecordCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
svr, err := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
if _, err = svr.Cancel(cmd.ProductRecordId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewProductRecordService(options map[string]interface{}) *ProductRecordService {
newProductRecordService := &ProductRecordService{}
return newProductRecordService
... ...
... ... @@ -18,6 +18,8 @@ type SearchMaterialsQuery struct {
LineId int `cname:"生产线ID" json:"lineId,omitempty"`
// 工段ID
SectionId int `json:"sectionId,omitempty"`
// 智能称重标识 0:全部 1:是 2:否
IntelligentWeighingFlag int `cname:"智能称重标识" json:"intelligentWeighingFlag"`
}
func (listProductGroupQuery *SearchMaterialsQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -2,16 +2,19 @@ package constant
import (
"fmt"
"os"
"strconv"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
)
//var Configurator utils.Configurator = utils.NewConfig("ini","config/app_test.conf")
var Configurator utils.Configurator = utils.EnvConfigurator{}
var SERVICE_NAME = "allied-creation-manufacture"
var SERVICE_ENV = "dev"
var HTTP_PORT int = 8081
var CACHE_PREFIX = "allied-creation-manufacture-dev"
var LOG_LEVEL = "debug"
var LOG_FILE = "app.log"
var PPROF_ON = true
//天联共创基础模块
var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com"
... ... @@ -35,46 +38,14 @@ const HeaderOrgId = "orgId"
const HeaderOrgIds = "orgIds"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
//if os.Getenv("CUSTOMER_ACCOUNT") != "" {
// account := os.Getenv("CUSTOMER_ACCOUNT")
// accounts := strings.Split(account, CUSTOMER_ACCOUNT_DELIMITER)
// var tmpAccounts []int64
// for i := range accounts {
// v, err := strconv.ParseInt(accounts[i], 10, 64)
// if err != nil {
// panic(err)
// }
// tmpAccounts = append(tmpAccounts, v)
// }
// if len(tmpAccounts) > 0 {
// CUSTOMER_ACCOUNT = tmpAccounts
// }
//}
if os.Getenv("ALLIED_CREATION_BASIC_HOST") != "" {
ALLIED_CREATION_BASIC_HOST = os.Getenv("ALLIED_CREATION_BASIC_HOST")
}
if os.Getenv("ALLIED_CREATION_USER_HOST") != "" {
ALLIED_CREATION_USER_HOST = os.Getenv("ALLIED_CREATION_USER_HOST")
}
if os.Getenv("ALLIED_CREATION_COOPERATION_HOST") != "" {
ALLIED_CREATION_COOPERATION_HOST = os.Getenv("ALLIED_CREATION_COOPERATION_HOST")
}
//if os.Getenv("SMS_SERVE_HOST") != "" {
// SMS_SERVE_HOST = os.Getenv("SMS_SERVE_HOST")
//}
if os.Getenv("MMM_BYTE_BANK_HOST") != "" {
MMM_BYTE_BANK_HOST = os.Getenv("MMM_BYTE_BANK_HOST")
}
if os.Getenv("SERVICE_ENV") != "" {
SERVICE_ENV = os.Getenv("SERVICE_ENV")
}
if os.Getenv("HTTP_PORT") != "" {
HTTP_PORT, _ = strconv.Atoi(os.Getenv("HTTP_PORT"))
}
LOG_LEVEL = Configurator.DefaultString("LOG_LEVEL", LOG_LEVEL)
ALLIED_CREATION_BASIC_HOST = Configurator.DefaultString("ALLIED_CREATION_BASIC_HOST", ALLIED_CREATION_BASIC_HOST)
ALLIED_CREATION_USER_HOST = Configurator.DefaultString("ALLIED_CREATION_USER_HOST", ALLIED_CREATION_USER_HOST)
ALLIED_CREATION_COOPERATION_HOST = Configurator.DefaultString("ALLIED_CREATION_COOPERATION_HOST", ALLIED_CREATION_COOPERATION_HOST)
MMM_BYTE_BANK_HOST = Configurator.DefaultString("MMM_BYTE_BANK_HOST", MMM_BYTE_BANK_HOST)
SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV)
HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT)
SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
PPROF_ON = Configurator.DefaultBool("PPROF_ON", PPROF_ON)
CACHE_PREFIX = SERVICE_NAME
}
... ...
package constant
import "os"
var (
// kafka 地址
KAFKA_HOST = "192.168.0.250:9092,192.168.0.251:9092,192.168.0.252:9092" //"106.75.231.90:9092"
... ... @@ -14,13 +12,6 @@ var (
)
func init() {
if os.Getenv("KAFKA_HOST") != "" {
KAFKA_HOST = os.Getenv("KAFKA_HOST")
}
//if os.Getenv("TOPIC_LOG_STASH") != "" {
// POSTGRESQL_PORT = os.Getenv("TOPIC_LOG_STASH")
//}
if os.Getenv("ENABLE_KAFKA_LOG") != "" {
ENABLE_KAFKA_LOG = true
}
KAFKA_HOST = Configurator.DefaultString("KAFKA_HOST", KAFKA_HOST)
ENABLE_KAFKA_LOG = Configurator.DefaultBool("ENABLE_KAFKA_LOG", ENABLE_KAFKA_LOG)
}
... ...
package constant
import (
"os"
"strconv"
"strings"
)
... ... @@ -20,18 +18,10 @@ var (
)
func init() {
if os.Getenv("MANUFACTURE_DEFAULT_COMPANYID") != "" {
MANUFACTURE_DEFAULT_COMPANYID, _ = strconv.Atoi(os.Getenv("MANUFACTURE_DEFAULT_COMPANYID"))
}
if os.Getenv("MANUFACTURE_DEFAULT_ORGID") != "" {
MANUFACTURE_DEFAULT_ORGID, _ = strconv.Atoi(os.Getenv("MANUFACTURE_DEFAULT_ORGID"))
}
if os.Getenv("MANUFACTURE_DEFAULT_WORKSHOPID") != "" {
MANUFACTURE_DEFAULT_WORKSHOPID, _ = strconv.Atoi(os.Getenv("MANUFACTURE_DEFAULT_WORKSHOPID"))
}
if os.Getenv("MANUFACTURE_PRODUCT_TYPE") != "" {
MANUFACTURE_PRODUCT_TYPE = os.Getenv("MANUFACTURE_PRODUCT_TYPE")
}
MANUFACTURE_DEFAULT_COMPANYID = Configurator.DefaultInt("MANUFACTURE_DEFAULT_COMPANYID", MANUFACTURE_DEFAULT_COMPANYID)
MANUFACTURE_DEFAULT_ORGID = Configurator.DefaultInt("MANUFACTURE_DEFAULT_ORGID", MANUFACTURE_DEFAULT_ORGID)
MANUFACTURE_DEFAULT_WORKSHOPID = Configurator.DefaultInt("MANUFACTURE_DEFAULT_WORKSHOPID", MANUFACTURE_DEFAULT_WORKSHOPID)
MANUFACTURE_PRODUCT_TYPE = Configurator.DefaultString("MANUFACTURE_PRODUCT_TYPE", MANUFACTURE_PRODUCT_TYPE)
productTypes := strings.Split(MANUFACTURE_PRODUCT_TYPE, ",")
for i, v := range productTypes {
MapProductType[i+1] = v
... ...
package constant
import "os"
var MQTT_TOPIC = "/MQTT"
//设备商提供的测试地址
... ... @@ -30,18 +28,12 @@ var MQTT_HOST = "47.97.5.102"
var MQTT_PORT = "6000"
var MQTT_USER = "admin"
var MQTT_PASSWORD = "123456"
var MQTT_UP = true
func init() {
if os.Getenv("MQTT_HOST") != "" {
MQTT_HOST = os.Getenv("MQTT_HOST")
}
if os.Getenv("MQTT_PORT") != "" {
MQTT_PORT = os.Getenv("MQTT_PORT")
}
if os.Getenv("MQTT_USER") != "" {
MQTT_USER = os.Getenv("MQTT_USER")
}
if os.Getenv("MQTT_PASSWORD") != "" {
MQTT_PASSWORD = os.Getenv("MQTT_PASSWORD")
}
MQTT_HOST = Configurator.DefaultString("MQTT_HOST", MQTT_HOST)
MQTT_PORT = Configurator.DefaultString("MQTT_PORT", MQTT_PORT)
MQTT_USER = Configurator.DefaultString("MQTT_USER", MQTT_USER)
MQTT_PASSWORD = Configurator.DefaultString("MQTT_PASSWORD", MQTT_PASSWORD)
MQTT_UP = Configurator.DefaultBool("MQTT_UP", MQTT_UP)
}
... ...
... ... @@ -3,10 +3,6 @@
package constant
import (
"os"
)
var POSTGRESQL_DB_NAME = "terms"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "123456"
... ... @@ -17,25 +13,12 @@ var DISABLE_SQL_GENERATE_PRINT = false
var DISABLE_SQL_GENERATE_COMMENT = true
func init() {
if os.Getenv("POSTGRESQL_DB_NAME") != "" {
POSTGRESQL_DB_NAME = os.Getenv("POSTGRESQL_DB_NAME")
}
if os.Getenv("POSTGRESQL_USER") != "" {
POSTGRESQL_USER = os.Getenv("POSTGRESQL_USER")
}
if os.Getenv("POSTGRESQL_PASSWORD") != "" {
POSTGRESQL_PASSWORD = os.Getenv("POSTGRESQL_PASSWORD")
}
if os.Getenv("POSTGRESQL_HOST") != "" {
POSTGRESQL_HOST = os.Getenv("POSTGRESQL_HOST")
}
if os.Getenv("POSTGRESQL_PORT") != "" {
POSTGRESQL_PORT = os.Getenv("POSTGRESQL_PORT")
}
if os.Getenv("DISABLE_CREATE_TABLE") != "" {
DISABLE_CREATE_TABLE = true
}
if os.Getenv("DISABLE_SQL_GENERATE_PRINT") != "" {
DISABLE_SQL_GENERATE_PRINT = true
}
POSTGRESQL_HOST = Configurator.DefaultString("POSTGRESQL_HOST", POSTGRESQL_HOST)
POSTGRESQL_PORT = Configurator.DefaultString("POSTGRESQL_PORT", POSTGRESQL_PORT)
POSTGRESQL_DB_NAME = Configurator.DefaultString("POSTGRESQL_DB_NAME", POSTGRESQL_DB_NAME)
POSTGRESQL_USER = Configurator.DefaultString("POSTGRESQL_USER", POSTGRESQL_USER)
POSTGRESQL_PASSWORD = Configurator.DefaultString("POSTGRESQL_PASSWORD", POSTGRESQL_PASSWORD)
DISABLE_CREATE_TABLE = Configurator.DefaultBool("DISABLE_CREATE_TABLE", DISABLE_CREATE_TABLE)
DISABLE_SQL_GENERATE_PRINT = Configurator.DefaultBool("DISABLE_SQL_GENERATE_PRINT", DISABLE_SQL_GENERATE_PRINT)
}
... ...
package constant
import "os"
var (
REDIS_HOST = "127.0.0.1"
REDIS_PORT = "6379"
REDIS_AUTH = ""
REDIS_ADDRESS = ""
// 是否关闭仓储层缓存
DISABLE_REPOSITORY_CACHE = false
ENABLE_REPOSITORY_CACHE = true
// 缓存过期时间 单位秒
REPOSITORY_CACHE_EXPIRE = 30 * 60
REDIS_ADDRESS = ""
// redis 考勤机打卡消息队列
REDIS_ZKTECO_KEY = "allied-creation-zkteco"
// redis 车间数据消息队列
... ... @@ -19,21 +17,9 @@ var (
)
func init() {
if os.Getenv("REDIS_HOST") != "" {
REDIS_HOST = os.Getenv("REDIS_HOST")
REDIS_AUTH = os.Getenv("REDIS_AUTH")
}
if os.Getenv("REDIS_PORT") != "" {
REDIS_PORT = os.Getenv("REDIS_PORT")
}
if _, ok := os.LookupEnv("REDIS_AUTH"); ok {
REDIS_AUTH = os.Getenv("REDIS_AUTH")
}
if os.Getenv("ENABLE_REPOSITORY_CACHE") != "" {
DISABLE_REPOSITORY_CACHE = false
}
if os.Getenv("DISABLE_REPOSITORY_CACHE") != "" {
DISABLE_REPOSITORY_CACHE = true
}
REDIS_HOST = Configurator.DefaultString("REDIS_HOST", REDIS_HOST)
REDIS_PORT = Configurator.DefaultString("REDIS_PORT", REDIS_PORT)
REDIS_AUTH = Configurator.DefaultString("REDIS_AUTH", REDIS_AUTH)
ENABLE_REPOSITORY_CACHE = Configurator.DefaultBool("ENABLE_REPOSITORY_CACHE", ENABLE_REPOSITORY_CACHE)
REDIS_ADDRESS = REDIS_HOST + ":" + REDIS_PORT
}
... ...
... ... @@ -224,6 +224,17 @@ func (d *DeviceRunningRecordInfo) HourDeviceStatusDetail(endTime int) map[string
on = append(on, s)
break
case 3:
if len(s) == 2 && s[1]-s[0] <= 5 {
last := len(on) - 1
if last >= 0 && len(on[last]) == 2 {
if on[last][1]+1 == s[0] { // [56,79] [80,80] => [56,80]
on[last][1] = s[1]
break
}
}
on = append(on, s)
break
}
off = append(off, s)
break
}
... ...
... ... @@ -2,8 +2,10 @@ package domain
import (
"errors"
"fmt"
"github.com/linmadan/egglib-go/utils/xtime"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
... ... @@ -78,15 +80,48 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr
if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) {
return 0
}
wt := utils.Round(productAttendanceRecord.SignOut.Sub(productAttendanceRecord.SignIn).Hours(), 1)
signIn := roundTime(productAttendanceRecord.SignIn)
signOut := roundTime(productAttendanceRecord.SignOut)
wt := utils.Round(signOut.Sub(signIn).Hours(), 2)
if productCalendar == nil {
return wt
return roundWorkTime(wt)
}
wt = wt - productAttendanceRecord.AttendanceBreakTime(productCalendar)
if wt < 0 {
return 0
}
return wt
return roundWorkTime(wt)
}
// roundWorkTime 工时取整[0:0.167]=> 0 \ [0.167,0.667]=> 0.5 \ [0.667,1]=>1
// 10/60 = 0.167 40/60 = 0.667
func roundWorkTime(wt float64) float64 {
i := float64(int(wt))
f := wt - i
if f < 0.167 {
return i
}
if f >= 0.167 && f < 0.667 {
return i + 0.5
}
if f >= 0.667 {
return i + 1
}
return i
}
func roundTime(t time.Time) time.Time {
hour, min, _ := t.Local().Clock()
y, m, d := t.Local().Date()
newTime := time.Date(y, m, d, hour, 0, 0, 0, time.Local)
if min < 11 {
min = 0
} else if min >= 11 && min < 41 {
min = 30
} else {
min = 60
}
return newTime.Add(time.Minute * time.Duration(min))
}
func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error {
... ... @@ -100,7 +135,7 @@ func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductC
return nil
}
newNow := now.BeginningOfDay().Add(-time.Hour * 24)
if overDay && productCalendar.MatchCalendarSelected(newNow) {
if overDay { //&& productCalendar.MatchCalendarSelected(newNow)
productAttendanceRecord.ProductDate = newNow
}
return nil
... ... @@ -132,20 +167,20 @@ func (productAttendanceRecord *ProductAttendanceRecord) ProductTime() time.Time
}
func (productAttendanceRecord *ProductAttendanceRecord) GroupName() string {
if productAttendanceRecord.Ext != nil {
if productAttendanceRecord.Ext == nil {
return ""
}
if productAttendanceRecord.Ext.AttendanceExt != nil {
if productAttendanceRecord.Ext.AttendanceExt == nil {
return ""
}
return productAttendanceRecord.Ext.AttendanceExt.GroupName
}
func (productAttendanceRecord *ProductAttendanceRecord) ApproveUser() *User {
if productAttendanceRecord.Ext != nil {
if productAttendanceRecord.Ext == nil {
return nil
}
if productAttendanceRecord.Ext.AttendanceExt != nil {
if productAttendanceRecord.Ext.AttendanceExt == nil {
return nil
}
if productAttendanceRecord.Ext.AttendanceExt.ApproveUserId == 0 {
... ... @@ -179,11 +214,19 @@ func (productAttendanceRecord *ProductAttendanceRecord) AttendanceBreakTime(prod
var (
checkSignIn, checkSignOut time.Time
)
checkSignIn = v.GetCheckBeginTime(signIn)
checkSignOut = v.GetCheckEndTime(signIn)
if xtime.BeforeEqual(signIn, checkSignIn) && xtime.AfterEqual(signOut, checkSignOut) {
checkSignIn = v.GetCheckBeginTime(signIn.Local())
checkSignOut = v.GetCheckEndTime(signIn.Local())
if xtime.BeforeEqual(signIn.Local(), checkSignIn) && xtime.AfterEqual(signOut.Local(), checkSignIn) {
if xtime.AfterEqual(signOut.Local(), checkSignOut) {
bt += v.BreakTime
} else {
bt += utils.Round(signOut.Local().Sub(checkSignIn).Hours(), 2)
}
}
log.Logger.Debug(fmt.Sprintf("range(%v,%v) actual(%v,%v) break_time:%v", checkSignIn, checkSignOut, signIn.Local(), signOut.Local(), bt))
}
if productAttendanceRecord.Ext != nil && productAttendanceRecord.Ext.AttendanceExt != nil {
productAttendanceRecord.Ext.AttendanceExt.BreakTime = bt
}
return bt
}
... ...
... ... @@ -14,4 +14,6 @@ type ProductAttendanceRecordExt struct {
ApproveUserName string `json:"approveUserName,omitempty"`
// 审核时间
ApproveAt int64 `json:"approveAt,omitempty"`
// 休息时间
BreakTime float64 `json:"breakTime"`
}
... ...
... ... @@ -25,8 +25,8 @@ func TestComputeWorkTimeBefore(t *testing.T) {
[]*ProductAttendanceRecord{
{
SignIn: xtime.MustParse("2022-05-05 09:00:00"),
SignOut: xtime.MustParse("2022-05-05 12:00:00"),
WorkTimeBefore: 2,
SignOut: xtime.MustParse("2022-05-05 13:00:00"),
WorkTimeBefore: 3,
},
{
SignIn: xtime.MustParse("2022-05-05 12:00:00"),
... ...
... ... @@ -34,16 +34,16 @@ func (period *ProductCalendarBreakTimePeriod) CheckOverDay() (bool, error) {
func (period *ProductCalendarBreakTimePeriod) GetCheckBeginTime(t time.Time) time.Time {
y, m, d := t.Date()
inHour, _ := strconv.Atoi(strings.Split(period.BeginAt, ":")[0])
inMinuter, _ := strconv.Atoi(strings.Split(period.BeginAt, ":")[1])
return time.Date(y, m, d, inHour, inMinuter, 0, 0, t.Location())
inHour, _ := strconv.ParseInt(strings.Split(period.BeginAt, ":")[0], 10, 64)
inMinuter, _ := strconv.ParseInt(strings.Split(period.BeginAt, ":")[1], 10, 64)
return time.Date(y, m, d, int(inHour), int(inMinuter), 0, 0, time.Local)
}
func (period *ProductCalendarBreakTimePeriod) GetCheckEndTime(t time.Time) time.Time {
y, m, d := t.Date()
inHour, _ := strconv.Atoi(strings.Split(period.EndAt, ":")[0])
inMinuter, _ := strconv.Atoi(strings.Split(period.EndAt, ":")[1])
checkTime := time.Date(y, m, d, inHour, inMinuter, 0, 0, t.Location())
inHour, _ := strconv.ParseInt(strings.Split(period.EndAt, ":")[0], 10, 64)
inMinuter, _ := strconv.ParseInt(strings.Split(period.EndAt, ":")[1], 10, 64)
checkTime := time.Date(y, m, d, int(inHour), int(inMinuter), 0, 0, time.Local)
if overDay, err := period.CheckOverDay(); overDay && err == nil {
return checkTime.AddDate(0, 0, 1)
}
... ...
... ... @@ -17,6 +17,9 @@ const (
const (
ProductRecordNotApprove = 1 // 未审核
ProductRecordApproved = 2 // 已审核
ProductRecordWithdraw = 3 // 已撤回
ProductRecordLogged = 4 // 已记录
ProductRecordAutoApproved = 5 // 自动审核
)
// 生产记录
... ... @@ -82,6 +85,21 @@ func (productRecord *ProductRecord) Approve(approveUser *User, weighAfter float6
return nil
}
func (productRecord *ProductRecord) Cancel() error {
if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordApproved {
return errors.New("已审核")
}
if productRecord.ProductRecordInfo.ApproveStatus == ProductRecordWithdraw {
return errors.New("已撤销")
}
//if xtime.BeforeEqual(productRecord.CreatedAt, xtime.BeginningOfDay()) {
// return errors.New("已记录")
//}
productRecord.ProductRecordInfo.ApproveStatus = ProductRecordWithdraw
productRecord.UpdatedAt = time.Now()
return nil
}
func TaskKeyPatternProductRecordStatics() string {
return fmt.Sprintf("%v:task:product-record:statics", constant.CACHE_PREFIX)
}
... ...
... ... @@ -11,7 +11,7 @@ const (
)
const (
ProductSection1 = "打料"
ProductSection1 = "制模"
ProductSection2 = "成型"
ProductSection3 = "穿串"
ProductSection4 = "包装"
... ...
... ... @@ -12,7 +12,7 @@ type ProductRecordInfo struct {
WeighBefore float64 `json:"weighBefore"`
// 产能-审核后
WeighAfter float64 `json:"weighAfter"`
// 审核状态 1:未审核 2:已审核
// 审核状态 1:未审核 2:已审核 3.已撤回 4.已记录 5.自动审核
ApproveStatus int `json:"approveStatus"`
// 审核时间
ApproveAt int64 `json:"approveAt"`
... ...
... ... @@ -6,6 +6,15 @@ const (
EmployeePartTime = 3 // 临时
)
// 用户状态
const (
UserStatusEnable UserStatus = 1
UserStatusDisable UserStatus = 2
UserStatusDestroy UserStatus = 3
)
type UserStatus int
// 用户对象
type User struct {
// 用户Id 用户唯一标识
... ... @@ -21,6 +30,8 @@ type User struct {
// 手机号码
Phone string `json:"phone,omitempty"`
// 启用状态
EnableStatus int `json:"-"`
// 额外扩展的参数
GroupId int `json:"-"`
GroupName string `json:"-"`
... ...
... ... @@ -176,3 +176,12 @@ func (gateway HttpLibAlliedCreationUser) OrgSearch(param ReqOrgSearch) (int, []*
err := gateway.FastDoRequest(url, method, param, &data)
return data.Count, data.Orgs, err
}
// TerminalReport 终端汇报
func (gateway HttpLibAlliedCreationUser) TerminalReport(param ReqTerminalReport) (DataTerminalReport, error) {
url := gateway.Host() + "/terminal/report"
method := "post"
var data DataTerminalReport
err := gateway.FastDoRequest(url, method, param, &data)
return data, err
}
... ...
... ... @@ -163,3 +163,21 @@ type (
Orgs []*models.Organization `json:"orgs"`
}
)
//返回组织列表
type (
ReqTerminalReport struct {
TerminalType string `json:"terminalType"`
TerminalId string `json:"terminalId"`
Command string `json:"command"`
Content string `json:"content"`
Table string `json:"table"`
CompanyId int64 `json:"companyId"`
OrgId int64 `json:"orgId"`
}
DataTerminalReport struct {
Response string `json:"response"`
}
)
... ...
... ... @@ -25,7 +25,6 @@ func (dao *DeviceDailyRunningRecordDao) TimeSectionRunningRecord(companyId, orgI
tx := dao.transactionContext.PgTx
sql := fmt.Sprintf(`
WITH ts_product as(
select sum(a.weight) total,a.ts from (
select
... ... @@ -47,8 +46,8 @@ WITH ts_product as(
-- select * from ts_product
, ts_product_list as (
select d.ts,ts_product.total from (
select to_char(c.ts::timestamp at time ZONE 'Asia/shanghai','mm-dd') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),'1 day') ts
select to_char(c.ts,'mm-dd') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai',to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai','1 day') ts
) c ) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total
... ...
... ... @@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC
// 日期
// 产品编号
// 调度状态 status
func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
func (dao *ProductPlanDispatchRecordDao) ProductPlanDispatchRecord(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
tx := dao.transactionContext.PgTx
productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord)
query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{})
... ... @@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
query.Where("org_id = ?", orgId)
query.Where("work_station->>'workStationId'=?", workStationId)
query.Where("product_date = ?", date)
if status > 0 {
query.Where("plan_dispatch_status = ?", status)
}
query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode)
query.Order("updated_at desc")
if err := query.First(); err != nil {
... ... @@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel)
}
}
func (dao *ProductPlanDispatchRecordDao) ProductPlan(companyId, orgId int, workshopId int, date time.Time, productCode string) (*domain.ProductPlan, error) {
tx := dao.transactionContext.PgTx
productPlan := new(models.ProductPlan)
query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
query.Where("company_id = ?", companyId)
query.Where("org_id = ?", orgId)
query.Where("workshop->>'workshopId'='?'", workshopId)
query.Where("product_date = ?", date)
if len(productCode) > 0 {
query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
}
query.Order("updated_at desc")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productPlan.ProductPlanId == 0 {
return nil, nil
} else {
return transform.TransformToProductPlanDomainModelFromPgModels(productPlan)
}
}
func (dao *ProductPlanDispatchRecordDao) ProductPlans(companyId, orgId int, workshopId int, date time.Time, productCode string) ([]*domain.ProductPlan, error) {
tx := dao.transactionContext.PgTx
productPlan := new(models.ProductPlan)
query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
query.Where("company_id = ?", companyId)
query.Where("org_id = ?", orgId)
query.Where("workshop->>'workshopId'='?'", workshopId)
query.Where("product_date = ?", date)
if len(productCode) > 0 {
query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
}
query.Order("updated_at desc")
var productPlanModels = make([]*models.ProductPlan, 0)
var productPlans = make([]*domain.ProductPlan, 0)
if err := query.Select(&productPlanModels); err != nil {
return productPlans, err
} else {
for _, productPlanModel := range productPlanModels {
if productPlan, err := transform.TransformToProductPlanDomainModelFromPgModels(productPlanModel); err != nil {
return productPlans, err
} else {
productPlans = append(productPlans, productPlan)
}
}
return productPlans, nil
}
}
... ...
... ... @@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from (
and product_record_info->>'approveStatus'='2'
and created_at >=?
and created_at <?
and work_station->>'sectionName' in ('打料','成型','穿串','包装')
and work_station->>'sectionName' in ('制模','成型','穿串','包装')
) a
group by a.workStationId
)
... ... @@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0)
)
--select * from item_product_rate
select a.sname, coalesce(b.rate,0) rate from (
select unnest(ARRAY ['打料','成型','穿串','包装']) sname
select unnest(ARRAY ['制模','成型','穿串','包装']) sname
) a left join item_product_rate b on a.sname=b.sname`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil {
return err
}
return nil
}
// ProductWeightStatics 产能统计
func (dao *ProductRecordDao) ProductWeightStatics(companyId, orgId, productRecordType, productPlanId int, workstationId string, beginTime time.Time, endTime time.Time) (float64, error) {
tx := dao.transactionContext.PgTx
var result = struct {
Total float64
}{}
sql := fmt.Sprintf(`
select coalesce(sum(cast(product_record_info->>'original' as DECIMAL)),0) total
from manufacture.product_records
where company_id = ? and org_id = ? and product_record_type = ?
and work_station->>'workStationId' = ?
and product_record_info->>'productPlanId' = '?'
and created_at >= ? and created_at < ?
`)
if _, err := tx.QueryOne(&result, sql, companyId, orgId, productRecordType, workstationId, productPlanId, beginTime, endTime); err != nil {
return 0, err
}
return result.Total, nil
}
... ...
... ... @@ -63,6 +63,7 @@ func (svr *UserService) ToUser(from *models.User) *domain.User {
IcCardNumber: from.IcCardNumber,
Avatar: from.UserInfo.Avatar,
Phone: from.UserInfo.Phone,
EnableStatus: from.EnableStatus,
}
if user.EmployeeType == 0 {
user.EmployeeType = 1 //默认正式员工
... ...
... ... @@ -100,9 +100,9 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
beginTime = xtime.BeginningOfDay() //time.Now().Add(-time.Hour*5)
endTime = time.Now()
)
if !xtime.IsZero(request.Date.Time()) {
beginTime = request.Date.Time().AddDate(0, 0, -1)
endTime = request.Date.Time()
if !xtime.IsZero(request.Date.Time()) && !request.Date.Time().Equal(beginTime) {
beginTime = request.Date.Time()
endTime = request.Date.Time().AddDate(0, 0, 1)
}
for _, v := range workshop.GetProductLines(domain.NotDeleted) {
var result = make([]*record, 0)
... ... @@ -162,13 +162,13 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
Total float64 `json:"total"`
}
var (
beingTime = xtime.BeginningOfDay().AddDate(0, 0, -5)
endTime = xtime.BeginningOfDay().AddDate(0, 0, 1)
beingTime = xtime.BeginningOfDay().AddDate(0, 0, -6)
endTime = xtime.BeginningOfDay().AddDate(0, 0, 1).Add(-time.Second)
)
//if !xtime.IsZero(time.Time(request.Date)) {
// beingTime = request.Date.Time().AddDate(0, 0, -5)
// endTime = request.Date.Time().AddDate(0, 0, 1)
//}
if !xtime.IsZero(time.Time(request.Date)) {
beingTime = request.Date.Time().AddDate(0, 0, -6)
endTime = request.Date.Time().AddDate(0, 0, 1).Add(-time.Second)
}
workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
if err != nil || workshop == nil {
return nil, nil
... ...
... ... @@ -215,6 +215,34 @@ func (ptr *PGMaterialService) AllMaterialGroupParent(opt *domain.OperateInfo, pr
return result, listId, err
}
func (ptr *PGMaterialService) AllMaterialGroupParentByBacktracking(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
pid = productMaterialGroupId
mapExists = make(map[int]int)
)
var result = make([]*domain.ProductMaterialGroup, 0)
for {
if pid == 0 {
break
}
if _, exists := mapExists[pid]; exists {
break
}
mapExists[pid] = pid
productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": pid, "allWithDeleted": "1"})
if err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
pid = productMaterialGroup.Pid
result = append([]*domain.ProductMaterialGroup{productMaterialGroup}, result...)
}
return result, listId, err
}
func NewPGMaterialService(transactionContext *pgTransaction.TransactionContext) (*PGMaterialService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -180,7 +180,31 @@ func (ptr *PGProductRecordService) Approve(productRecordId int, approveUserId in
return struct{}{}, nil
}
func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, approveUserId int, weight float64, status int) (interface{}, error) {
// Approve 审核生产记录 (二级品审核)
func (ptr *PGProductRecordService) Cancel(productRecordId int) (interface{}, error) {
productRecordRepository, err := repository.NewProductRecordRepository(ptr.transactionContext)
var productRecord *domain.ProductRecord
productRecord, err = productRecordRepository.FindOne(map[string]interface{}{"productRecordId": productRecordId})
if err != nil {
return nil, err
}
if err = productRecord.Cancel(); err != nil {
return nil, err
}
if _, err = productRecordRepository.Save(productRecord); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// 发送Job
productRecord.ProductRecordInfo.Weigh = -productRecord.ProductRecordInfo.Weigh
if err = SendProductRecordStaticsJob(productRecord); err != nil {
return nil, err
}
return struct{}{}, nil
}
func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, approveUserId int, weightAfter float64, status int) (interface{}, error) {
var productRecordRepository, _ = repository.NewProductRecordRepository(ptr.transactionContext)
var record *domain.ProductRecord
var err error
... ... @@ -196,26 +220,19 @@ func (ptr *PGProductRecordService) BatchApprove(list []*domain.ProductRecord, ap
for i := range list {
record = list[i]
t := record.ProductRecordInfo.WeighBefore
if weight > 0 {
t = weight
weighBefore := record.ProductRecordInfo.WeighBefore
if weightAfter > 0 {
weighBefore = weightAfter
}
if t <= 0 && status == domain.AttendanceAutoApproved {
if weighBefore <= 0 || record.ProductRecordInfo.ApproveStatus != domain.ProductRecordNotApprove {
continue
}
if err = record.Approve(user, t, time.Now(), status); err != nil {
if err = record.Approve(user, weighBefore, time.Now(), status); err != nil {
return nil, err
}
if _, err := productRecordRepository.Save(record); err != nil {
return nil, err
}
}
for i := range list {
record = list[i]
if record.ProductRecordInfo.WeighBefore <= 0 && status == domain.AttendanceAutoApproved {
continue
}
if e := SendProductRecordStaticsJob(record); e != nil {
log.Logger.Error("【发送产量统计任务失败】" + e.Error())
}
... ...
... ... @@ -11,7 +11,7 @@ import (
)
const (
ProductSection1 = "打料"
ProductSection1 = "制模" //打料更新为制模
ProductSection2 = "成型"
ProductSection3 = "穿串"
ProductSection4 = "包装"
... ... @@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext)
workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt)
if err == domain.ErrorNotFound {
workshopProductRecord = newWorkshopProductRecord(productRecord, productPlan)
workshopProductRecord = NewWorkshopProductRecord(productRecord, productPlan)
} else {
if err != nil {
log.Logger.Error(err.Error())
... ... @@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original))
workshopProductRecord.UpdateProductWeigh(productRecord)
// 打料 跟 成型工段的初始产能是批次的产能
if productRecord.WorkStation.SectionName == ProductSection1 && productRecord.WorkStation.SectionName == ProductSection2 {
workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
}
//if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
// workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
//}
if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
// TODO:异常处理
... ... @@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
return nil, nil
}
// newEmployeeProductRecord 员工生产记录
func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
// NewWorkshopProductRecord 车间生产记录
func NewWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
record := &domain.WorkshopProductRecord{
CompanyId: productRecord.CompanyId,
OrgId: productRecord.OrgId,
... ... @@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *
}
// 打料、成型有初始值
if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
record.ProductWeigh = productPlan.PlanDevoted.Weight
record.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
}
return record
}
... ...
... ... @@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d
// 封箱机、串串机需要定位到批次
if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi ||
datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local)
if plan, err = ptr.findDeviceProductPlan(companyId, orgId, workStation.WorkStationId, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
if plan, err = ptr.findProductPlanAndActive(companyId, orgId, workStation, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType})
} else {
planId = plan.PlanDispatchRecordExt.ProductPlanId
... ... @@ -161,7 +161,7 @@ func (ptr *PGWorkshopDataConsumeService) newDeviceRunningData(record *domain.Dev
}
data.Temp1 = utils.Truncate(deviceYouZhaJi.FrontTemp, 1)
data.Temp2 = utils.Truncate(deviceYouZhaJi.BackTemp, 1)
data.Alarm = deviceYouZhaJi.Alarm
//data.Alarm = deviceYouZhaJi.Alarm
} else {
deviceYouZhaJi := &domain.DeviceYouZhaJi2{}
err = json.Unmarshal(mBytes, deviceYouZhaJi)
... ... @@ -170,7 +170,7 @@ func (ptr *PGWorkshopDataConsumeService) newDeviceRunningData(record *domain.Dev
}
data.Temp1 = utils.Truncate(deviceYouZhaJi.Temp1, 1)
data.Temp2 = utils.Truncate(deviceYouZhaJi.Temp2, 1)
data.Alarm = deviceYouZhaJi.Alarm
//data.Alarm = deviceYouZhaJi.Alarm
}
break
//串串机
... ... @@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId,
}
// 查找设备的生产计划,如果计划没有上线的话将他上线
func (ptr *PGWorkshopDataConsumeService) findDeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
func (ptr *PGWorkshopDataConsumeService) findProductPlanAndActive(companyId, orgId int, workStation *domain.WorkStation, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext)
planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext)
var setPlanOnline = false
record, err := planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOnline)
record, err := planDispatchRecordDao.ProductPlanDispatchRecord(companyId, orgId, workStation.WorkStationId, date, productCode, 0)
// 未找到当前工段的调度计划,从计划管理查询是否有匹配记录,如果有在调度计划中上线
var productPlan *domain.ProductPlan
if err == domain.ErrorNotFound {
if record, err = planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOffline); err != nil {
if productPlan, err = planDispatchRecordDao.ProductPlan(companyId, orgId, workStation.WorkshopId, date, productCode); err == nil && productPlan != nil {
var productPlanDispatch = domain.NewProductPlanDispatchRecord(productPlan, workStation)
if productPlanDispatch, err = planDispatchRecordRepository.Save(productPlanDispatch); err != nil {
return nil, err
}
return productPlanDispatch, nil
}
return nil, err
} else {
setPlanOnline = true
}
if err != nil {
return nil, err
}
if record != nil && record.PlanDispatchStatus == domain.PlanOffline {
if err = record.ChangeStatus(domain.PlanOnline); err != nil {
return nil, err
}
if setPlanOnline {
record.ChangeStatus(domain.PlanOnline)
if record, err = planDispatchRecordRepository.Save(record); err != nil {
return nil, err
}
... ...
... ... @@ -6,6 +6,17 @@ import (
)
func TransformToDeviceCollectionDomainModelFromPgModels(deviceCollectionModel *models.DeviceCollection) (*domain.DeviceCollection, error) {
if deviceCollectionModel.DeviceType == domain.DeviceTypeYouZhaJi {
if tmp, ok := deviceCollectionModel.Values["Temp1"]; ok {
deviceCollectionModel.Values["FrontTemp"] = tmp
}
if tmp, ok := deviceCollectionModel.Values["Temp2"]; ok {
deviceCollectionModel.Values["TankTemp"] = tmp
}
if tmp, ok := deviceCollectionModel.Values["Temp3"]; ok {
deviceCollectionModel.Values["BackTemp"] = tmp
}
}
return &domain.DeviceCollection{
DeviceCollectionId: deviceCollectionModel.DeviceCollectionId,
WorkShopName: deviceCollectionModel.WorkShopName,
... ...
... ... @@ -130,6 +130,7 @@ func (repository *ProductGroupRepository) FindOne(queryOptions map[string]interf
query.SetWhereByQueryOption("work_station->>'workStationId'=?", "workStationId")
query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
query.SetWhereByQueryOption("work_station->>'lineId'='?'", "lineId")
query.SetWhereByQueryOption("work_station->>'sectionId'='?'", "sectionId")
if v, ok := queryOptions["includeDeleted"]; ok && v.(bool) {
query.AllWithDeleted()
}
... ...
... ... @@ -120,6 +120,9 @@ func (repository *ProductMaterialGroupRepository) FindOne(queryOptions map[strin
query.SetWhereByQueryOption("product_material_group_id = ?", "productMaterialGroupId")
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("material_group_number = ?", "materialGroupNumber")
if _, ok := queryOptions["allWithDeleted"]; ok {
query.AllWithDeleted()
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
... ...
... ... @@ -164,7 +164,7 @@ func (repository *ProductMaterialRepository) Find(queryOptions map[string]interf
query.Where("material_name like ?", fmt.Sprintf("%%%v%%", v))
}
if v, ok := queryOptions["materialCategory"]; ok && v != "" {
query.Where(fmt.Sprintf(`material_category->>'category' like '%%%v%%'`, v))
query.Where(fmt.Sprintf(`material_category->>'category' = '%v'`, v))
}
if v, ok := queryOptions["materialNumbers"]; ok && len(v.([]string)) > 0 {
query.Where("material_number in (?)", pg.In(v))
... ...
... ... @@ -6,6 +6,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
... ... @@ -147,12 +148,18 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
query.SetWhereByQueryOption("product_record_type & ? >0", "productRecordType")
query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
query.SetWhereByQueryOption("work_station->>'lineId'='?'", "lineId")
query.SetWhereByQueryOption("work_station->>'sectionId'='?'", "sectionId")
if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int)) > 0 {
query.Where(`org_id in (?)`, pg.In(v))
}
if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_worker->>'userName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["productWorkerId"]; ok && v.(int) > 0 {
query.Where(`product_worker->>'userId' = '?'`, v)
}
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`work_station->>'workshopName' like '%%%v%%'`, v))
}
... ... @@ -180,6 +187,15 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
if v, ok := queryOptions["productPlanId"]; ok && v.(int) > 0 {
query.Where(fmt.Sprintf(`product_record_info->>'productPlanId' = '%v'`, v))
}
if v, ok := queryOptions["status"]; ok && v.(int) > 0 {
query.Where(fmt.Sprintf(`product_record_info->>'approveStatus' = '%v'`, v))
}
if v, ok := queryOptions["inStatus"]; ok && len(v.([]int)) > 0 {
query.Where(`product_record_info->>'approveStatus' in (?)`, pg.In(utils.ToArrayString(v.([]int))))
}
if v, ok := queryOptions["lastProductRecordId"]; ok && v.(int) > 0 {
query.Where(`product_record_id < ?`, v)
}
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("product_record_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
... ...
package utils
import (
"github.com/beego/beego/v2/core/config"
"github.com/beego/beego/v2/server/web"
"os"
"strconv"
)
type Configurator interface {
DefaultString(key string, defaultVal string) string
DefaultInt(key string, defaultVal int) int
DefaultInt64(key string, defaultVal int64) int64
DefaultBool(key string, defaultVal bool) bool
DefaultFloat(key string, defaultVal float64) float64
}
// EnvConfigurator read config from env param with default value
type EnvConfigurator struct{}
func (c EnvConfigurator) DefaultString(key string, defaultVal string) string {
if os.Getenv(key) != "" {
return os.Getenv(key)
}
return defaultVal
}
func (c EnvConfigurator) DefaultInt(key string, defaultVal int) int {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.Atoi(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseInt(os.Getenv(key), 10, 64)
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultBool(key string, defaultVal bool) bool {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseBool(os.Getenv(key))
if err != nil {
return defaultVal
}
return v
}
func (c EnvConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
if os.Getenv(key) == "" {
return defaultVal
}
v, err := strconv.ParseFloat(os.Getenv(key), 64)
if err != nil {
return defaultVal
}
return v
}
// BeegoAppConfigurator read config from beego config file with default value
type BeegoAppConfigurator struct {
}
func (c BeegoAppConfigurator) DefaultString(key string, defaultVal string) string {
return web.AppConfig.DefaultString(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt(key string, defaultVal int) int {
return web.AppConfig.DefaultInt(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
return web.AppConfig.DefaultInt64(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultBool(key string, defaultVal bool) bool {
return web.AppConfig.DefaultBool(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
return web.AppConfig.DefaultFloat(key, defaultVal)
}
func NewConfig(adapterName, filename string) Configurator {
config, err := config.NewConfig(adapterName, filename)
if err != nil {
panic(err)
}
return config
}
... ...
package utils
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestEnvConfigurator(t *testing.T) {
os.Setenv("bool", "true")
os.Setenv("hello", "world")
os.Setenv("number", "10")
var config Configurator = EnvConfigurator{}
assert.Equal(t, "world", config.DefaultString("hello", "w"))
assert.Equal(t, "w", config.DefaultString("unknown", "w"))
assert.Equal(t, true, config.DefaultBool("bool", false))
assert.Equal(t, true, config.DefaultBool("unknown", true))
assert.Equal(t, 10, config.DefaultInt("number", 5))
assert.Equal(t, 5, config.DefaultInt("unknown", 5))
assert.Equal(t, int64(10), config.DefaultInt64("number", 5))
assert.Equal(t, int64(5), config.DefaultInt64("unknown", 5))
assert.Equal(t, float64(10), config.DefaultFloat("number", 5))
assert.Equal(t, float64(5), config.DefaultFloat("unknown", 5))
}
... ...
... ... @@ -8,7 +8,10 @@ import (
"github.com/bwmarrin/snowflake"
jsonlib "github.com/linmadan/egglib-go/utils/json"
"github.com/shopspring/decimal"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io"
"io/ioutil"
"reflect"
"strconv"
"strings"
... ... @@ -422,3 +425,21 @@ func Truncate(value float64, places int32) float64 {
rsp, _ := quantity.Float64()
return rsp
}
func Utf8ToGbk(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
d, e := ioutil.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
func GbkToUtf8(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
d, e := ioutil.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
... ...
... ... @@ -3,6 +3,9 @@ package beego
import (
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"net/http"
"net/http/pprof"
"os"
"strconv"
... ... @@ -39,6 +42,22 @@ func init() {
web.BConfig.Listen.HTTPSPort = port
}
}
if constant.PPROF_ON {
web.Handler("/debug/pprof/", http.HandlerFunc(pprof.Index))
web.Handler("/debug/cmdline", http.HandlerFunc(pprof.Cmdline))
web.Handler("/debug/profile", http.HandlerFunc(pprof.Profile))
web.Handler("/debug/symbol", http.HandlerFunc(pprof.Symbol))
web.Handler("/debug/trace", http.HandlerFunc(pprof.Trace))
web.Handler("/debug/allocs", pprof.Handler("allocs"))
web.Handler("/debug/block", pprof.Handler("block"))
web.Handler("/debug/goroutine", pprof.Handler("goroutine"))
web.Handler("/debug/heap", pprof.Handler("heap"))
web.Handler("/debug/mutex", pprof.Handler("mutex"))
web.Handler("/debug/threadcreate", pprof.Handler("threadcreate"))
}
web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
... ...
... ... @@ -154,6 +154,8 @@ func (controller *StatisticsController) TaskHandler() func(ctx *context.Context)
Response(ctx, nil, err)
return
}
case "13":
crontab.AutoInitWorkshopProductRecord(nil)
}
Response(ctx, nil, nil)
}
... ...
package controllers
import (
"fmt"
"github.com/beego/beego/v2/server/web/context"
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/allied-lib/gateway/allied_creation_user"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"strings"
"time"
"unicode/utf8"
)
type DeviceZKTecoController struct {
... ... @@ -21,7 +27,8 @@ func (controller *DeviceZKTecoController) PostCdata() {
data := &domain.DeviceZkTeco{
Sn: sn,
}
if len(bodyList) > 2 {
table := controller.Ctx.Input.Query("table")
if len(bodyList) > 2 && table == "ATTLOG" {
data.UserNo = bodyList[0]
//转成时间格式
mTime, err := time.ParseInLocation("2006-01-02 15:04:05", bodyList[1], time.Local)
... ... @@ -36,6 +43,7 @@ func (controller *DeviceZKTecoController) PostCdata() {
log.Logger.Debug(err.Error() + "data:" + bodyList[1])
}
}
RedirectToUserModule(controller.Ctx, false)
controller.Response(data, nil)
}
... ... @@ -46,9 +54,72 @@ func (controller *DeviceZKTecoController) GetCdata() {
func (controller *DeviceZKTecoController) GetRequest() {
//controller.Ctx.WriteString("C:11:DATA\tQUERY\tUSERINFO\tPIN=10086")
controller.Ctx.WriteString("OK")
//controller.Ctx.WriteString("C:7EceWxtHB6:DATA QUERY USERINFO PIN=3")
//controller.Ctx.WriteString("OK")
RedirectToUserModule(controller.Ctx, true)
}
func (controller *DeviceZKTecoController) Ping() {
controller.Ctx.WriteString("OK")
}
func RedirectToUserModule(ctx *context.Context, useResult bool) {
var svr = allied_creation_user.NewHttpLibAlliedCreationUser(constant.ALLIED_CREATION_USER_HOST)
data := ctx.Input.RequestBody
uri := ctx.Request.URL.Path
sn := ctx.Input.Query("SN")
table := ""
cmd := uri
switch uri {
case "/zkteco/iclock/getrequest": // 获取下行命令
cmd = "getrequest"
case "/zkteco/iclock/cdata": // 上报数据
cmd = "cdata"
table = ctx.Input.Query("table")
case "/zkteco/iclock/devicecmd":
cmd = "devicecmd"
}
content := string(data)
if !utf8.Valid(data) {
utf8Content, _ := utils.GbkToUtf8(data) //ConvertToString(content, "gbk", "utf-8")
content = string(utf8Content)
}
param := allied_creation_user.ReqTerminalReport{
TerminalType: "zkteco",
TerminalId: sn,
Command: cmd,
CompanyId: int64(constant.MANUFACTURE_DEFAULT_COMPANYID),
OrgId: int64(constant.MANUFACTURE_DEFAULT_ORGID),
Table: table,
Content: content,
}
if !useResult {
log.Logger.Debug(fmt.Sprintf("命令透传(sn:%v)-命令:%v 命令(内容):%v 成功", sn, cmd, content))
go func() {
defer func() {
if p := recover(); p != nil {
log.Logger.Error(fmt.Sprintf("%v", p))
}
}()
svr.TerminalReport(param)
}()
return
}
response, err := svr.TerminalReport(param)
if err != nil {
log.Logger.Debug(fmt.Sprintf("命令透传(sn:%v)-命令:%v 命令(内容):%v 应答:%v 错误:%v", sn, cmd, string(data), response.Response, err.Error()))
ctx.WriteString("OK")
return
}
log.Logger.Debug(fmt.Sprintf("命令透传(sn:%v)-命令:%v 命令(内容):%v 应答:%v 成功", sn, cmd, string(data), response.Response))
gbkData, _ := utils.Utf8ToGbk([]byte(response.Response))
ctx.Output.Header("Content-Type", "text/plain;charset=gbk")
ack := string(gbkData)
ctx.WriteString(ack)
}
func (controller *DeviceZKTecoController) DeviceCmd() {
//sn := controller.Ctx.Input.Query("SN")
RedirectToUserModule(controller.Ctx, false)
controller.Ctx.WriteString("OK")
}
... ...
... ... @@ -78,3 +78,11 @@ func (controller *ProductCalendarController) SearchProductCalendar() {
total, data, err := productCalendarService.SearchProductCalendar(ParseOperateInfo(controller.BaseController), cmd)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductCalendarController) GetProductGroupCalendar() {
productCalendarService := service.NewProductCalendarService(nil)
cmd := &query.GetProductGroupCalendarQuery{}
Must(controller.Unmarshal(cmd))
data, err := productCalendarService.GetProductGroupCalendar(cmd)
controller.Response(data, err)
}
... ...
... ... @@ -48,7 +48,8 @@ func (controller *ProductMaterialGroupController) RemoveProductMaterialGroup() {
controller.Unmarshal(removeProductMaterialGroupCommand)
productMaterialGroupId, _ := controller.GetInt(":productMaterialGroupId")
removeProductMaterialGroupCommand.ProductMaterialGroupId = productMaterialGroupId
data, err := productMaterialGroupService.RemoveProductMaterialGroup(removeProductMaterialGroupCommand)
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialGroupService.RemoveProductMaterialGroup(operateInfo, removeProductMaterialGroupCommand)
controller.Response(data, err)
}
... ...
... ... @@ -84,6 +84,26 @@ func (controller *ProductRecordController) SearchProductRecord() {
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductRecordController) History() {
productPlanService := service.NewProductRecordService(nil)
cmd := &query.HistoryProductRecordQuery{}
Must(controller.Unmarshal(cmd))
operateInfo := ParseOperateInfo(controller.BaseController)
//cmd.OrgId = operateInfo.OrgId
cmd.CompanyId = operateInfo.CompanyId
cmd.InOrgIds = operateInfo.OrgIds
total, data, err := productPlanService.HistoryProductRecord(ParseOperateInfo(controller.BaseController), cmd)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductRecordController) CancelProductRecord() {
productRecordService := service.NewProductRecordService(nil)
cmd := &command.CancelProductRecordCommand{}
controller.Unmarshal(cmd)
data, err := productRecordService.CancelProductRecord(cmd)
controller.Response(data, err)
}
func (controller *ProductRecordController) SearchEmployeeProductRecord() {
productPlanService := service.NewProductRecordService(nil)
cmd := &query.SearchEmployeeProductRecordQuery{}
... ...
... ... @@ -86,6 +86,7 @@ func (controller *UnitConversionController) SearchMaterial() {
operateInfo := ParseOperateInfo(controller.BaseController)
cmd.OrgId = operateInfo.OrgId
cmd.CompanyId = operateInfo.CompanyId
cmd.IntelligentWeighingFlag = 1
_, data, err := unitConversionService.SearchMaterial(ParseOperateInfo(controller.BaseController), cmd)
controller.Response(data, err)
}
... ...
... ... @@ -21,4 +21,5 @@ func init() {
web.Router("/zkteco/iclock/cdata", &controllers.DeviceZKTecoController{}, "Get:GetCdata")
web.Router("/zkteco/iclock/getrequest", &controllers.DeviceZKTecoController{}, "Get:GetRequest")
web.Router("/zkteco/iclock/ping", &controllers.DeviceZKTecoController{}, "Get:Ping")
web.Router("/zkteco/iclock/devicecmd", &controllers.DeviceZKTecoController{}, "Post:DeviceCmd")
}
... ...
... ... @@ -14,4 +14,5 @@ func init() {
web.Router("/product-calendars/", &controllers.ProductCalendarController{}, "Get:ListProductCalendar")
web.Router("/product-calendars/search", &controllers.ProductCalendarController{}, "Post:SearchProductCalendar")
web.Router("/product-calendars/product-group-calendar", &controllers.ProductCalendarController{}, "Post:GetProductGroupCalendar")
}
... ...
... ... @@ -14,6 +14,8 @@ func init() {
web.Router("/product-records/approve", &controllers.ProductRecordController{}, "Post:ApproveProductRecord")
web.Router("/product-records/search", &controllers.ProductRecordController{}, "Post:SearchProductRecord")
web.Router("/product-records/second-level-record/search", &controllers.ProductRecordController{}, "Post:SearchProductRecord")
web.Router("/product-records/history", &controllers.ProductRecordController{}, "Post:History")
web.Router("/product-records/cancel", &controllers.ProductRecordController{}, "Post:CancelProductRecord")
web.Router("/product-records/employee-productive/search", &controllers.ProductRecordController{}, "Post:SearchEmployeeProductRecord")
web.Router("/product-records/workshop-productive/search", &controllers.ProductRecordController{}, "Post:SearchWorkshopProductRecord")
}
... ...
... ... @@ -30,13 +30,14 @@ func OnReceiveData(client pahomqtt.Client, message pahomqtt.Message) {
}
if workShop, ok := payload["WorkShop"]; ok {
if t, ok := payload["UpTime"]; ok {
collectionTime, _ = time.ParseInLocation("2006-01-02 - 15:04:05", t.(string), time.Local)
}
if collectionTime.IsZero() {
log.Logger.Error(fmt.Sprintf("采集时间有误:%v ", collectionTime), map[string]interface{}{"data": message})
return
}
//if t, ok := payload["UpTime"]; ok {
// collectionTime, _ = time.ParseInLocation("2006-01-02 - 15:04:05", t.(string), time.Local)
//}
//if collectionTime.IsZero() {
// log.Logger.Error(fmt.Sprintf("采集时间有误:%v ", collectionTime), map[string]interface{}{"data": message})
// return
//}
collectionTime = time.Now()
var mBytes []byte
for key, item := range payload {
if key == "WorkShop" || key == "UpTime" {
... ...