作者 liujunxiong

合并分支 'test' 到 'dev_liujunxiong'

Test



查看合并请求 !11
正在显示 90 个修改的文件 包含 6514 行增加131 行删除
... ... @@ -29,3 +29,5 @@ swagger.json
swagger.yaml
*.log
lastupdate.tmp
allied-creation-manufacture
main_local.go
... ...
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "./main.go",
"buildFlags": "--tags=local"
}
]
}
\ No newline at end of file
... ...
# 生产制造项目说明
- 开发环境服务器地址:http://allied-creation-manufacture-dev.fjmaimaimai.com
- 测试环境服务器地址: http://allied-creation-manufacture-test.fjmaimaimai.com
- 前端调用的地址 http://allied-creation-gateway-dev.fjmaimaimai.com/v1/manufacture
- 前端调用的地址 http://allied-creation-gateway-test.fjmaimaimai.com/v1/manufacture
## 1.数据导入导出模块
### 1.1.Excel导入流程
### 1.1.Excel 导入流程
- 原型说明
... ... @@ -14,7 +20,6 @@
- [导入接口文档地址](https://doc-press.fjmaimaimai.com/team/frontend/plugins/business/import.html)
```
POST/v1/web/file-import
... ... @@ -26,11 +31,10 @@ file 文件
code 对应导入模块的编码
```
- ``对接步骤``以导入公司用户模块为例
- `对接步骤`以导入公司用户模块为例
1.定义接口导入的`code`为`ADMIN_SYSTEM-MANAGE_BASE_USER` 2.根据接口解析导入文件的数据 3.调用基础库解析数据并传到后台
1.定义接口导入的``code``为``ADMIN_SYSTEM-MANAGE_BASE_USER``
2.根据接口解析导入文件的数据
3.调用基础库解析数据并传到后台
```go
// 1.解析列
... ... @@ -80,21 +84,23 @@ result, err := userGateway.UserBatchAdd(allied_creation_user.ReqBatchAddUser{
```
```go
```
### 2.2 Excel导出流程
### 2.2 Excel 导出流程
- 功能原型说明
实现可以自定义选择列进行导出,以及选择导出格式,导出格式有 ``xlsx``\\``csv``,功能如下图所示:
实现可以自定义选择列进行导出,以及选择导出格式,导出格式有 `xlsx`\\`csv`,功能如下图所示:
![](https://timeless-world.oss-cn-shenzhen.aliyuncs.com/opportunity/dev_online/20220225/object/1645789890_JbTa22EtANsD3fm2nJ4aH6FJkHzXaHJB.png)
- 前后端交互说明
``接口定义``
`接口定义`
导出接口
```shell
POST /v1/web/file-export
... ... @@ -130,9 +136,7 @@ GET/v1/web/file-export/fields/:code
- 交互流程
1.前台根据 ``导出列查询接口`` 获取可以导出的列;
2.勾选需要导出的列、文件格式,调用 ``导出接口`` 向后台发起导出数据请求;
1.前台根据 `导出列查询接口` 获取可以导出的列; 2.勾选需要导出的列、文件格式,调用 `导出接口` 向后台发起导出数据请求;
#### 2.2.1 后端导出实现
... ... @@ -148,6 +152,7 @@ type ExcelMaker interface {
```
如下所示
```go
//ExportCooperationUserData 导出共创用户数据
type ExportCooperationUserData struct {
... ...
... ... @@ -2,5 +2,17 @@
-- 表 product_plan
-- 唯一索引 company_id,org_id,batch_number
create unique index idx_product_plan_company_id_org_id_batch_number on manufacture.product_plan using btree (company_id,org_id,batch_number);
CREATE INDEX IF NOT EXISTS idx_files_source_file_id on metadata.files using btree(source_file_id);
CREATE INDEX IF NOT EXISTS idx_tables_company_id_table_type on metadata.tables using btree((context->>'companyId'),table_type);
CREATE INDEX IF NOT EXISTS idx_tables_parent_id on metadata.tables using btree(parent_id);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_log_type_source_id on metadata.logs using btree((context->>'companyId'),log_type,source_id);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_object_name on metadata.logs using btree((context->>'companyId'),object_name);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_object_type on metadata.logs using btree((context->>'companyId'),object_type);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_operation_type on metadata.logs using btree((context->>'companyId'),operation_type);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_content on metadata.logs using btree((context->>'companyId'),content);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_operator_name on metadata.logs using btree((context->>'companyId'),operator_name);
CREATE INDEX IF NOT EXISTS idx_logs_company_id_created_at on metadata.logs using btree((context->>'companyId'),created_at);
CREATE INDEX IF NOT EXISTS idx_mapping_rules_company_id_table_id_file_id on metadata.mapping_rules using btree((context->>'companyId'),table_id,file_id);
\ No newline at end of file
... ...
... ... @@ -2,7 +2,7 @@ apiVersion: v1
kind: Service
metadata:
name: allied-creation-manufacture
namespace: mmm-suplus-test
namespace: mmm-suplus-dev
labels:
k8s-app: allied-creation-manufacture
spec:
... ... @@ -17,7 +17,7 @@ apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: allied-creation-manufacture
namespace: mmm-suplus-test
namespace: mmm-suplus-dev
labels:
k8s-app: allied-creation-manufacture
spec:
... ... @@ -97,29 +97,29 @@ spec:
- name: HTTP_PORT
value: "8082"
- name: SERVICE_ENV
value: "test"
value: "dev"
- 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"
value: "http://allied-creation-gateway-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_USER_HOST
value: "https://allied-creation-user-test.fjmaimaimai.com"
value: "http://allied-creation-user-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_COOPERATION_HOST
value: "https://allied-creation-cooperation-test.fjmaimaimai.com"
value: "http://allied-creation-cooperation-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_BASIC_HOST
value: "https://allied-creation-basic-test.fjmaimaimai.com"
value: "http://allied-creation-basic-dev.fjmaimaimai.com"
- name: ALLIED_CREATION_MANUFACTURE_HOST
value: "http://allied-creation-manufacture-test.fjmaimaimai.com"
value: "http://allied-creation-manufacture-dev.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"
value: "http://suplus-sale-app-gateway-dev.fjmaimaimai.com"
- name: MANUFACTURE_DEFAULT_COMPANYID
value: "23"
value: "1"
- name: MANUFACTURE_DEFAULT_ORGID
value: "487"
value: "1"
- name: MANUFACTURE_DEFAULT_WORKSHOPID
value: "28"
value: "2"
- name: MANUFACTURE_PRODUCT_TYPE
value: "SG,SG"
- name: MQTT_HOST
... ...
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
kubectl -n mmm-suplus-dev get pods | grep -q allied-creation-manufacture
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
kubectl create -f /tmp/dev/allied-creation-manufacture/allied-creation-manufacture.yaml --record
kubectl -n mmm-suplus-dev get svc | grep -q allied-creation-manufacture
if [ "$?" == "0" ];then
echo "project service install success!"
echo "allied-creation-manufacture service install success!"
else
echo "project service install fail!"
echo "allied-creation-manufacture service install fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
kubectl -n mmm-suplus-dev get pods | grep -q allied-creation-manufacture
if [ "$?" == "0" ];then
echo "project deployment install success!"
echo "allied-creation-manufacture deployment install success!"
else
echo "project deployment install fail!"
echo "allied-creation-manufacture deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/project/project.yaml
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
kubectl delete -f /tmp/dev/allied-creation-manufacture/allied-creation-manufacture.yaml
kubectl -n mmm-suplus-dev get svc | grep -q allied-creation-manufacture
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
kubectl -n mmm-suplus-dev get svc | grep -q allied-creation-manufacture
done
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
kubectl -n mmm-suplus-dev get pods | grep -q allied-creation-manufacture
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
kubectl -n mmm-suplus-dev get pods | grep -q allied-creation-manufacture
done
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
kubectl create -f /tmp/dev/allied-creation-manufacture/allied-creation-manufacture.yaml --record
kubectl -n mmm-suplus-dev get svc | grep -q allied-creation-manufacture
if [ "$?" == "0" ];then
echo "project service update success!"
echo "allied-creation-manufacture service update success!"
else
echo "project service update fail!"
echo "allied-creation-manufacture service update fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
kubectl -n mmm-suplus-dev get pods | grep -q allied-creation-manufacture
if [ "$?" == "0" ];then
echo "project deployment update success!"
echo "allied-creation-manufacture deployment update success!"
else
echo "project deployment update fail!"
echo "allied-creation-manufacture deployment update fail!"
fi
fi
\ No newline at end of file
... ...
... ... @@ -120,3 +120,5 @@ spec:
value: "47.97.5.102"
- name: MQTT_PORT
value: "6000"
- name: MQTT_UP
value: "true"
\ No newline at end of file
... ...
//go:build !local
// +build !local
package main
import (
"fmt"
"time"
"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"
... ... @@ -9,7 +14,6 @@ import (
"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"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
... ...
... ... @@ -2,10 +2,11 @@ package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
)
type CreateAttendanceCommand struct {
... ... @@ -14,7 +15,7 @@ type CreateAttendanceCommand struct {
// 考勤类型 1.正常 2.支援
AttendanceType int `cname:"考勤类型" json:"attendanceType,omitempty"`
// 生产班组Id
ProductGroupId int `cname:"生产班组Id" json:"productGroupId,omitempty" valid:"Required"`
// ProductGroupId int `cname:"生产班组Id" json:"productGroupId,omitempty" valid:"Required"`
// 生产工人
ProductWorkerId int `cname:"生产工人" json:"productWorkerId,omitempty" valid:"Required"`
// 车间ID
... ...
package dto
import (
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
)
type AttendanceRecordDto struct {
... ... @@ -63,7 +64,9 @@ func (d *AttendanceRecordDto) LoadDto(m *domain.ProductAttendanceRecord, orgId i
d.WorkTimeAfter = m.WorkTimeAfter
d.AttendanceStatus = m.AttendanceStatus
d.AuthFlag = domain.CheckOrgAuth(orgId, m.OrgId)
if m.Ext != nil {
d.OrgName = m.Ext.OrgName
}
d.ApproveUser = m.ApproveUser()
d.GroupName = m.GroupName()
if m.Ext != nil && m.Ext.AttendanceExt != nil {
... ...
... ... @@ -2,6 +2,8 @@ package service
import (
"fmt"
"time"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/xtime"
... ... @@ -13,12 +15,16 @@ import (
"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/utils"
"time"
)
type AttendanceService struct {
}
func NewAttendanceService(options map[string]interface{}) *AttendanceService {
newAttendanceService := &AttendanceService{}
return newAttendanceService
}
// 审核工时
func (attendanceService *AttendanceService) ApproveAttendance(cmd *command.ApproveAttendanceCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
... ... @@ -99,11 +105,11 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var productGroup *domain.ProductGroup
_, productGroup, err = factory.FastPgProductGroup(transactionContext, cmd.ProductGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
// var productGroup *domain.ProductGroup
// _, productGroup, err = factory.FastPgProductGroup(transactionContext, cmd.ProductGroupId)
// if err != nil {
// return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
// }
//var workTime float64 = 0
//if cmd.WorkTime-cmd.BreakTime > 0 {
... ... @@ -139,8 +145,8 @@ func (attendanceService *AttendanceService) CreateAttendance(operateInfo *domain
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithAttendanceExt(&domain.ProductAttendanceRecordExt{
GroupName: productGroup.GroupName,
ProductGroupId: productGroup.ProductGroupId,
// GroupName: productGroup.GroupName,
// ProductGroupId: productGroup.ProductGroupId,
BreakTime: cmd.BreakTime,
}),
ProductDate: productDate,
... ... @@ -426,8 +432,3 @@ func (attendanceService *AttendanceService) SearchWorkshopWorkTimeStatics(operat
}
return count, result, nil
}
func NewAttendanceService(options map[string]interface{}) *AttendanceService {
newAttendanceService := &AttendanceService{}
return newAttendanceService
}
... ...
... ... @@ -30,7 +30,7 @@ func (attendanceService *AttendanceService) WorkshopWorkTimeRecordStatics(cmd *c
log.Logger.Error(err.Error())
return nil, err
}
//TODO 添加功过统计
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
... ...
... ... @@ -2,9 +2,10 @@ package service
import (
"fmt"
"strings"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
"strings"
"github.com/linmadan/egglib-go/utils/excel"
)
... ... @@ -51,7 +52,7 @@ func (srv ExcelDataService) fieldValueAllEmpty(param map[string]string) bool {
return isAllEmpty
}
//// FileImportTemplate 导入模板
// // FileImportTemplate 导入模板
func (srv ExcelDataService) FileImportTemplate(importDataCommand *command.ImportDataCommand) (interface{}, error) {
var mapTemplate = map[string]string{
//domain.ImportCompanyUser: "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210916/object/1631807485_EaxECeRz23WpzrMZmbwdEPRJ3Pdxpx5X.xlsx",
... ... @@ -59,6 +60,12 @@ func (srv ExcelDataService) FileImportTemplate(importDataCommand *command.Import
//domain.ImportDividendsOrders: "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210927/object/1632743206_NPYTKw6RGhXn4TpYNEQhGGdCkXKXTnxM.xlsx",
//domain.ImportCooperationUser: "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210926/object/1632635345_SbfzmkXjQHhCwPw4MB7zb5EBBtdp2MSE.xlsx",
//domain.ImportDividendsReturnOrders: "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/dev_online/20210927/object/1632743214_rNHm6ZBXZaC5xKTrsE7M4h45MY6n6Ff3.xlsx",
//二级品审核导入
//"ImportProductRecordLevel2": "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/test/20221030/object/1667144411_R3h4nQxxcMJ7ympktMsYBBQ6bAcFC6xj.xlsx",
//工时管理导入
//"ImportAttendance": "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/test/20221030/object/1667144523_w66QpzZTfxsmhbM5mmBrHjpytcydMNs2.xlsx",
//事故管理导入
// "ImportProductTrouble": "https://timeless-world.oss-cn-shenzhen.aliyuncs.com/open-api/test/20221030/object/1667144570_xYKYMrMnXWTyasDPnX2JNXEZHd3rJsWG.xlsx",
}
var url string
var ok bool
... ...
package service
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"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/converter"
)
type importAttendance struct {
ProductDate string `json:"productDate"` //日期
WorkshopName string `json:"workshopName"` //车间名称
LineName string `json:"lineName"` //线别名称
SectionName string `json:"sectionName"` //工位名称
WorkerName string `json:"workerName"` //工人姓名
AttendanceType string `json:"attendanceType"` //考勤类型 正常 支援
SignIn string `json:"signIn"` //上岗时间
SignOut string `json:"signOut"` //离岗时间
BreakTime string `json:"breakTime"` //休息时间
FailReason string `json:"failReason"` //数据校验失败的理由
}
func (data *importAttendance) validField() error {
if len(data.ProductDate) == 0 {
return errors.New("日期未填写。")
}
if len(data.WorkerName) == 0 {
return errors.New("车间名称未填写。")
}
if len(data.LineName) == 0 {
return errors.New("线别名称未填写。")
}
if len(data.SectionName) == 0 {
return errors.New("工位名称未填写。")
}
if len(data.WorkerName) == 0 {
return errors.New("工人姓名未填写。")
}
if len(data.AttendanceType) == 0 {
return errors.New("类型未填写。")
}
if len(data.SignIn) == 0 {
return errors.New("上岗时间未填写。")
}
if len(data.SignOut) == 0 {
return errors.New("下岗时间未填写。")
}
if len(data.BreakTime) == 0 {
return errors.New("休息时间未填写。")
}
return nil
}
// 导入生产计划
func (srv ExcelDataService) ImportDataAttendance(importDataCommand *command.ImportDataCommand) (interface{}, error) {
excelImport := excel.NewExcelImport()
excelImport.RowBegin = 3 //第二行开始读取
excelImport.DataFields = []excel.DataField{
{EnName: "productDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workerName", CnName: "姓名"},
{EnName: "attendanceType", CnName: "类型"},
{EnName: "signIn", CnName: "上岗时间"},
{EnName: "signOut", CnName: "离岗时间"},
{EnName: "breakTime", CnName: "休息时长(小时)"},
}
excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
items := make([]importAttendance, 0)
for _, v := range excelData {
item := importAttendance{
ProductDate: strings.TrimSpace(v["productDate"]),
WorkshopName: strings.TrimSpace(v["workshopName"]),
LineName: strings.TrimSpace(v["lineName"]),
SectionName: strings.TrimSpace(v["sectionName"]),
WorkerName: strings.TrimSpace(v["workerName"]),
AttendanceType: strings.TrimSpace(v["attendanceType"]),
SignIn: strings.TrimSpace(v["signIn"]),
SignOut: strings.TrimSpace(v["signOut"]),
BreakTime: strings.TrimSpace(v["breakTime"]),
FailReason: "",
}
items = append(items, item)
}
failRows, err := srv.BatchAddAttendance(*importDataCommand.Operator, items)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}
// BatchAddAttendance 工时管理,导入工时数据
func (srv ExcelDataService) BatchAddAttendance(operate domain.OperateInfo, param []importAttendance) (
failRows []interface{}, 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()
}()
//获取当前操作人
userSrv := domainService.NewUserService()
// operateUser, err := userSrv.User(operate.UserId)
// if err != nil {
// return nil, application.ThrowError(application.TRANSACTION_ERROR, "查询操作人数据失败。"+err.Error())
// }
//获取当前操作人的组织
var org *domain.Org
org, err = userSrv.Organization(operate.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
//车间数据
//生产班组 数据
productGroupRepo, _ := factory.CreateProductGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, productGroupList, err := productGroupRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间列表
_, workshopList, err := workshopRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "获取车间列表失败"+err.Error())
}
//车间名称+/+工人名 作为键名
workerMap := map[string][]*domain.User{}
for _, v := range productGroupList {
for _, vv := range v.GroupMembers {
k := v.WorkStation.WorkshopName + "/" + vv.UserName
isIn := false
for _, vvv := range workerMap[k] {
if vvv.UserId == vv.UserId {
isIn = true
break
}
}
if !isIn {
workerMap[k] = append(workerMap[k], vv)
}
}
}
//车间名称+/+线别名称+/+工段名称 作为键名
workStationMap := map[string]*domain.WorkStation{}
for _, v := range workshopList {
for _, v2 := range v.ProductLines {
for _, v3 := range v2.ProductSections {
workStationName := strings.Join([]string{
v.WorkshopName, v2.LineName, v3.SectionName,
}, "/")
workStationMap[workStationName] = domain.NewWorkStation(v, v2, v3)
}
}
}
var attendanceList []*domain.ProductAttendanceRecord
nowTime := time.Now()
//检查导入的数据
for i := range param {
//检查字段值
err := param[i].validField()
if err != nil {
param[i].FailReason = err.Error()
failRows = append(failRows, param[i])
continue
}
//检查日期格式
productDate, err := time.ParseInLocation("2006-01-02", param[i].ProductDate, time.Local)
if err != nil {
param[i].FailReason = "日期格式错误,例 2006-01-02。"
failRows = append(failRows, param[i])
continue
}
//检查类型
attendanceType := 0
// 考勤类型 1.正常 2.支援
if param[i].AttendanceType == "支援" {
attendanceType = 1
} else if param[i].AttendanceType == "正常" {
attendanceType = 2
} else {
param[i].FailReason = "类型内容异常。"
failRows = append(failRows, param[i])
continue
}
//检查上岗时间格式
signInStr := fmt.Sprintf("%s %s", param[i].ProductDate, param[i].SignIn)
signIn, err := time.ParseInLocation("2006-01-02 15:04:05", signInStr, time.Local)
if err != nil {
param[i].FailReason = "上岗时间格式错误,例 15:04:05。"
failRows = append(failRows, param[i])
continue
}
//检查离岗时间格式
signOutStr := fmt.Sprintf("%s %s", param[i].ProductDate, param[i].SignOut)
signOut, err := time.ParseInLocation("2006-01-02 15:04:05", signOutStr, time.Local)
if err != nil {
param[i].FailReason = "离岗时间格式错误,例 15:04:05。"
failRows = append(failRows, param[i])
continue
}
//检查员工姓名
var worker *domain.User
workKey := param[i].WorkshopName + "/" + param[i].WorkerName
if u, ok := workerMap[workKey]; ok {
if len(u) > 1 {
param[i].FailReason = "当前车间存在重复的用户名"
failRows = append(failRows, param[i])
continue
}
worker = u[0]
} else {
param[i].FailReason = "当前车间不存在用户" + param[i].WorkerName
failRows = append(failRows, param[i])
continue
}
//检查工位
var workStation *domain.WorkStation
workStationName := param[i].WorkshopName + "/" + param[i].LineName + "/" + param[i].SectionName
if v, ok := workStationMap[workStationName]; ok {
workStation = v
} else {
param[i].FailReason = "车间、线别、工段不存在"
failRows = append(failRows, param[i])
continue
}
//休息时间(小时)
beakTime, err := strconv.ParseFloat(param[i].BreakTime, 64)
if err != nil {
param[i].FailReason = "休息时长填写错误"
failRows = append(failRows, param[i])
continue
}
tempItem := &domain.ProductAttendanceRecord{
ProductAttendanceId: 0,
CompanyId: operate.CompanyId,
OrgId: operate.OrgId,
AttendanceType: attendanceType,
ProductWorker: worker,
WorkStation: workStation,
SignIn: signIn,
SignOut: signOut,
AttendanceStatus: domain.AttendanceAutoApproved, //自动审核
WorkTimeBefore: 0.0,
WorkTimeAfter: 0.0,
CreatedAt: nowTime,
UpdatedAt: nowTime,
DeletedAt: time.Time{},
ProductDate: productDate,
Ext: &domain.Ext{
OrgName: org.OrgName,
DeviceExt: &domain.DeviceExt{},
ProductPlanExt: &domain.ProductPlanExt{},
AttendanceExt: &domain.ProductAttendanceRecordExt{},
},
}
//计算工时
workTime := tempItem.ComputeWorkTime(beakTime)
tempItem.WorkTimeAfter = workTime
tempItem.WorkTimeBefore = workTime
attendanceList = append(attendanceList, tempItem)
}
if len(failRows) > 0 {
return failRows, nil
}
attendanceRepo, _ := factory.CreateProductAttendanceRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
for i := range attendanceList {
_, err = attendanceRepo.Save(attendanceList[i])
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
productRecordCommand "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/command"
productRecordService "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/converter"
)
// ImportProductCapacities 导入产能数据
func (srv ExcelDataService) ImportProductCapacities(importDataCommand *command.ImportDataCommand) (interface{}, error) {
excelImport := excel.NewExcelImport()
excelImport.RowBegin = 3 //第二行开始读取
excelImport.DataFields = []excel.DataField{
{EnName: "recordDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workOn", CnName: "班别"},
{EnName: "workerName", CnName: "姓名"},
{EnName: "batchNumber", CnName: "批次号"},
{EnName: "weigh", CnName: "产量(kg)"},
}
excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
items := make([]productRecordCommand.BatchAddProductCapacitiesCmd, 0, len(excelData))
item := productRecordCommand.BatchAddProductCapacitiesCmd{}
for _, v := range excelData {
item = productRecordCommand.BatchAddProductCapacitiesCmd{
RecordDate: v["recordDate"],
WorkshopName: v["workshopName"],
LineName: v["lineName"],
SectionName: v["sectionName"],
WorkerName: v["workerName"],
BatchNumber: v["batchNumber"],
WorkOn: v["workOn"],
Weigh: v["weigh"],
FailReason: "",
}
items = append(items, item)
}
svr := productRecordService.NewProductRecordService(nil)
failRows, err := svr.BatchAddProductCapacities(importDataCommand.Operator, items)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
productRecordCommand "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/command"
productRecordService "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/converter"
)
// ImportProductRecord 导入二级品生产记录
func (srv ExcelDataService) ImportProductRecord(importDataCommand *command.ImportDataCommand) (interface{}, error) {
excelImport := excel.NewExcelImport()
excelImport.RowBegin = 3 //第二行开始读取
excelImport.DataFields = []excel.DataField{
{EnName: "createdDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workerName", CnName: "姓名"},
{EnName: "batchNumber", CnName: "批次号"},
{EnName: "weigh", CnName: "二级品重量"},
}
excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
items := make([]productRecordCommand.BatchAddProductRecordCommand, 0, len(excelData))
item := productRecordCommand.BatchAddProductRecordCommand{}
for _, v := range excelData {
item = productRecordCommand.BatchAddProductRecordCommand{
CreatedDate: v["createdDate"],
WorkshopName: v["workshopName"],
LineName: v["lineName"],
SectionName: v["sectionName"],
WorkerName: v["workerName"],
BatchNumber: v["batchNumber"],
Weigh: v["weigh"],
FailReason: "",
}
items = append(items, item)
}
svr := productRecordService.NewProductRecordService(nil)
failRows, err := svr.BatchAddProductRecord(importDataCommand.Operator, items)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
productTroubleCommand "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/command"
productTroubleService "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils/converter"
)
// ImportProductTrouble 导入事故记录
func (srv ExcelDataService) ImportProductTrouble(importDataCommand *command.ImportDataCommand) (interface{}, error) {
excelImport := excel.NewExcelImport()
excelImport.RowBegin = 3 //第二行开始读取
excelImport.DataFields = []excel.DataField{
{EnName: "recordDate", CnName: "日期"},
{EnName: "workshopName", CnName: "车间"},
{EnName: "lineName", CnName: "线别"},
{EnName: "sectionName", CnName: "工段"},
{EnName: "workerName", CnName: "姓名"},
{EnName: "typesName", CnName: "事故类型"},
{EnName: "amountLoss", CnName: "损失金额"},
}
excelData, err := converter.OpenImportFileFromIoReader(excelImport, importDataCommand.Reader, importDataCommand.FileExt) //excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
items := make([]productTroubleCommand.BatchAddProductTroubleCommand, 0, len(excelData))
item := productTroubleCommand.BatchAddProductTroubleCommand{}
for _, v := range excelData {
item = productTroubleCommand.BatchAddProductTroubleCommand{
RecordDate: v["recordDate"],
WorkshopName: v["workshopName"],
LineName: v["lineName"],
SectionName: v["sectionName"],
WorkerName: v["workerName"],
AmountLoss: v["amountLoss"],
TypesName: v["typesName"],
FailReason: "",
}
items = append(items, item)
}
svr := productTroubleService.NewProductTroubleService(nil)
failRows, err := svr.BatchAddProductTrouble(importDataCommand.Operator, items)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return srv.importResultWithHeader(excelImport.DataFields, failRows, len(items)), nil
}
... ...
... ... @@ -157,3 +157,35 @@ func CreateProductMaterialRepository(options map[string]interface{}) (domain.Pro
}
return repository.NewProductMaterialRepository(transactionContext)
}
func CreateRewardStandardRepository(options map[string]interface{}) (domain.RewardStandardRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewRewardStandardRepository(transactionContext)
}
func CreateRewardRuleRepository(options map[string]interface{}) (domain.RewardRuleRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewRewardRuleRepository(transactionContext)
}
func CreateProductTroubleRepository(options map[string]interface{}) (domain.ProductTroubleRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewProductTroubleRepository(transactionContext)
}
func CreateRewardSummaryRepository(options map[string]interface{}) (domain.RewardSummaryRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewRewardSummaryRepository(transactionContext)
}
... ...
package command
import "errors"
type BatchAddProductCapacitiesCmd struct {
WorkshopName string `json:"workshopName"` //车间
LineName string `json:"lineName"` //生产线
SectionName string `json:"sectionName"` //工段
WorkerName string `json:"workerName"` //员工
Weigh string `json:"weigh"` //产量重量
BatchNumber string `json:"batchNumber"` //计划 批次号
RecordDate string `json:"recordDate"` //日期 2006-01-02
WorkOn string `json:"workOn"` //上班班次 1:全天 2:白班 4:中班 8:夜班
FailReason string `json:"failReason"`
}
func (data *BatchAddProductCapacitiesCmd) ValidField() error {
if len(data.RecordDate) == 0 {
return errors.New("日期未填写")
}
if len(data.WorkshopName) == 0 {
return errors.New("车间未填写")
}
if len(data.LineName) == 0 {
return errors.New("生产线未填写")
}
if len(data.SectionName) == 0 {
return errors.New("工段未填写")
}
if len(data.WorkerName) == 0 {
return errors.New("姓名未填写")
}
if len(data.BatchNumber) == 0 {
return errors.New("批次未填写")
}
if len(data.Weigh) == 0 {
return errors.New("重量未填写")
}
if len(data.WorkOn) == 0 {
return errors.New("上班班次未填写")
}
return nil
}
... ...
package command
import "errors"
// 批量添加生产记录,二级品
type BatchAddProductRecordCommand struct {
CreatedDate string `json:"createdDate"` // 日期
WorkshopName string `json:"workshopName"` // 车间
LineName string `json:"lineName"` // 生产线
SectionName string `json:"sectionName"` // 工段
WorkerName string `json:"workerName"` // 工人名称
BatchNumber string `json:"batchNumber"` // 批次
Weigh string `json:"weigh"` // 重量
FailReason string `json:"failReason"` // 数据检查失败的原因
}
func (cmd *BatchAddProductRecordCommand) ValidField() error {
if len(cmd.CreatedDate) == 0 {
return errors.New("日期未填写")
}
if len(cmd.WorkshopName) == 0 {
return errors.New("车间未填写")
}
if len(cmd.LineName) == 0 {
return errors.New("生产线未填写")
}
if len(cmd.SectionName) == 0 {
return errors.New("工段未填写")
}
if len(cmd.WorkerName) == 0 {
return errors.New("姓名未填写")
}
if len(cmd.BatchNumber) == 0 {
return errors.New("批次号未填写")
}
if len(cmd.Weigh) == 0 {
return errors.New("重量未填写")
}
return nil
}
... ...
package command
type CreateProductCapacitiesCmd struct {
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId" valid:"Required"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId" valid:"Required"`
// 工段ID
SectionId int `cname:"工段ID" json:"sectionId" valid:"Required"`
//员工
WorkerId []int `cname:"工人ID" json:"workerId" valid:"Required"`
//产量重量
Weigh float64 `cname:"重量" json:"weigh" valid:"Required" `
//计划id
ProductPlanId int `json:"productPlanId"`
//日期
RecordDate string `json:"recordDate"`
//上班班次 1:全天 2:白班 4:中班 8:夜班
WorkOn int `json:"workOn"`
//保存并审核
SaveAndApprove bool `json:"saveAndApprove"`
}
... ...
... ... @@ -9,12 +9,28 @@ import (
)
type CreateProductRecordCommand struct {
// 生产记录ID
ProductRecordId int `cname:"生产记录ID" json:"productRecordId" valid:"Required"`
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId" valid:"Required"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId" valid:"Required"`
// 工段ID
SectionId int `cname:"工段ID" json:"sectionId" valid:"Required"`
WorkerId []int `cname:"工人ID" json:"workerId" valid:"Required"`
//生气计划id
ProductPlanId int `cname:"生气计划id" json:"productPlanId" valid:"Required"`
CreatedDate string `cname:"日期" json:"createdDate" valid:"Required"`
//重量
Weigh float64 `cname:"重量" json:"weigh" valid:"Required" `
//保存并审核
SaveAndApprove bool `json:"saveAndApprove"`
}
func (createProductRecordCommand *CreateProductRecordCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createProductRecordCommand *CreateProductRecordCommand) ValidateCommand() error {
... ...
package command
type SaveProductCapacitiesCmd struct {
//id
ProductRecordId int `json:"productRecordId"`
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId" valid:"Required"`
// 生产线ID
LineId int `cname:"生产线ID" json:"lineId" valid:"Required"`
// 工段ID
SectionId int `cname:"工段ID" json:"sectionId" valid:"Required"`
//员工
WorkerId int `cname:"工人ID" json:"workerId" valid:"Required"`
//产量重量
Weigh float64 `cname:"重量" json:"weigh" valid:"Required" `
//计划id
ProductPlanId int `json:"productPlanId"`
//日期
RecordDate string `json:"recordDate"`
//上班班次 1:全天 2:白班 4:中班 8:夜班
WorkOn int `json:"workOn"`
//保存并审核
SaveAndApprove bool `json:"saveAndApprove"`
}
... ...
package dto
//产能管理-列表
type ProductCapacitiesList struct {
ProductRecordId int `json:"productRecordId"`
WorkshopName string `json:"workshopName"` //车间名称
LineName string `json:"lineName"` //线别名称
SectionName string `json:"sectionName"` //工段
WorkerName string `json:"workerName"` // 用户姓名
EmployeeType int `json:"employeeType"` // 员工类型 1:固定 2:派遣 3.临时
ProductName string `json:"productName"` //品名
WorkerOn int `json:"workerOn"` //班别
ProductWeigh float64 `json:"productWeigh"` // 产能
CreatedAt string `json:"createdAt"` // 创建时间
ApproveStatus int `json:"approveStatus"` //0:未审核 1:已审核 2.自动审核
}
//产能管理-列表-详情
type ProductCapacitiesInfo struct {
ProductRecordId int `json:"id"`
WorkshopId int `json:"workshopId" ` // 车间ID
WorkshopName string `json:"workshopName"` //
LineId int `json:"lineId"` // 生产线ID
LineName string `json:"lineName"` //
SectionId int `json:"sectionId" ` // 工段ID
SectionName string `json:"sectionName"` //
WorkerId int `json:"workerId" ` //员工
WorkerName string `json:"workerName"` //
Weigh float64 `json:"weigh"` //产量重量
ProductPlanId int `json:"productPlanId"` //
BatchNumber string `json:"batchNumber"` //批次号
ProductName string `json:"productName"` //产品名称
ParticipateType int `json:"participateType"` //参与类型 1:正常 2:支援
RecordDate string `json:"recordDate"` //日期
WorkOn int `json:"workOn"` //上班班次 1:全天 2:白班 4:中班 8:夜班
}
... ...
package query
type GetProductCapacitiesQuery struct {
EmployeeProductRecordId int `json:"id"`
}
... ...
package query
type ListProductCapacitiesQuery struct {
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize"`
CompanyId int `json:"companyId"`
OrgId int `json:"orgId"`
WorkshopName string `json:"workshopName"`
LineName string `json:"lineName"`
SectionName string `json:"sectionName"`
ProductBeginTime string `json:"productBeginTime"`
ProductEndTime string `json:"productEndTime"`
WorkerName string `json:"workerName"`
}
... ...
package service
import (
"strconv"
"strings"
"time"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productRecord/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
)
//产能管理
// 产能管理 页面上手动创建员工生产记录
func (productRecordService *ProductRecordService) SaveProductCapacities(operateInfo *domain.OperateInfo, param *command.SaveProductCapacitiesCmd) (map[string]interface{}, 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()
}()
//日期
recordDate, err := time.Parse("2006-01-02", param.RecordDate)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
}
//员工数据
var worker *domain.User
userService := domainService.NewUserService()
worker, err = userService.User(param.WorkerId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取员工错误,"+err.Error())
}
//操作人数据
var user *domain.User
user, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取操作人错误,"+err.Error())
}
//组织数据
var org *domain.Org
org, err = userService.Organization(operateInfo.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
workshop, err := workshopRepo.FindOne(map[string]interface{}{"workshopId": param.WorkshopId})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间数据失败"+err.Error())
}
workstation, err := workshop.FindWorkStation(param.WorkshopId, param.LineId, param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间工段数据失败"+err.Error())
}
//获取生产记录
productPlanRepo, _ := factory.CreateProductPlanRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
planData, err := productPlanRepo.FindOne(map[string]interface{}{
"productPlanId": param.ProductPlanId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取计划任务数据失败"+err.Error())
}
//员工生产记录
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
nowTime := time.Now()
if param.ProductRecordId > 0 {
productRecord, err := productRecordRepo.FindOne(map[string]interface{}{
"productRecordId": param.ProductRecordId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取生产记录数据失败"+err.Error())
}
if productRecord.ProductRecordInfo.ApproveStatus != domain.ProductRecordNotApprove {
return nil, application.ThrowError(application.ARG_ERROR, "生产记录不可再被编辑")
}
}
epRecord := &domain.ProductRecord{
ProductRecordId: param.ProductRecordId,
UpdatedAt: nowTime,
OrgId: operateInfo.OrgId,
CompanyId: operateInfo.CompanyId,
WorkStation: workstation,
ProductWorker: worker,
CreatedAt: recordDate,
Ext: &domain.Ext{
Operator: user,
OrgName: org.OrgName,
},
ProductRecordType: domain.RecordTypeReceiveMaterial,
ProductRecordInfo: &domain.ProductRecordInfo{
WorkOn: param.WorkOn,
ProductDate: param.RecordDate,
Weigh: param.Weigh,
WeighBefore: param.Weigh,
ApproveStatus: domain.ProductRecordNotApprove,
ApproveAt: 0,
ApproveUser: nil,
ProductPlanId: planData.ProductPlanId,
PlanProductName: planData.PlanProductName,
BatchNumber: planData.BatchNumber,
},
}
if param.SaveAndApprove {
epRecord.ProductRecordInfo.ApproveAt = nowTime.Unix()
epRecord.ProductRecordInfo.ApproveStatus = domain.ProductRecordApproved
epRecord.ProductRecordInfo.ApproveUser = user
}
_, err = productRecordRepo.Save(epRecord)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "保存员工生产记录失败"+err.Error())
}
if param.SaveAndApprove {
_ = domainService.SendProductRecordStaticsJob(epRecord)
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"productRecordId": epRecord.ProductRecordId,
}, nil
}
// 产能管理 列表
func (productRecordService *ProductRecordService) ListProductCapacities(operateInfo *domain.OperateInfo, param *query.ListProductCapacitiesQuery) (int64, []dto.ProductCapacitiesList, 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()
}()
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
productBeginTime, _ := time.ParseInLocation("2006-01-02", param.ProductBeginTime, time.Local)
productEndTime, _ := time.ParseInLocation("2006-01-02", param.ProductEndTime, time.Local)
if !productEndTime.IsZero() {
productEndTime.Add((86400 - 1) * time.Second)
}
condition := map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
"userName": param.WorkerName,
"workshopName": param.WorkshopName,
"lineName": param.LineName,
"sectionName": param.SectionName,
"productBeginTime": productBeginTime,
"productEndTime": productEndTime,
}
limit := param.PageSize
offset := param.PageSize * (param.PageNumber - 1)
if limit >= 0 {
condition["limit"] = limit
}
if offset >= 0 {
condition["offset"] = offset
}
count, productRecords, err := productRecordRepo.Find(condition)
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.ProductCapacitiesList, 0)
for _, v := range productRecords {
item := dto.ProductCapacitiesList{
ProductRecordId: v.ProductRecordId,
WorkshopName: v.WorkStation.WorkshopName,
LineName: v.WorkStation.LineName,
SectionName: v.WorkStation.SectionName,
WorkerName: v.ProductWorker.UserName,
EmployeeType: v.ProductWorker.EmployeeType,
ProductName: v.ProductRecordInfo.PlanProductName,
WorkerOn: v.ProductRecordInfo.WorkOn,
ProductWeigh: v.ProductRecordInfo.Weigh,
CreatedAt: v.CreatedAt.Local().Format("2006-01-02"),
ApproveStatus: v.ProductRecordInfo.ApproveStatus,
}
result = append(result, item)
}
return count, result, nil
}
// 产能管理 列表-详情
func (productRecordService *ProductRecordService) GetProductCapacities(operateInfo *domain.OperateInfo, id int) (*dto.ProductCapacitiesInfo, 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()
}()
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
recordData, err := productRecordRepo.FindOne(map[string]interface{}{
"productRecordId": id,
})
if 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())
}
var result = dto.ProductCapacitiesInfo{
ProductRecordId: recordData.ProductRecordId,
WorkshopId: recordData.WorkStation.WorkshopId,
WorkshopName: recordData.WorkStation.WorkshopName,
LineId: recordData.WorkStation.LineId,
LineName: recordData.WorkStation.LineName,
SectionId: recordData.WorkStation.SectionId,
SectionName: recordData.WorkStation.SectionName,
WorkerId: recordData.ProductWorker.UserId,
WorkerName: recordData.ProductWorker.UserName,
Weigh: recordData.ProductRecordInfo.Weigh,
BatchNumber: recordData.ProductRecordInfo.BatchNumber,
ProductName: recordData.ProductRecordInfo.PlanProductName,
ProductPlanId: recordData.ProductRecordInfo.ProductPlanId,
RecordDate: recordData.CreatedAt.Format("2006-01-02"),
WorkOn: recordData.ProductRecordInfo.WorkOn,
}
return &result, nil
}
// 产能管理 列表-删除
func (productRecordService *ProductRecordService) DeleteProductCapacities(operateInfo *domain.OperateInfo, id int) (map[string]interface{}, 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()
}()
eProductRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
recordData, err := eProductRecordRepo.FindOne(map[string]interface{}{
"productRecordId": id,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
_, err = eProductRecordRepo.Remove(recordData)
if 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 map[string]interface{}{
"productRecordId": recordData.ProductRecordId,
}, nil
}
// 产能管理 列表-审核
func (productRecordService *ProductRecordService) ApproveProductCapacities(operateInfo *domain.OperateInfo, id int) (map[string]interface{}, 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()
}()
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
recordData, err := productRecordRepo.FindOne(map[string]interface{}{
"productRecordId": id,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
userService := domainService.NewUserService()
//操作人数据
var user *domain.User
user, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取操作人错误,"+err.Error())
}
err = recordData.Approve(user, recordData.ProductRecordInfo.Weigh, time.Now(), domain.ProductRecordApproved)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
_, err = productRecordRepo.Save(recordData)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "保存数据错误,"+err.Error())
}
_ = domainService.SendProductRecordStaticsJob(recordData)
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"productRecordId": recordData.ProductRecordId,
}, nil
}
// 从excel导入 批量添加
func (srv *ProductRecordService) BatchAddProductCapacities(operate *domain.OperateInfo, dataList []command.BatchAddProductCapacitiesCmd) (
failRows []interface{}, 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()
}()
//获取当前操作人
userSrv := domainService.NewUserService()
operateUser, err := userSrv.User(operate.UserId)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "查询操作人数据失败。"+err.Error())
}
//获取当前操作人的组织
var org *domain.Org
org, err = userSrv.Organization(operate.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
//生产班组 数据
productGroupRepo, _ := factory.CreateProductGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//生产计划数据
productPlanRepo, _ := factory.CreateProductPlanRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, productGroupList, err := productGroupRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间列表
_, workshopList, err := workshopRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "获取车间列表失败"+err.Error())
}
//车间名称+/+工人名 作为键名
workerMap := map[string][]*domain.User{}
for _, v := range productGroupList {
for _, vv := range v.GroupMembers {
k := v.WorkStation.WorkshopName + "/" + vv.UserName
isIn := false
for _, vvv := range workerMap[k] {
if vvv.UserId == vv.UserId {
isIn = true
break
}
}
if !isIn {
workerMap[k] = append(workerMap[k], vv)
}
}
}
//车间名称+/+线别名称+/+工段名称 作为键名
workStationMap := map[string]*domain.WorkStation{}
for _, v := range workshopList {
for _, v2 := range v.ProductLines {
for _, v3 := range v2.ProductSections {
workStationName := strings.Join([]string{
v.WorkshopName, v2.LineName, v3.SectionName,
}, "/")
workStationMap[workStationName] = domain.NewWorkStation(v, v2, v3)
}
}
}
productRecordList := []*domain.ProductRecord{}
nowTime := time.Now()
for i := range dataList {
//检查字段
err = dataList[i].ValidField()
if err != nil {
dataList[i].FailReason = err.Error()
failRows = append(failRows, dataList[i])
continue
}
//检查日期格式
productDate, err := time.ParseInLocation("2006-01-02", dataList[i].RecordDate, time.Local)
if err != nil {
dataList[i].FailReason = "日期格式错误,例 2006-01-02。"
failRows = append(failRows, dataList[i])
continue
}
//检查工位
var workStation *domain.WorkStation
workStationName := dataList[i].WorkshopName + "/" + dataList[i].LineName + "/" + dataList[i].SectionName
if v, ok := workStationMap[workStationName]; ok {
workStation = v
} else {
dataList[i].FailReason = "车间、线别、工段不存在"
failRows = append(failRows, dataList[i])
continue
}
//检查员工姓名
var worker *domain.User
workKey := dataList[i].WorkshopName + "/" + dataList[i].WorkerName
if u, ok := workerMap[workKey]; ok {
if len(u) > 1 {
dataList[i].FailReason = "当前车间存在重复的用户名"
failRows = append(failRows, dataList[i])
continue
}
worker = u[0]
} else {
dataList[i].FailReason = "当前车间不存在用户" + dataList[i].WorkerName
failRows = append(failRows, dataList[i])
continue
}
//二级品重量
weigh, err := strconv.ParseFloat(dataList[i].Weigh, 64)
if err != nil {
dataList[i].FailReason = "重量填写错误"
failRows = append(failRows, dataList[i])
continue
}
//按批次获取生产计划
productPlanData, err := productPlanRepo.FindOne(map[string]interface{}{
"batchNumber": dataList[i].BatchNumber,
"companyId": operate.CompanyId,
})
if err != nil {
dataList[i].FailReason = "批次号不存在"
failRows = append(failRows, dataList[i])
continue
}
//检查上班班次 1:全天 2:白班 4:中班 8:夜班
workerOn := 0
switch dataList[i].WorkOn {
case "全天":
workerOn = 1
case "白班":
workerOn = 2
case "中班":
workerOn = 4
case "夜班":
workerOn = 8
default:
dataList[i].FailReason = "上班班次 填写错误"
failRows = append(failRows, dataList[i])
continue
}
tempItem := &domain.ProductRecord{
ProductRecordId: 0,
CompanyId: operate.CompanyId,
OrgId: operate.OrgId,
ProductRecordType: domain.RecordTypeReceiveMaterial,
ProductWorker: worker,
WorkStation: workStation,
CreatedAt: productDate,
UpdatedAt: nowTime,
DeletedAt: time.Time{},
ProductRecordInfo: &domain.ProductRecordInfo{
ProductDate: productDate.Local().Format("2006-01-02"),
Original: weigh,
Weigh: weigh,
WeighBefore: weigh,
WeighAfter: weigh,
ApproveStatus: domain.ProductRecordAutoApproved,
ApproveAt: nowTime.Unix(),
ApproveUser: operateUser,
UnitConversionId: productPlanData.Ext.ProductPlanExt.ProductId,
ProductPlanId: productPlanData.ProductPlanId,
PlanProductName: productPlanData.PlanProductName,
BatchNumber: productPlanData.BatchNumber,
ProductGroupId: 0,
WorkOn: workerOn,
},
Ext: &domain.Ext{
Operator: operateUser,
OrgName: org.OrgName,
},
PreRecord: &domain.ProductRecord{},
}
productRecordList = append(productRecordList, tempItem)
}
if len(failRows) > 0 {
return failRows, nil
}
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
for i := range productRecordList {
_, err := productRecordRepo.Save(productRecordList[i])
if 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 failRows, nil
}
// 产能管理 页面上手动创建员工生产记录
func (productRecordService *ProductRecordService) CreateProductCapacities(operateInfo *domain.OperateInfo, param *command.CreateProductCapacitiesCmd) (map[string]interface{}, 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()
}()
//日期
recordDate, err := time.Parse("2006-01-02", param.RecordDate)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
}
userService := domainService.NewUserService()
//操作人数据
var user *domain.User
user, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取操作人错误,"+err.Error())
}
//组织数据
var org *domain.Org
org, err = userService.Organization(operateInfo.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
workshop, err := workshopRepo.FindOne(map[string]interface{}{"workshopId": param.WorkshopId})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间数据失败"+err.Error())
}
workstation, err := workshop.FindWorkStation(param.WorkshopId, param.LineId, param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间工段数据失败"+err.Error())
}
//获取生产记录
productPlanRepo, _ := factory.CreateProductPlanRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
planData, err := productPlanRepo.FindOne(map[string]interface{}{
"productPlanId": param.ProductPlanId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取计划任务数据失败"+err.Error())
}
//员工生产记录
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
nowTime := time.Now()
productRecordIds := []int{}
for _, workerId := range param.WorkerId {
//员工数据
worker, err := userService.User(workerId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取员工错误,"+err.Error())
}
epRecord := &domain.ProductRecord{
UpdatedAt: nowTime,
OrgId: operateInfo.OrgId,
CompanyId: operateInfo.CompanyId,
WorkStation: workstation,
ProductWorker: worker,
CreatedAt: recordDate,
Ext: &domain.Ext{
Operator: user,
OrgName: org.OrgName,
},
ProductRecordType: domain.RecordTypeReceiveMaterial,
ProductRecordInfo: &domain.ProductRecordInfo{
WorkOn: param.WorkOn,
ProductDate: param.RecordDate,
Weigh: param.Weigh,
WeighBefore: param.Weigh,
ApproveStatus: domain.ProductRecordNotApprove,
ApproveAt: 0,
ApproveUser: nil,
ProductPlanId: planData.ProductPlanId,
PlanProductName: planData.PlanProductName,
BatchNumber: planData.BatchNumber,
},
}
if param.SaveAndApprove {
epRecord.ProductRecordInfo.ApproveAt = nowTime.Unix()
epRecord.ProductRecordInfo.ApproveStatus = domain.ProductRecordApproved
epRecord.ProductRecordInfo.ApproveUser = user
}
_, err = productRecordRepo.Save(epRecord)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "保存员工生产记录失败"+err.Error())
}
if param.SaveAndApprove {
_ = domainService.SendProductRecordStaticsJob(epRecord)
}
productRecordIds = append(productRecordIds, epRecord.ProductRecordId)
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"productRecordIds": productRecordIds,
}, nil
}
... ...
... ... @@ -2,6 +2,12 @@ package service
import (
"fmt"
"strconv"
"strings"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
... ... @@ -12,13 +18,17 @@ 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"
"time"
)
// 生产记录服务
type ProductRecordService struct {
}
func NewProductRecordService(options map[string]interface{}) *ProductRecordService {
newProductRecordService := &ProductRecordService{}
return newProductRecordService
}
// 生产记录审核
func (productRecordService *ProductRecordService) ApproveProductRecord(cmd *command.ApproveProductRecordCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
... ... @@ -35,7 +45,7 @@ func (productRecordService *ProductRecordService) ApproveProductRecord(cmd *comm
transactionContext.RollbackTransaction()
}()
svr, err := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
svr, _ := domainService.NewPGProductRecordService(transactionContext.(*pgTransaction.TransactionContext))
if _, err = svr.Approve(cmd.ProductRecordId, cmd.ApproveUserId, cmd.WeighAfter, time.Now()); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
... ... @@ -46,9 +56,9 @@ func (productRecordService *ProductRecordService) ApproveProductRecord(cmd *comm
return struct{}{}, nil
}
// 创建生产记录服务
func (productRecordService *ProductRecordService) CreateProductRecord(createProductRecordCommand *command.CreateProductRecordCommand) (interface{}, error) {
if err := createProductRecordCommand.ValidateCommand(); err != nil {
// 创建生产记录服务,二级品
func (productRecordService *ProductRecordService) CreateProductRecord(operateInfo *domain.OperateInfo, param *command.CreateProductRecordCommand) (interface{}, error) {
if err := param.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
... ... @@ -61,25 +71,100 @@ func (productRecordService *ProductRecordService) CreateProductRecord(createProd
defer func() {
transactionContext.RollbackTransaction()
}()
newProductRecord := &domain.ProductRecord{
ProductRecordId: createProductRecordCommand.ProductRecordId,
//日期
dataTime, err := time.ParseInLocation("2006-01-02", param.CreatedDate, time.Local)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
}
var productRecordRepository domain.ProductRecordRepository
if value, err := factory.CreateProductRecordRepository(map[string]interface{}{
//生产记录存储
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productRecordRepository = value
})
//生产计划
productPlanRepo, _ := factory.CreateProductPlanRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//生产计划数据
productPlanData, err := productPlanRepo.FindOne(map[string]interface{}{
"product_plan_id": param.ProductPlanId,
"company_id": operateInfo.CompanyId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "生产计划id错误,"+err.Error())
}
//用户数据
var user *domain.User
userService := domainService.NewUserService()
user, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取用户错误,"+err.Error())
}
if productRecord, err := productRecordRepository.Save(newProductRecord); err != nil {
var org *domain.Org
org, err = userService.Organization(operateInfo.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
}
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
workshop, err := workshopRepo.FindOne(map[string]interface{}{"workshopId": param.WorkshopId})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间数据失败"+err.Error())
}
workstation, err := workshop.FindWorkStation(param.WorkshopId, param.LineId, param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取车间工段数据失败"+err.Error())
}
productRecordIds := []int{}
for _, workerId := range param.WorkerId {
workerData, err := userService.User(workerId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取员工数据错误,"+err.Error())
}
productRecordData := &domain.ProductRecord{
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
ProductRecordType: domain.RecordTypeSecondLevelWeigh,
ProductWorker: workerData,
WorkStation: workstation,
CreatedAt: dataTime,
UpdatedAt: time.Now(),
ProductRecordInfo: &domain.ProductRecordInfo{
ProductDate: productPlanData.ProductDate.Local().Format("2006-01-02"),
Original: param.Weigh,
Weigh: utils.Round(param.Weigh, 1),
WeighBefore: utils.Round(param.Weigh, 1),
UnitConversionId: 0,
ApproveStatus: domain.ProductRecordNotApprove,
ProductPlanId: productPlanData.ProductPlanId,
BatchNumber: productPlanData.BatchNumber,
PlanProductName: productPlanData.PlanProductName,
ProductGroupId: 0,
WorkOn: productPlanData.WorkOn,
},
Ext: domain.NewExt(org.OrgName),
}
//保存并审核
if param.SaveAndApprove {
productRecordData.Approve(user, param.Weigh, time.Now(), domain.ProductRecordApproved)
}
_, err = productRecordRepo.Save(productRecordData)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "保存生产记录"+err.Error())
}
productRecordIds = append(productRecordIds, productRecordData.ProductRecordId)
if param.SaveAndApprove {
_ = domainService.SendProductRecordStaticsJob(productRecordData)
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productRecord, nil
}
return map[string]interface{}{
"productRecordId": productRecordIds,
}, nil
}
// 返回生产记录服务
... ... @@ -370,7 +455,219 @@ func (productRecordService *ProductRecordService) CancelProductRecord(cmd *comma
return struct{}{}, nil
}
func NewProductRecordService(options map[string]interface{}) *ProductRecordService {
newProductRecordService := &ProductRecordService{}
return newProductRecordService
// BatchAddProductRecord 从文件导入的数据,批量添加生产记录,二级品数据
func (productRecordService *ProductRecordService) BatchAddProductRecord(operate *domain.OperateInfo, param []command.BatchAddProductRecordCommand) (
failRows []interface{}, 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()
}()
//获取当前操作人
userSrv := domainService.NewUserService()
operateUser, err := userSrv.User(operate.UserId)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "查询操作人数据失败。"+err.Error())
}
//获取当前操作人的组织
var org *domain.Org
org, err = userSrv.Organization(operate.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
//生产班组 数据
productGroupRepo, _ := factory.CreateProductGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//生产计划数据
productPlanRepo, _ := factory.CreateProductPlanRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, productGroupList, err := productGroupRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间列表
_, workshopList, err := workshopRepo.Find(map[string]interface{}{
"companyId": operate.CompanyId,
"orgId": operate.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "获取车间列表失败"+err.Error())
}
//车间名称+/+工人名 作为键名
workerMap := map[string][]*domain.User{}
for _, v := range productGroupList {
for _, vv := range v.GroupMembers {
k := v.WorkStation.WorkshopName + "/" + vv.UserName
isIn := false
for _, vvv := range workerMap[k] {
if vvv.UserId == vv.UserId {
isIn = true
break
}
}
if !isIn {
workerMap[k] = append(workerMap[k], vv)
}
}
}
//车间名称+/+线别名称+/+工段名称 作为键名
workStationMap := map[string]*domain.WorkStation{}
for _, v := range workshopList {
for _, v2 := range v.ProductLines {
for _, v3 := range v2.ProductSections {
workStationName := strings.Join([]string{
v.WorkshopName, v2.LineName, v3.SectionName,
}, "/")
workStationMap[workStationName] = domain.NewWorkStation(v, v2, v3)
}
}
}
productRecordList := []*domain.ProductRecord{}
nowTime := time.Now()
for i := range param {
//检查字段
err = param[i].ValidField()
if err != nil {
param[i].FailReason = err.Error()
failRows = append(failRows, param[i])
continue
}
//检查日期格式
productDate, err := time.ParseInLocation("2006-01-02", param[i].CreatedDate, time.Local)
if err != nil {
param[i].FailReason = "日期格式错误,例 2006-01-02。"
failRows = append(failRows, param[i])
continue
}
//检查工位
var workStation *domain.WorkStation
workStationName := param[i].WorkshopName + "/" + param[i].LineName + "/" + param[i].SectionName
if v, ok := workStationMap[workStationName]; ok {
workStation = v
} else {
param[i].FailReason = "车间、线别、工段不存在"
failRows = append(failRows, param[i])
continue
}
// //获取生产班组
// var productGroup *domain.ProductGroup
// if v, ok := productGroupMap[param[i].ProductGroupName]; ok {
// productGroup = v
// } else {
// param[i].FailReason = "班组不存在"
// failRows = append(failRows, param[i])
// continue
// }
//检查员工姓名
var worker *domain.User
workKey := param[i].WorkshopName + "/" + param[i].WorkerName
if u, ok := workerMap[workKey]; ok {
if len(u) > 1 {
param[i].FailReason = "当前车间存在重复的用户名"
failRows = append(failRows, param[i])
continue
}
worker = u[0]
} else {
param[i].FailReason = "当前车间不存在用户" + param[i].WorkerName
failRows = append(failRows, param[i])
continue
}
//二级品重量
weigh, err := strconv.ParseFloat(param[i].Weigh, 64)
if err != nil {
param[i].FailReason = "二级品重量填写错误"
failRows = append(failRows, param[i])
continue
}
//按批次获取生产计划
productPlanData, err := productPlanRepo.FindOne(map[string]interface{}{
"batchNumber": param[i].BatchNumber,
"companyId": operate.CompanyId,
})
if err != nil {
param[i].FailReason = "批次号不存在"
failRows = append(failRows, param[i])
continue
}
tempItem := &domain.ProductRecord{
ProductRecordId: 0,
CompanyId: operate.CompanyId,
OrgId: operate.OrgId,
ProductRecordType: domain.RecordTypeSecondLevelWeigh,
ProductWorker: worker,
WorkStation: workStation,
CreatedAt: productDate,
UpdatedAt: nowTime,
DeletedAt: time.Time{},
ProductRecordInfo: &domain.ProductRecordInfo{
ProductDate: productDate.Local().Format("2006-01-02"),
Original: weigh,
Weigh: weigh,
WeighBefore: weigh,
WeighAfter: weigh,
ApproveStatus: domain.ProductRecordAutoApproved,
ApproveAt: nowTime.Unix(),
ApproveUser: operateUser,
UnitConversionId: productPlanData.Ext.ProductPlanExt.ProductId,
ProductPlanId: productPlanData.ProductPlanId,
PlanProductName: productPlanData.PlanProductName,
BatchNumber: productPlanData.BatchNumber,
ProductGroupId: 0,
WorkOn: productPlanData.WorkOn,
},
Ext: &domain.Ext{
Operator: operateUser,
OrgName: org.OrgName,
},
PreRecord: &domain.ProductRecord{},
}
productRecordList = append(productRecordList, tempItem)
}
if len(failRows) > 0 {
return failRows, nil
}
productRecordRepo, _ := factory.CreateProductRecordRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
for i := range productRecordList {
_, err := productRecordRepo.Save(productRecordList[i])
if 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())
}
for i := range productRecordList {
err = domainService.SendProductRecordStaticsJob(productRecordList[i])
if err != nil {
e := fmt.Sprintf("【发送产量统计任务失败】 ProductRecordId=%d, %s", productRecordList[i].ProductRecordId, err.Error())
log.Logger.Error(e)
return failRows, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
return failRows, nil
}
... ...
package command
import "errors"
type BatchAddProductTroubleCommand struct {
RecordDate string `json:"recordDate"` //事故发生的日期 2006-01-02
WorkshopName string `json:"workshopId"` //车间
LineName string `json:"lineName"` //生产线
SectionName string `json:"sectionId" valid:"Required"` //工段
WorkerName string `json:"workerId"` //员工名字
AmountLoss string `json:"amountLoss"` // 损失的金额
TypesName string `json:"types"` // 事故类型 1 安全事故 ,2 质量事故, 3 金属事故 ,4 非金属事故
FailReason string `json:"failReason"` // 数据检查失败的原因
}
func (c *BatchAddProductTroubleCommand) ValidField() error {
if len(c.RecordDate) == 0 {
return errors.New("日期 必填")
}
if len(c.WorkshopName) == 0 {
return errors.New("车间 必填")
}
if len(c.LineName) == 0 {
return errors.New("生产线 必填")
}
if len(c.SectionName) == 0 {
return errors.New("工段 必填")
}
if len(c.WorkerName) == 0 {
return errors.New("员工名字 必填")
}
if len(c.AmountLoss) == 0 {
return errors.New("损失金额 必填")
}
if len(c.TypesName) == 0 {
return errors.New("事故类型 必填")
}
return nil
}
... ...
package command
//创建事故记录
type CreateProductTroubleCommand struct {
Id int `json:"id"` //id
WorkshopId int `json:"workshopId" valid:"Required"` //车间id
LineId int `json:"lineId" valid:"Required"` //生产线ID
SectionId int `json:"sectionId" valid:"Required"` //工段ID
WorkerId []int `json:"workerId"` //员工id //多选
Remark string `json:"remark"` //备注
AmountLoss float64 `json:"amountLoss"` // 损失的金额
Types string `json:"types"` // 事故类型 1 安全事故 ,2 质量事故, 3 金属事故 ,4 非金属事故
RecordDate string `json:"recordDate"` // 事故发生的日期
SaveAndApprove bool `json:"saveAndApprove"` //保存并审核
}
... ...
package command
//保存事故记录
type SaveProductTroubleCommand struct {
Id int `json:"id"` //id
WorkshopId int `json:"workshopId" valid:"Required"` //车间id
LineId int `json:"lineId" valid:"Required"` //生产线ID
SectionId int `json:"sectionId" valid:"Required"` //工段ID
WorkerId int `json:"workerId"` //员工id
Remark string `json:"remark"` //备注
AmountLoss float64 `json:"amountLoss"` // 损失的金额
Types string `json:"types"` // 事故类型 1 安全事故 ,2 质量事故, 3 金属事故 ,4 非金属事故
RecordDate string `json:"recordDate"` // 事故发生的日期
SaveAndApprove bool `json:"saveAndApprove"` //保存并审核
}
... ...
package dto
type ProductTroubleInfo struct {
Id int `json:"id"` //id
WorkshopId int `json:"workshopId"` //车间id
WorkshopName string `json:"workshopName"` //
LineId int `json:"lineId"` //生产线ID
LineName string `json:"lineName"` //
SectionId int `json:"sectionId"` //工段ID
SectionName string `json:"sectionName"` //
WorkerId int `json:"workerId"` //员工id
WorkerName string `json:"workerName"` //员工名称
Remark string `json:"remark"` //备注
ProductDate string `json:"productDate"` //日期
AmountLoss float64 `json:"amountLoss"` //损失的金额
Types string `json:"types"` //事故类型
}
... ...
package dto
type ProductTroubleList struct {
Id int `json:"id"` //id
WorkshopId int `json:"workshopId"` //车间id
WorkshopName string `json:"workshopName"` //
LineId int `json:"lineId"` //生产线ID
LineName string `json:"lineName"` //
SectionId int `json:"sectionId"` //工段ID
SectionName string `json:"sectionName"` //
Remark string `json:"remark"` //备注
ProductDate string `json:"productDate"` //日期
AmountLoss float64 `json:"amountLoss"` //损失的金额
Types string `json:"types"` //事故类型
WorkerId int `json:"workerId"` //员工
WorkerName string `json:"workerName"` //员工名称
ApproveStatus int `json:"approveStatus"` //审核状态
ApproveStatusName string `json:"approveStatusName"` //审核状态
}
... ...
package dto
type RewardSummaryList struct {
Id int `json:"id"`
RecordDate string `json:"recordDate"` //日期
WorkshopName string `json:"workshopName"` //车间名称
LineName string `json:"lineName"` //线别名称
SectionName string `json:"sectionName"` //工段
WorkerName string `json:"workerName"` //员工名字
Yield string `json:"yield"` //产效
UpToStandard string `json:"upToStandard"` //合格率
Accident1 string `json:"accident1"` //质量事故
Accident2 string `json:"accident2"` //安全事故
Accident3 string `json:"accident3"` //异物事故
SummaryResult string `json:"summaryResult"` //奖惩结果
ResultDesc string `json:"resultDesc"` //产效结果
}
... ...
package query
type GetProductTroubleQuery struct {
// 生产记录ID
Id int `json:"id" valid:"Required"`
}
... ...
package query
type ListProductTrouble struct {
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber"`
// 页数
PageSize int `cname:"页数" json:"pageSize"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName"`
//员工名称
WorkerName string `cname:"员工名称" json:"workerName"`
}
... ...
package query
type ListRewardSummaryQuery struct {
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber"`
// 页数
PageSize int `cname:"页数" json:"pageSize"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName"`
LineName string `cname:"线别名称" json:"lineName"`
BeginDate string `cname:"开始的日期" json:"beginDate"`
EndDate string `cname:"结束的日期" json:"endDate"`
}
... ...
package service
import (
"time"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "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/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
)
//功过看板 展示(员工)
// RewardSummaryPublicNoticeDay 功过看板 日榜
func (srv ProductTroubleService) RewardSummaryPublicNoticeDay(operateInfo *domain.OperateInfo) (map[string]interface{}, 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()
}()
rewardSumaryDao, _ := dao.NewRewardSumaryDao(transactionContext.(*pgTransaction.TransactionContext))
nowTime := time.Now().Format("2006-01-02")
sumaryData, err := rewardSumaryDao.SeachRewardSummaryDay(operateInfo.CompanyId, operateInfo.OrgId, nowTime)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"list": sumaryData,
"recordDay": nowTime,
}
return result, nil
}
// RewardSummaryPublicNoticeYield 功过看板 产效
func (srv ProductTroubleService) RewardSummaryPublicNoticeYield(operateInfo *domain.OperateInfo) (map[string]interface{}, 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()
}()
rewardSumaryDao, _ := dao.NewRewardSumaryDao(transactionContext.(*pgTransaction.TransactionContext))
nowTime := time.Now().Format("2006-01-02")
sumaryData, err := rewardSumaryDao.SeachRewardSummaryYield(operateInfo.CompanyId, operateInfo.OrgId, nowTime)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"list": sumaryData,
}
return result, nil
}
// RewardSummaryPublicNoticeUpToStandard 功过看板 合格率
func (srv ProductTroubleService) RewardSummaryPublicNoticeUpToStandard(operateInfo *domain.OperateInfo) (map[string]interface{}, 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()
}()
rewardSumaryDao, _ := dao.NewRewardSumaryDao(transactionContext.(*pgTransaction.TransactionContext))
nowTime := time.Now().Format("2006-01-02")
sumaryData, err := rewardSumaryDao.SeachRewardUpToStandard(operateInfo.CompanyId, operateInfo.OrgId, nowTime)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"list": sumaryData,
}
return result, nil
}
// RewardSummaryPublicNoticeDay 功过看板 异常
func (srv ProductTroubleService) RewardSummaryPublicNoticeAccident(operateInfo *domain.OperateInfo) (map[string]interface{}, 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()
}()
rewardSumaryDao, _ := dao.NewRewardSumaryDao(transactionContext.(*pgTransaction.TransactionContext))
nowTime := time.Now().Format("2006-01-02")
sumaryData, err := rewardSumaryDao.SeachRewardAccident(operateInfo.CompanyId, operateInfo.OrgId, nowTime)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"list": sumaryData,
}
return result, nil
}
// RewardSummaryPublicNoticeDay 功过看板 月榜
func (srv ProductTroubleService) RewardSummaryPublicNoticeMonth(operateInfo *domain.OperateInfo) (map[string]interface{}, 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()
}()
rewardSumaryDao, _ := dao.NewRewardSumaryDao(transactionContext.(*pgTransaction.TransactionContext))
nowTime := time.Now().Format("2006-01")
sumaryData, err := rewardSumaryDao.SeachRewardSummaryMonth(operateInfo.CompanyId, operateInfo.OrgId, nowTime)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"list": sumaryData,
}
return result, nil
}
... ...
package service
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
)
// 事故管理
type ProductTroubleService struct{}
func NewProductTroubleService(options map[string]interface{}) *ProductTroubleService {
newService := &ProductTroubleService{}
return newService
}
func (srv ProductTroubleService) SaveProductTrouble(operateInfo *domain.OperateInfo, param *command.SaveProductTroubleCommand) (map[string]interface{}, 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()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
workShopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间数据
workShopData, err := workShopRepo.FindOne(map[string]interface{}{
"workshopId": param.WorkshopId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据不能存在"+err.Error())
}
if workShopData.CompanyId != operateInfo.CompanyId {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据填写错误")
}
workStation, err := workShopData.FindWorkStation(param.WorkshopId, param.LineId, param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
recordDate, err := time.ParseInLocation("2006-01-02", param.RecordDate, time.Local)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
}
var workerUser *domain.User
userService := domainService.NewUserService()
workerUser, err = userService.User(param.WorkerId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取员工信息失败,"+err.Error())
}
var troubleData *domain.ProductTrouble
if param.Id > 0 {
troubleData, err = productTroubleRepo.FindOne(map[string]interface{}{
"id": param.Id,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "事故数据填写错误")
}
} else {
troubleData = &domain.ProductTrouble{
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
CreatedAt: time.Now(),
ApproveStatus: domain.TroubleWaitApprove,
}
}
troubleData.AmountLoss = param.AmountLoss
troubleData.ProductWorker = *workerUser
troubleData.RecordDate = recordDate
troubleData.Remark = param.Remark
troubleData.UpdatedAt = time.Now()
troubleData.WorkStation = *workStation
err = troubleData.SetTypes(param.Types)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if param.SaveAndApprove {
var approveUser *domain.User
userService := domainService.NewUserService()
approveUser, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取审核人信息失败,"+err.Error())
}
err = troubleData.Approve(approveUser)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
}
_, err = productTroubleRepo.Save(troubleData)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if param.SaveAndApprove {
summaryServe, _ := domainService.NewPGRewardSummaryStaticService(transactionContext.(*pgTransaction.TransactionContext))
err = summaryServe.CreateRewardSummaryByProductTrouble(troubleData)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "计算功过奖惩明细失败,"+err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"id": troubleData.Id,
}, nil
}
func (srv ProductTroubleService) GetProductTrouble(id int) (*dto.ProductTroubleInfo, 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()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
troubleData, err := productTroubleRepo.FindOne(map[string]interface{}{
"id": id,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "事故数据不存在,"+err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := dto.ProductTroubleInfo{
Id: troubleData.Id,
WorkshopId: troubleData.WorkStation.WorkshopId,
WorkshopName: troubleData.WorkStation.WorkshopName,
LineId: troubleData.WorkStation.LineId,
LineName: troubleData.WorkStation.LineName,
SectionId: troubleData.WorkStation.SectionId,
SectionName: troubleData.WorkStation.SectionName,
Remark: troubleData.Remark,
ProductDate: troubleData.RecordDate.Format("2006-01-02"),
AmountLoss: troubleData.AmountLoss,
Types: string(troubleData.Types),
WorkerId: troubleData.ProductWorker.UserId,
WorkerName: troubleData.ProductWorker.UserName,
}
return &result, nil
}
func (srv ProductTroubleService) DeleteProductTrouble(id int64) error {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
troubleData, err := productTroubleRepo.FindOne(map[string]interface{}{
"id": id,
})
if err != nil {
return application.ThrowError(application.ARG_ERROR, "事故数据不存在,"+err.Error())
}
_, err = productTroubleRepo.Remove(troubleData)
if err != nil {
return application.ThrowError(application.ARG_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil
}
// 审核事故
func (srv ProductTroubleService) ApproveProductTrouble(operateInfo *domain.OperateInfo, id int64) error {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
troubleData, err := productTroubleRepo.FindOne(map[string]interface{}{
"id": id,
})
if err != nil {
return application.ThrowError(application.ARG_ERROR, "事故数据不存在,"+err.Error())
}
var approveUser *domain.User
userService := domainService.NewUserService()
approveUser, err = userService.User(operateInfo.UserId)
if err != nil {
return application.ThrowError(application.ARG_ERROR, "获取审核人信息失败,"+err.Error())
}
err = troubleData.Approve(approveUser)
if err != nil {
return application.ThrowError(application.ARG_ERROR, err.Error())
}
troubleData.UpdatedAt = time.Now()
_, err = productTroubleRepo.Save(troubleData)
if err != nil {
return application.ThrowError(application.ARG_ERROR, err.Error())
}
//汇总奖惩明细
summaryServe, _ := domainService.NewPGRewardSummaryStaticService(transactionContext.(*pgTransaction.TransactionContext))
err = summaryServe.CreateRewardSummaryByProductTrouble(troubleData)
if err != nil {
return application.ThrowError(application.ARG_ERROR, "计算功过奖惩明细失败,"+err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil
}
// ListProductTrouble 事故管理列表
func (srv ProductTroubleService) ListProductTrouble(param *query.ListProductTrouble) (int64, []dto.ProductTroubleList, 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()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
limit := param.PageSize
offset := param.PageSize * (param.PageNumber - 1)
condition := map[string]interface{}{
"limit": limit,
"offset": offset,
"companyId": param.CompanyId,
"orgId": param.OrgId,
}
if len(param.WorkerName) > 0 {
condition["productWorkerName"] = param.WorkerName
}
if len(param.WorkshopName) > 0 {
condition["workshopName"] = param.WorkshopName
}
cnt, troubleDataList, err := productTroubleRepo.Find(condition)
if err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, "事故数据不存在,"+err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := []dto.ProductTroubleList{}
var item dto.ProductTroubleList
for _, v := range troubleDataList {
item = dto.ProductTroubleList{
Id: v.Id,
WorkshopId: v.WorkStation.WorkshopId,
WorkshopName: v.WorkStation.WorkshopName,
LineId: v.WorkStation.LineId,
LineName: v.WorkStation.LineName,
SectionId: v.WorkStation.SectionId,
SectionName: v.WorkStation.SectionName,
Remark: v.Remark,
ProductDate: v.RecordDate.Local().Format("2006-01-02"),
AmountLoss: v.AmountLoss,
Types: v.GetTypesName(),
WorkerId: v.ProductWorker.UserId,
WorkerName: v.ProductWorker.UserName,
ApproveStatus: int(v.ApproveStatus),
ApproveStatusName: v.GetApproveStatusName(),
}
result = append(result, item)
}
return cnt, result, nil
}
// 批量添加事故数据
func (srv ProductTroubleService) BatchAddProductTrouble(operateInfo *domain.OperateInfo, param []command.BatchAddProductTroubleCommand) (failRows []interface{}, 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()
}()
//获取当前操作人
userSrv := domainService.NewUserService()
operateUser, err := userSrv.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "查询操作人数据失败。"+err.Error())
}
//车间数据
workshopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间列表
_, workshopList, err := workshopRepo.Find(map[string]interface{}{
"companyId": operateInfo.CompanyId,
"orgId": operateInfo.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "获取车间列表失败"+err.Error())
}
//生产班组 数据
productGroupRepo, _ := factory.CreateProductGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, productGroupList, err := productGroupRepo.Find(map[string]interface{}{
"companyId": operateInfo.CompanyId,
"orgId": operateInfo.OrgId,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//车间名称+/+工人名 作为键名
workerMap := map[string][]*domain.User{}
//班组名称 作为键名
// productGroupMap := map[string]*domain.ProductGroup{}
for _, v := range productGroupList {
// productGroupMap[v.GroupName] = v
for _, vv := range v.GroupMembers {
k := v.WorkStation.WorkshopName + "/" + vv.UserName
isIn := false
for _, vvv := range workerMap[k] {
if vvv.UserId == vv.UserId {
isIn = true
break
}
}
if !isIn {
workerMap[k] = append(workerMap[k], vv)
}
}
}
//车间名称+/+线别名称+/+工段名称 作为键名
workStationMap := map[string]*domain.WorkStation{}
for _, v := range workshopList {
for _, v2 := range v.ProductLines {
for _, v3 := range v2.ProductSections {
workStationName := strings.Join([]string{
v.WorkshopName, v2.LineName, v3.SectionName,
}, "/")
workStationMap[workStationName] = domain.NewWorkStation(v, v2, v3)
}
}
}
troubleDataList := make([]*domain.ProductTrouble, 0, len(param))
nowTime := time.Now()
for i := range param {
//检查字段
err = param[i].ValidField()
if err != nil {
param[i].FailReason = err.Error()
failRows = append(failRows, param[i])
continue
}
//检查日期格式
recordDate, err := time.ParseInLocation("2006-01-02", param[i].RecordDate, time.Local)
if err != nil {
param[i].FailReason = "日期格式错误,例 2006-01-02。"
failRows = append(failRows, param[i])
continue
}
//检查工位
var workStation *domain.WorkStation
workStationName := param[i].WorkshopName + "/" + param[i].LineName + "/" + param[i].SectionName
if v, ok := workStationMap[workStationName]; ok {
workStation = v
} else {
param[i].FailReason = "车间、线别、工段不存在"
failRows = append(failRows, param[i])
continue
}
//检查员工姓名
var worker *domain.User
workKey := param[i].WorkshopName + "/" + param[i].WorkerName
if u, ok := workerMap[workKey]; ok {
if len(u) > 1 {
param[i].FailReason = "当前车间存在重复的用户名"
failRows = append(failRows, param[i])
continue
}
worker = u[0]
} else {
param[i].FailReason = "当前车间不存在用户" + param[i].WorkerName
failRows = append(failRows, param[i])
continue
}
//损失金额
amountLoss, err := strconv.ParseFloat(param[i].AmountLoss, 64)
if err != nil {
param[i].FailReason = "损失金额填写错误"
failRows = append(failRows, param[i])
continue
}
item := &domain.ProductTrouble{
Id: 0,
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
WorkStation: *workStation,
ProductWorker: *worker,
AmountLoss: amountLoss,
Types: "",
RecordDate: recordDate,
Remark: "",
ApproveStatus: domain.TroubleIsApprove,
ApproveAt: &nowTime,
ApproveUser: operateUser,
CreatedAt: nowTime,
UpdatedAt: nowTime,
DeletedAt: nil,
}
err = item.SetTypes(param[i].TypesName)
if err != nil {
param[i].FailReason = "事故类型填写错误"
failRows = append(failRows, param[i])
continue
}
troubleDataList = append(troubleDataList, item)
}
if len(failRows) > 0 {
return failRows, nil
}
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
summaryServe, _ := domainService.NewPGRewardSummaryStaticService(transactionContext.(*pgTransaction.TransactionContext))
for i := range troubleDataList {
//添加事故数据
_, err = productTroubleRepo.Save(troubleDataList[i])
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
//汇总奖惩明细
err = summaryServe.CreateRewardSummaryByProductTrouble(troubleDataList[i])
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "计算功过奖惩明细失败,"+err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 奖惩汇总数据列表
func (srv ProductTroubleService) ListRewardSummary(param *query.ListRewardSummaryQuery) (int64, []dto.RewardSummaryList, 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()
}()
rewardSummaryRepo, _ := factory.CreateRewardSummaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
limit := param.PageSize
offset := param.PageSize * (param.PageNumber - 1)
condition := map[string]interface{}{
"orgId": param.OrgId,
"companyId": param.CompanyId,
"offset": offset,
"limit": limit,
}
//搜索条件日期
if len(param.BeginDate) > 0 {
beginDate, err := time.ParseInLocation("2006-01-02", param.BeginDate, time.Local)
if err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
} else {
condition["beginDate"] = beginDate
}
}
//搜索条件日期
if len(param.EndDate) > 0 {
endDate, err := time.ParseInLocation("2006-01-02", param.EndDate, time.Local)
if err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
} else {
endDate = endDate.Add((86400 - 1) * time.Second)
condition["endDate"] = endDate
}
}
//搜索条件 车间名称
if len(param.WorkshopName) > 0 {
condition["workshopName"] = param.WorkshopName
}
//搜索条件 线别名称
if len(param.LineName) > 0 {
condition["lineName"] = param.LineName
}
cnt, rewardSummaryList, err := rewardSummaryRepo.Find(condition)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := []dto.RewardSummaryList{}
for _, v := range rewardSummaryList {
item := dto.RewardSummaryList{
Id: v.Id,
RecordDate: v.RecordDate.Local().Format("2006-01-02"),
WorkshopName: v.WorkStation.WorkshopName,
LineName: v.WorkStation.LineName,
SectionName: v.WorkStation.SectionName,
WorkerName: v.Worker.UserName,
Yield: fmt.Sprintf("%.2f", v.Yield),
UpToStandard: fmt.Sprintf("%.2f%%", v.UpToStandard),
Accident1: fmt.Sprintf("%d次%.2f元", v.AccidentNum1, v.AccidentAmount1),
Accident2: fmt.Sprintf("%d次%.2f元", v.AccidentNum2, v.AccidentAmount2),
Accident3: fmt.Sprintf("金属%d次,非金属%d次", v.AccidentNum3, v.AccidentNum4),
SummaryResult: fmt.Sprintf("%v", v.SummaryResult),
ResultDesc: "",
}
if v.SummaryResult == 0 {
item.ResultDesc = "不奖不惩"
} else if v.SummaryResult > 0 {
item.ResultDesc = "奖"
} else {
item.ResultDesc = "惩"
}
result = append(result, item)
}
return cnt, result, nil
}
// 创建事故数据
func (srv ProductTroubleService) CreateProductTrouble(operateInfo *domain.OperateInfo, param *command.CreateProductTroubleCommand) (map[string]interface{}, 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()
}()
productTroubleRepo, _ := factory.CreateProductTroubleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
workShopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间数据
workShopData, err := workShopRepo.FindOne(map[string]interface{}{
"workshopId": param.WorkshopId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据不能存在"+err.Error())
}
if workShopData.CompanyId != operateInfo.CompanyId {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据填写错误")
}
workStation, err := workShopData.FindWorkStation(param.WorkshopId, param.LineId, param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
recordDate, err := time.ParseInLocation("2006-01-02", param.RecordDate, time.Local)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "日期格式错误")
}
var operaterUser *domain.User
userService := domainService.NewUserService()
operaterUser, err = userService.User(operateInfo.UserId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取审核人信息失败,"+err.Error())
}
for _, workerId := range param.WorkerId {
var workerUser *domain.User
workerUser, err = userService.User(workerId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "获取员工信息失败,"+err.Error())
}
var troubleData *domain.ProductTrouble
if param.Id > 0 {
troubleData, err = productTroubleRepo.FindOne(map[string]interface{}{
"id": param.Id,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "事故数据填写错误")
}
} else {
troubleData = &domain.ProductTrouble{
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
CreatedAt: time.Now(),
ApproveStatus: domain.TroubleWaitApprove,
}
}
troubleData.AmountLoss = param.AmountLoss
troubleData.ProductWorker = *workerUser
troubleData.RecordDate = recordDate
troubleData.Remark = param.Remark
troubleData.UpdatedAt = time.Now()
troubleData.WorkStation = *workStation
err = troubleData.SetTypes(param.Types)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
if param.SaveAndApprove {
err = troubleData.Approve(operaterUser)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
}
_, err = productTroubleRepo.Save(troubleData)
if 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 map[string]interface{}{}, nil
}
... ...
package command
type SaveRewardRuleCommand struct {
// RewardTag string `json:"rewardTag"`
RewardNum int `json:"rewardNum"`
RewardAmount string `json:"rewardAmount"`
// FaultTag string `json:"faultTag"`
FaultNum int `json:"faultNum"`
FaultAmount string `json:"faultAmount"`
Remark string `json:"remark"`
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SaveRewardStandardCommand struct {
Id int `json:"id"` //奖惩标准 id
WorkshopId int `json:"workshopId" valid:"Required"` //车间id
LineId int `json:"lineId" valid:"Required"` //生产线ID
SectionId int `json:"sectionId" valid:"Required"` //工段ID
Remark string `json:"remark"` //备注
TargetType int `json:"targetType" valid:"Required"` //指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
TargeVal1 string `json:"targeVal1"` //填写的指标值1
TargeVal2 string `json:"targeVal2"` //填写的指标值2
TargeVal3 string `json:"targeVal3"` //填写的指标值3
TargeVal4 string `json:"targeVal4"` //填写的指标值4
}
func (removeProductCommand *SaveRewardStandardCommand) Valid(validation *validation.Validation) {
}
func (removeProductCommand *SaveRewardStandardCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeProductCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeProductCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
type RewardRuleInfo struct {
RewardNum int `json:"rewardNum"`
RewardAmount string `json:"rewardAmount"`
FaultNum int `json:"faultNum"`
FaultAmount string `json:"faultAmount"`
Remark string `json:"remark"`
}
... ...
package dto
type RewardStandardInfo struct {
Id int `json:"id"` //奖惩标准id
WorkshopId int `json:"workshopId"` //车间id
WorkshopName string `json:"workshopName"` //
LineId int `json:"lineId"` //生产线ID
LineName string `json:"lineName"` //
SectionId int `json:"sectionId"` //工段ID
SectionName string `json:"sectionName"` //
Remark string `json:"remark"` //备注
TargetType int `json:"targetType"` //指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
TargeVal1 string `json:"targeVal1"` //填写的指标值1
TargeVal2 string `json:"targeVal2"` //填写的指标值2
TargeVal3 string `json:"targeVal3"` //填写的指标值3
TargeVal4 string `json:"targeVal4"` //填写的指标值4
}
... ...
package dto
type RewardStandardList struct {
Id int `json:"id"` //奖惩标准id
WorkshopId int `json:"workshopId"` //车间id
WorkshopName string `json:"workshopName"` //车间名称
LineId int `json:"lineId"` //生产线ID
LineName string `json:"lineName"` //生产线名称
SectionId int `json:"sectionId"` //工段ID
SectionName string `json:"sectionName"` //工段名称
Remark string `json:"remark"` //备注
TargetType int `json:"targetType"` //指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
TargetTypeName string `json:"targetTypeName"` //指标类别
TargeReward string `json:"targeReward"` //描述功劳指标
TargeFault string `json:"targeFault"` //描述过失指标
}
... ...
package query
type GetRewardStandard struct {
Id int `json:"id"`
}
... ...
package query
type ListRewardStandard struct {
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber"`
// 页数
PageSize int `cname:"页数" json:"pageSize"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName"`
// 线别名称
LineName string `cname:"线别名称" json:"lineName"`
// 工段名称
SectionName string `cname:"工段名称" json:"sectionName"`
}
... ...
package service
import (
"time"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type RewardStandardService struct{}
func NewRewardStandardService(options map[string]interface{}) *RewardStandardService {
newService := &RewardStandardService{}
return newService
}
// SaveRewardStandard 保存奖惩标准数据
func (srv RewardStandardService) SaveRewardStandard(operateInfo *domain.OperateInfo, param *command.SaveRewardStandardCommand) (*command.SaveRewardStandardCommand, error) {
if err := param.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()
}()
rewardStandardRepo, _ := factory.CreateRewardStandardRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, dataList, err := rewardStandardRepo.Find(map[string]interface{}{
"limit": 1,
"workshopId": param.WorkshopId,
"lineId": param.LineId,
"sectionId": param.SectionId,
"targetType": param.TargetType,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(dataList) > 0 {
if dataList[0].Id != param.Id {
return nil, application.ThrowError(application.BUSINESS_ERROR, "当前指标已存在")
}
}
var rewardStandardData *domain.RewardStandard
if param.Id > 0 {
rewardStandardData, err = rewardStandardRepo.FindOne(map[string]interface{}{
"id": param.Id,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据不存在"+err.Error())
}
if rewardStandardData.CompanyId != operateInfo.CompanyId {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据填写错误")
}
} else {
rewardStandardData = &domain.RewardStandard{
CreatedAt: time.Now(),
}
}
workShopRepo, _ := factory.CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
//获取车间数据
workShopData, err := workShopRepo.FindOne(map[string]interface{}{
"workshopId": param.WorkshopId,
})
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据不能存在"+err.Error())
}
if workShopData.CompanyId != operateInfo.CompanyId {
return nil, application.ThrowError(application.ARG_ERROR, "车间数据填写错误")
}
productLineData, err := workShopData.FindLine(param.LineId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
productSection, err := productLineData.FindSection(param.SectionId)
if err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
rewardStandardData.UpdatedAt = time.Now()
rewardStandardData.ProductSection = *productSection
rewardStandardData.ProductLine = productLineData.SimpleProductLine()
rewardStandardData.Workshop = workShopData.SimpleWorkshop()
rewardStandardData.Remark = param.Remark
rewardStandardData.CompanyId = operateInfo.CompanyId
rewardStandardData.OrgId = operateInfo.OrgId
err = rewardStandardData.UpdateTarge(
param.TargetType,
param.TargeVal1,
param.TargeVal2,
param.TargeVal3,
param.TargeVal4)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
_, err = rewardStandardRepo.Save(rewardStandardData)
if 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())
}
param.Id = rewardStandardData.Id
return param, nil
}
// GetRewardStandard 根据id获取奖惩标准数据
func (srv RewardStandardService) GetRewardStandard(operateInfo *domain.OperateInfo, param *query.GetRewardStandard) (*dto.RewardStandardInfo, 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()
}()
rewardStandardRepo, _ := factory.CreateRewardStandardRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
rewardStandardData, err := rewardStandardRepo.FindOne(map[string]interface{}{
"id": param.Id,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据不存在"+err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if operateInfo.CompanyId != rewardStandardData.CompanyId {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据不存在")
}
result := dto.RewardStandardInfo{
Id: rewardStandardData.Id,
WorkshopId: rewardStandardData.Workshop.WorkshopId,
WorkshopName: rewardStandardData.Workshop.WorkshopName,
LineId: rewardStandardData.ProductLine.LineId,
LineName: rewardStandardData.ProductLine.LineName,
SectionId: rewardStandardData.ProductSection.SectionId,
SectionName: rewardStandardData.ProductSection.SectionName,
Remark: rewardStandardData.Remark,
TargetType: rewardStandardData.TargetType,
TargeVal1: rewardStandardData.TargeVal1,
TargeVal2: rewardStandardData.TargeVal2,
TargeVal3: rewardStandardData.TargeVal3,
TargeVal4: rewardStandardData.TargeVal4,
}
return &result, nil
}
// DeleteRewardStandard 根据id删除奖惩标准
func (srv RewardStandardService) DeleteRewardStandard(operateInfo *domain.OperateInfo, param *query.GetRewardStandard) (*domain.RewardStandard, 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()
}()
rewardStandardRepo, _ := factory.CreateRewardStandardRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
rewardStandardData, err := rewardStandardRepo.FindOne(map[string]interface{}{
"id": param.Id,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据不存在:"+err.Error())
}
if operateInfo.CompanyId != rewardStandardData.CompanyId {
return nil, application.ThrowError(application.BUSINESS_ERROR, "指标数据不存在")
}
_, err = rewardStandardRepo.Remove(rewardStandardData)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "操作指标数据失败"+err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return rewardStandardData, nil
}
// ListRewardStandard 奖惩标准列表
func (srv RewardStandardService) ListRewardStandard(param *query.ListRewardStandard) (int64, []dto.RewardStandardList, 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()
}()
rewardStandardRepo, _ := factory.CreateRewardStandardRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
condition := map[string]interface{}{
"limit": 20,
"offset": 0,
"companyId": param.CompanyId,
}
if param.PageSize > 0 {
condition["limit"] = param.PageSize
}
offset := param.PageSize * (param.PageNumber - 1)
if offset > 0 {
condition["offset"] = offset
}
if len(param.WorkshopName) > 0 {
condition["workshopName"] = param.WorkshopName
}
if len(param.SectionName) > 0 {
condition["sectionName"] = param.SectionName
}
if len(param.LineName) > 0 {
condition["lineName"] = param.LineName
}
cnt, rewardStandardList, err := rewardStandardRepo.Find(condition)
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())
}
listResult := make([]dto.RewardStandardList, 0)
var temp dto.RewardStandardList
for _, v := range rewardStandardList {
temp = dto.RewardStandardList{
Id: v.Id,
WorkshopId: v.Workshop.WorkshopId,
WorkshopName: v.Workshop.WorkshopName,
LineId: v.ProductLine.LineId,
LineName: v.ProductLine.LineName,
SectionId: v.ProductSection.SectionId,
SectionName: v.ProductSection.SectionName,
Remark: v.Remark,
TargetType: v.TargetType,
TargetTypeName: v.TargetTypeName(),
TargeReward: v.ShowTargeReward(),
TargeFault: v.ShowTargeFault(),
}
listResult = append(listResult, temp)
}
return cnt, listResult, nil
}
// SaveRewardRule 保存奖惩规则
func (srv RewardStandardService) SaveRewardRule(operateInfo *domain.OperateInfo, param *command.SaveRewardRuleCommand) (*command.SaveRewardRuleCommand, 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()
}()
rewardRuleRepo, _ := factory.CreateRewardRuleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, ruleList, err := rewardRuleRepo.Find(map[string]interface{}{
"companyId": operateInfo.CompanyId,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var newRewardRule *domain.RewardRule
if len(ruleList) > 0 {
newRewardRule = ruleList[0]
} else {
newRewardRule = &domain.RewardRule{
CreatedAt: time.Now(),
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
FaultTag: ">",
RewardTag: ">",
}
}
newRewardRule.UpdatedAt = time.Now()
newRewardRule.FaultAmount = param.FaultAmount
newRewardRule.FaultNum = param.FaultNum
newRewardRule.RewardAmount = param.RewardAmount
newRewardRule.RewardNum = param.RewardNum
newRewardRule.Remark = param.Remark
_, err = rewardRuleRepo.Save(newRewardRule)
if 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 param, err
}
// GetRewardRule 获取奖惩规则
func (srv RewardStandardService) GetRewardRule(operateInfo *domain.OperateInfo) (*dto.RewardRuleInfo, 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()
}()
rewardRuleRepo, _ := factory.CreateRewardRuleRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
_, ruleList, err := rewardRuleRepo.Find(map[string]interface{}{
"companyId": operateInfo.CompanyId,
})
if 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())
}
var newRewardRule *dto.RewardRuleInfo
if len(ruleList) > 0 {
newRewardRule = &dto.RewardRuleInfo{
RewardNum: ruleList[0].RewardNum,
RewardAmount: ruleList[0].RewardAmount,
FaultNum: ruleList[0].FaultNum,
FaultAmount: ruleList[0].RewardAmount,
Remark: ruleList[0].Remark,
}
} else {
newRewardRule = &dto.RewardRuleInfo{}
}
return newRewardRule, nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
pgTransaction "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/infrastructure/dao"
)
//车间看板(生产)
// 车间描述
func (svr *CommonStatisticsService) WorkshopDesc() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
workshopDesc, err := boardShowData.WorkshopDesc(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
//在岗人数
onDuty, err := boardShowData.OnDutyCount(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := map[string]interface{}{
"lines": workshopDesc.Lines,
"uname": workshopDesc.Uname,
"workon": workshopDesc.Workon,
"workshopName": workshopDesc.WorkshopName,
"onDuty": onDuty,
}
return result, nil
}
// 员工效率排名
func (svr *CommonStatisticsService) EmployeeWorkpieceRatio() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.EmployeeWorkpieceRatio(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
// TimeSectionProductRecord 时段产能
func (svr *CommonStatisticsService) TimeSectionProductRecord() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
// todo
result, err := boardShowData.TimeSectionProductRecord(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
7, 8,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
// TopShow 今日昨日历史最佳
func (svr *CommonStatisticsService) TopShow() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.TopShow(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return result, nil
}
// ProportionOfSecondLevel 二级品占比
func (svr *CommonStatisticsService) ProportionOfSecondLevel() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.ProportionOfSecondLevel(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
// SectionProductInfo 工段生产信息
func (svr *CommonStatisticsService) SectionProductInfo() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.SectionProductInfo(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
// WorkshopPlanCompletionCurrent 当前计划达成率
func (svr *CommonStatisticsService) WorkshopPlanCompletionCurrent() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.WorkshopPlanCompletionCurrent(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"rate": result,
}
return listData, nil
}
// WorkshopPlanCompletion5Day 近5天计划达成率
func (svr *CommonStatisticsService) WorkshopPlanCompletion5Day() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.WorkshopPlanCompletion5Day(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
// 批次产能
func (svr *CommonStatisticsService) ProductPlan() (interface{}, 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()
}()
boardShowData, _ := dao.NewBoardShowDao(transactionContext.(*pgTransaction.TransactionContext))
result, err := boardShowData.ProductPlan(
constant.MANUFACTURE_DEFAULT_COMPANYID,
constant.MANUFACTURE_DEFAULT_ORGID,
constant.MANUFACTURE_DEFAULT_WORKSHOPID,
)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
listData := map[string]interface{}{
"list": result,
}
return listData, nil
}
... ...
... ... @@ -12,6 +12,11 @@ import (
type CommonStatisticsService struct {
}
func NewCommonStatisticsService(options map[string]interface{}) *CommonStatisticsService {
newProductSectionService := &CommonStatisticsService{}
return newProductSectionService
}
// CommonStatisticsService 通用的统计服务
func (svr *CommonStatisticsService) CommonStatisticsService(cmd *query.CommonStatisticsQuery) (interface{}, error) {
if err := cmd.ValidateQuery(); err != nil {
... ... @@ -39,8 +44,3 @@ func (svr *CommonStatisticsService) CommonStatisticsService(cmd *query.CommonSta
}
return response, nil
}
func NewCommonStatisticsService(options map[string]interface{}) *CommonStatisticsService {
newProductSectionService := &CommonStatisticsService{}
return newProductSectionService
}
... ...
... ... @@ -2,10 +2,11 @@ package constant
import (
"fmt"
"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.NewConfig("ini","config/app_test.conf")
var Configurator utils.Configurator = utils.EnvConfigurator{}
var SERVICE_NAME = "allied-creation-manufacture"
... ... @@ -16,13 +17,14 @@ 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"
//天联共创用户模块
var ALLIED_CREATION_USER_HOST = "http://localhost:8081" //"http://allied-creation-user-dev.fjmaimaimai.com"
// 天联共创用户模块
// svar ALLIED_CREATION_USER_HOST = "http://localhost:8081"
var ALLIED_CREATION_USER_HOST = "http://allied-creation-user-test.fjmaimaimai.com"
//天联共创业务模块
// 天联共创业务模块
var ALLIED_CREATION_COOPERATION_HOST = "http://localhost:8082" // "http://allied-creation-cooperation-dev.fjmaimaimai.com"
var MMM_BYTE_BANK_HOST = "http://220.250.41.79:8301"
... ...
... ... @@ -28,7 +28,7 @@ var MQTT_HOST = "47.97.5.102"
var MQTT_PORT = "6000"
var MQTT_USER = "admin"
var MQTT_PASSWORD = "123456"
var MQTT_UP = true
var MQTT_UP = false
func init() {
MQTT_HOST = Configurator.DefaultString("MQTT_HOST", MQTT_HOST)
... ...
... ... @@ -3,11 +3,11 @@
package constant
var POSTGRESQL_DB_NAME = "terms"
var POSTGRESQL_DB_NAME = "allied_creation_test"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "123456"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
var POSTGRESQL_PASSWORD = "eagle1010"
var POSTGRESQL_HOST = "114.55.200.59"
var POSTGRESQL_PORT = "31543"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
var DISABLE_SQL_GENERATE_COMMENT = true
... ...
... ... @@ -3,10 +3,11 @@ package domain
import (
"errors"
"fmt"
"time"
"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"
)
const (
... ... @@ -159,6 +160,9 @@ func (productAttendanceRecord *ProductAttendanceRecord) Approve(approveUser *Use
}
func (productAttendanceRecord *ProductAttendanceRecord) ProductTime() time.Time {
if productAttendanceRecord.Ext == nil {
return time.Time{}
}
attendanceExt := productAttendanceRecord.Ext.AttendanceExt
if attendanceExt != nil && !xtime.IsZero(productAttendanceRecord.ProductDate) {
return productAttendanceRecord.ProductDate
... ... @@ -230,3 +234,12 @@ func (productAttendanceRecord *ProductAttendanceRecord) AttendanceBreakTime(prod
}
return bt
}
// 计算上岗到 离岗之间的工作时间,
// breakTime 休息时间(小时)
func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTime(breakTime float64) float64 {
signIn := roundTime(productAttendanceRecord.SignIn)
signOut := roundTime(productAttendanceRecord.SignOut)
wt := utils.Round(signOut.Sub(signIn).Hours()-breakTime, 2)
return roundWorkTime(wt)
}
... ...
... ... @@ -14,6 +14,12 @@ type ProductLine struct {
Removed int `json:"removed,omitempty"`
}
//输出简化的模型
type SimpleProductLine struct {
LineId int `json:"lineId"` // 生产线ID
LineName string `json:"lineName"` // 生产线名称
}
// 查询生产线
func (productLine *ProductLine) FindSection(sectionId int) (*ProductSection, error) {
for i := range productLine.ProductSections {
... ... @@ -37,3 +43,11 @@ func (productLine *ProductLine) GetProductSections(removed int) []*ProductSectio
}
return result
}
//SimpleProductLine 输出简化的模型
func (productLine *ProductLine) SimpleProductLine() SimpleProductLine {
return SimpleProductLine{
LineId: productLine.LineId,
LineName: productLine.LineName,
}
}
... ...
package domain
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
)
const (
... ...
... ... @@ -7,6 +7,8 @@ type ProductRecordStaticInfo struct {
ProductDate string `json:"productDate"`
// 生产计划ID
ProductPlanId int `json:"productPlanId,omitempty"`
PlanProductCode string `json:"planProductCode"`
// 计划的产品名称
PlanProductName string `json:"planProductName,omitempty"`
// 批号
... ...
package domain
import (
"errors"
"time"
)
// 事故管理数据结构
type ProductTrouble struct {
Id int `json:"id"` // id
CompanyId int `json:"companyId"` // 企业id
OrgId int `json:"orgId"` // 组织ID
WorkStation WorkStation `json:"workStation"` // 工作位置
ProductWorker User `json:"productWorker,omitempty"` // 生产工人
AmountLoss float64 `json:"amountLoss"` // 损失的金额
Types TroubleType `json:"types"` // 事故类型 1 安全事故 ,2 质量事故, 3 金属事故 ,4 非金属事故
RecordDate time.Time `json:"recordDate"` // 事故发生的日期
Remark string `json:"remakr"` // 备注
ApproveStatus ProductTroubleApprove `json:"approveStatus"` // 审核状态 1:未审核 2:已审核 3.自动审核
ApproveAt *time.Time `json:"approveAt"` // 审核时间
ApproveUser *User `json:"approveUser"` // 审核人
CreatedAt time.Time `json:"createdAt,omitempty"` // 创建时间
UpdatedAt time.Time `json:"updatedAt,omitempty"` // 更新时间
DeletedAt *time.Time `json:"deletedAt,omitempty"` // 删除时间
}
// 事故类型
type TroubleType string
// 事故类型 1 安全事故 ,2 质量事故, 3 金属事故 ,4 非金属事故
const (
TroubleType1 TroubleType = "安全事故"
TroubleType2 TroubleType = "质量事故"
TroubleType3 TroubleType = "金属事故"
TroubleType4 TroubleType = "非金属事故"
)
// 事故管理 审核状态
type ProductTroubleApprove int
// 审核状态 1:未审核 2:已审核
const (
TroubleWaitApprove ProductTroubleApprove = 1
TroubleIsApprove ProductTroubleApprove = 2
)
type ProductTroubleRepository interface {
Save(param *ProductTrouble) (*ProductTrouble, error)
Remove(param *ProductTrouble) (*ProductTrouble, error)
FindOne(queryOptions map[string]interface{}) (*ProductTrouble, error)
Find(queryOptions map[string]interface{}) (int64, []*ProductTrouble, error)
}
func (m *ProductTrouble) SetTypes(v string) error {
troubleType := TroubleType(v)
switch troubleType {
case TroubleType1, TroubleType2, TroubleType3, TroubleType4:
m.Types = troubleType
default:
return errors.New("ProductTrouble.Types 值错误")
}
return nil
}
// 审核事故数据
func (m *ProductTrouble) Approve(approveUser *User) error {
nowTime := time.Now()
switch m.ApproveStatus {
case TroubleIsApprove:
return errors.New("事故不需要重复审核")
default:
m.ApproveAt = &nowTime
m.ApproveStatus = TroubleIsApprove
m.ApproveUser = approveUser
}
return nil
}
func (m *ProductTrouble) GetApproveStatusName() string {
switch m.ApproveStatus {
case TroubleWaitApprove:
return "未审核"
case TroubleIsApprove:
return "已审核"
}
return ""
}
func (m *ProductTrouble) GetTypesName() string {
switch m.Types {
case TroubleType1:
return "安全事故"
case TroubleType2:
return "质量事故"
case TroubleType3:
return "金属事故"
case TroubleType4:
return "非金属事故"
}
return ""
}
... ...
package domain
import (
"strconv"
"time"
)
// RewardStandard 奖惩规则
type RewardRule struct {
Id int `json:"id"` //奖惩规则id
CompanyId int `json:"companyId"` //企业id
OrgId int `json:"orgId"` //组织ID
RewardTag string `json:"rewardTag"`
RewardNum int `json:"rewardNum"`
RewardAmount string `json:"rewardAmount"`
FaultTag string `json:"faultTag"`
FaultNum int `json:"faultNum"`
FaultAmount string `json:"faultAmount"`
Remark string `json:"remark"`
CreatedAt time.Time
UpdatedAt time.Time
}
type RewardRuleRepository interface {
Save(param *RewardRule) (*RewardRule, error)
FindOne(queryOptions map[string]interface{}) (*RewardRule, error)
Find(queryOptions map[string]interface{}) (int64, []*RewardRule, error)
}
func (m *RewardRule) ValidRewardTag() bool {
switch m.RewardTag {
case ">":
default:
return false
}
return true
}
func (m *RewardRule) ValidFaultTag() bool {
switch m.FaultTag {
case ">":
default:
return false
}
return true
}
// 计算奖惩 的金额
func (m *RewardRule) SumRewardAmount(rewardNum int, faultNum int) float64 {
result := float64(0)
rewardAmount, _ := strconv.ParseFloat(m.RewardAmount, 64)
faultAmount, _ := strconv.ParseFloat(m.FaultAmount, 64)
if rewardNum > m.RewardNum {
result += rewardAmount
}
if faultNum > m.FaultNum {
result -= faultAmount
}
return result
}
... ...
package domain
import (
"errors"
"fmt"
"strconv"
"time"
)
// RewardStandard 奖惩标准
type RewardStandard struct {
Id int `json:"id"` //奖惩标准id
CompanyId int `json:"companyId"` //企业id
OrgId int `json:"orgId"` //组织ID
Workshop SimpleWorkshop `json:"workshop"` //车间id
ProductLine SimpleProductLine `json:"productLine"` //生产线
ProductSection ProductSection `json:"ProductSection"` //工段
Remark string `json:"remark"` //备注
TargetType int `json:"targetType"` //指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
TargeVal1 string `json:"targeVal1"` //填写的指标值1
TargeVal2 string `json:"targeVal2"` //填写的指标值2
TargeVal3 string `json:"targeVal3"` //填写的指标值3
TargeVal4 string `json:"targeVal4"` //填写的指标值4
CreatedAt time.Time `json:"createdAt"` //创建时间
UpdatedAt time.Time `json:"updatedAt"` //更新时间
DeletedAt *time.Time `json:"-"` //删除时间
}
/*
填写的指标值描述
产效=> 功: 大于等于 x kg/小时;过:小于 x kg/小时
合格率=> 功:大于等于 x% ;过:小于 x%
安全事故 => 功:小于等于 x 次 或者 损失小于等于 x 元;过:大于 x 次 或 损失大于 x 元
质量事故 => 功:小于等于 x 次 或者 损失 小于等于 x 元;过:大于 x 次 或者 损失大于 x 元
异物次数 => 功:发现金属小于等于 x 次 或者 发现非金属小于等于 x 次
过:发现金属大于 x 次 或 发现非金数大于 x 次
*/
type RewardStandardRepository interface {
Save(param *RewardStandard) (*RewardStandard, error)
Remove(param *RewardStandard) (*RewardStandard, error)
FindOne(queryOptions map[string]interface{}) (*RewardStandard, error)
Find(queryOptions map[string]interface{}) (int64, []*RewardStandard, error)
}
// 指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
const (
TargetType1 int = 1
TargetType2 int = 2
TargetType3 int = 3
TargetType4 int = 4
TargetType5 int = 5
)
// UpdateTarge 更新指标内容
func (m *RewardStandard) UpdateTarge(targetType int, targeVal1 string, targeVal2 string, targeVal3 string, targeVal4 string) error {
switch targetType {
case TargetType1, TargetType2:
if len(targeVal1) == 0 || len(targeVal2) == 0 {
return errors.New("功过指标内容不能为空")
}
_, err := strconv.Atoi(targeVal1)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
_, err = strconv.Atoi(targeVal2)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
m.TargetType = targetType
m.TargeVal1 = targeVal1
m.TargeVal2 = targeVal2
m.TargeVal3 = ""
m.TargeVal4 = ""
case TargetType3, TargetType4, TargetType5:
if len(targeVal1) == 0 || len(targeVal2) == 0 || len(targeVal3) == 0 || len(targeVal4) == 0 {
return errors.New("功过指标内容不能为空")
}
_, err := strconv.Atoi(targeVal1)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
_, err = strconv.Atoi(targeVal2)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
_, err = strconv.Atoi(targeVal3)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
_, err = strconv.Atoi(targeVal4)
if err != nil {
return errors.New("功过指标内容需要为整数")
}
m.TargetType = targetType
m.TargeVal1 = targeVal1
m.TargeVal2 = targeVal2
m.TargeVal3 = targeVal3
m.TargeVal4 = targeVal4
default:
return errors.New("指标类型填写错误")
}
return nil
}
// TargetTypeName
func (m *RewardStandard) TargetTypeName() string {
switch m.TargetType {
case TargetType1:
return "产效"
case TargetType2:
return "合格率"
case TargetType3:
return "安全事故"
case TargetType4:
return "质量事故"
case TargetType5:
return "异物次数"
}
return ""
}
// ShowTargeReward 功过指标描述,功劳
func (m *RewardStandard) ShowTargeReward() string {
show := ""
switch m.TargetType {
case TargetType1:
show = fmt.Sprintf(">=%skg/小时", m.TargeVal1)
case TargetType2:
show = fmt.Sprintf(">=%s%%", m.TargeVal1)
case TargetType3:
show = fmt.Sprintf("<=%s次或损失<=%s元", m.TargeVal1, m.TargeVal2)
case TargetType4:
show = fmt.Sprintf("<=%s次或损失<=%s元", m.TargeVal1, m.TargeVal2)
case TargetType5:
show = fmt.Sprintf("金属<=%s次或非金属<=%s", m.TargeVal1, m.TargeVal2)
}
return show
}
// ShowTargeFault 功过指标描述,过失
func (m *RewardStandard) ShowTargeFault() string {
show := ""
switch m.TargetType {
case TargetType1:
show = fmt.Sprintf("<%skg/小时", m.TargeVal2)
case TargetType2:
show = fmt.Sprintf("<%s%%", m.TargeVal2)
case TargetType3:
show = fmt.Sprintf(">%s次或损失>%s元", m.TargeVal3, m.TargeVal4)
case TargetType4:
show = fmt.Sprintf("<=%s次或损失>%s元", m.TargeVal3, m.TargeVal4)
case TargetType5:
show = fmt.Sprintf("金属>%s次或非金属>%s", m.TargeVal3, m.TargeVal4)
}
return show
}
// 判定功过, 指标类别 1:产效
// param1 产效值
// 功过结果 0 无,1 功 ,-1 过;
func (m *RewardStandard) VerdictTargetType1(param1 float64) int {
val1, _ := strconv.ParseFloat(m.TargeVal1, 64)
val2, _ := strconv.ParseFloat(m.TargeVal2, 64)
result := 0
if param1 > val1 {
result = 1
} else if param1 < val2 {
result = -1
}
return result
}
// 判定功过, 指标类别 2:合格率
// param1 合格率
// 功过结果 0 无,1 功 ,-1 过;
func (m *RewardStandard) VerdictTargetType2(param1 float64) int {
val1, _ := strconv.ParseFloat(m.TargeVal1, 64)
val2, _ := strconv.ParseFloat(m.TargeVal2, 64)
result := 0
if param1 > val1 {
result = 1
} else if param1 < val2 {
result = -1
}
return result
}
// 判定功过, 指标类别 3:安全事故;
// param1 安全事故次数;
// param1 损失金额;
// 功过结果 0 无,1 功 ,-1 过;
func (m *RewardStandard) VerdictTargetType3(param1 int, param2 float64) int {
val1, _ := strconv.Atoi(m.TargeVal1)
val2, _ := strconv.ParseFloat(m.TargeVal2, 64)
result := 0
//判定功
if param1 <= val1 {
result = 1
}
if param2 <= val2 {
result = 1
}
//判定过
val3, _ := strconv.Atoi(m.TargeVal3)
val4, _ := strconv.ParseFloat(m.TargeVal4, 64)
if param1 > val3 {
result = -1
}
if param2 > val4 {
result = -1
}
return result
}
// 判定功过, 指标类别 4:质量事故;
// param1 质量事故 次数;
// param1 损失金额;
// 功过结果 0 无,1 功 ,-1 过;
func (m *RewardStandard) VerdictTargetType4(param1 int, param2 float64) int {
val1, _ := strconv.Atoi(m.TargeVal1)
val2, _ := strconv.ParseFloat(m.TargeVal2, 64)
result := 0
//判定功
if param1 <= val1 {
result = 1
}
if param2 <= val2 {
result = 1
}
//判定过
val3, _ := strconv.Atoi(m.TargeVal3)
val4, _ := strconv.ParseFloat(m.TargeVal4, 64)
if param1 > val3 {
result = -1
}
if param2 > val4 {
result = -1
}
return result
}
// 判定功过, 指标类别 5:异物次数;
// param1 金属异物 次数;
// param2 非金属 次数;
// 功过结果 0 无,1 功 ,-1 过;
func (m *RewardStandard) VerdictTargetType5(param1 int, param2 int) int {
val1, _ := strconv.Atoi(m.TargeVal1)
val2, _ := strconv.Atoi(m.TargeVal2)
result := 0
//判定功
if param1 <= val1 {
result = 1
}
if param2 <= val2 {
result = 1
}
//判定过
val3, _ := strconv.Atoi(m.TargeVal3)
val4, _ := strconv.Atoi(m.TargeVal4)
if param1 > val3 {
result = -1
}
if param2 > val4 {
result = -1
}
return result
}
... ...
package domain
import (
"time"
)
// RewardSummary 功过奖惩明细
type RewardSummary struct {
Id int `json:"id"`
CompanyId int `json:"companyId"`
OrgId int `json:"orgId"`
RecordDate time.Time `json:"recordDate"` //日期
RecordDateStr string `json:"recordDateStr"` //
WorkStation WorkStation `json:"workStation"` //工作位置
Worker User `json:"user"` //员工
UpToStandard float64 `json:"upToStandard"` //合格率
UpToStandardResult int `json:"upToStandardResult"` //合格率 功过评定结果 1`功` -1 `过` 0 `不奖不惩`
Yield float64 `json:"yield"` //产能
YieldResult int `json:"yieldResult"` //产能 功过评定结果 1`功` -1 `过` 0 `不奖不惩`
AccidentNum1 int `json:"accidentNum1"` //质量事故 次数
AccidentAmount1 float64 `json:"accidentAmount1"` //质量事故 损失金额
AccidentResult1 int `json:"accidentResult1"` //质量事故 功过评定结果 1`功` -1 `过` 0 `不奖不惩`
AccidentNum2 int `json:"accidentNum2"` //安全事故 次数
AccidentAmount2 float64 `json:"accidentAmount2"` //安全事故 损失金额
AccidentResult2 int `json:"accidentResult2"` //安全事故 功过评定结果 1`功` -1 `过` 0 `不奖不惩`
AccidentNum3 int `json:"accidentNum3"` //异物金属事故 次数
AccidentResult3 int `json:"accidentResult3"` //异物事故 功过评定结果 1`功` -1 `过` 0 `不奖不惩`
AccidentNum4 int `json:"accidentNum4"` //异物非金属事故次数
SummaryResult float64 `json:"summaryResult"` //奖惩金额计算结果(元)
CreatedAt time.Time `json:"createdAt"` //
UpdatedAt time.Time `json:"UpdatedAt"` //
}
type RewardSummaryRepository interface {
Save(param *RewardSummary) (*RewardSummary, error)
FindOne(queryOptions map[string]interface{}) (*RewardSummary, error)
Find(queryOptions map[string]interface{}) (int64, []*RewardSummary, error)
}
// SummaryAccident 汇总事故数据
func (c *RewardSummary) SummaryAccident(trouble *ProductTrouble, rewardStandard *RewardStandard) {
switch trouble.Types {
case TroubleType1:
c.AccidentNum2 = +1
c.AccidentAmount2 = +trouble.AmountLoss
if rewardStandard == nil {
c.AccidentResult2 = 0
} else {
r := rewardStandard.VerdictTargetType3(c.AccidentNum2, c.AccidentAmount2)
c.AccidentResult2 = r
}
case TroubleType2:
c.AccidentNum1 = +1
c.AccidentAmount1 = +trouble.AmountLoss
if rewardStandard == nil {
c.AccidentResult1 = 0
} else {
r := rewardStandard.VerdictTargetType4(c.AccidentNum1, c.AccidentAmount1)
c.AccidentResult2 = r
}
case TroubleType3:
c.AccidentNum3 = +1
if rewardStandard == nil {
c.AccidentResult3 = 0
} else {
r := rewardStandard.VerdictTargetType5(c.AccidentNum3, 0)
c.AccidentResult2 = r
}
case TroubleType4:
c.AccidentNum4 = +1
if rewardStandard != nil {
r := rewardStandard.VerdictTargetType5(0, c.AccidentNum4)
c.AccidentResult2 = r
}
}
}
func (c *RewardSummary) ApplySummaryResult(rule *RewardRule) {
rewardNum := 0
faultNum := 0
if c.AccidentResult1 < 0 {
faultNum = +1
} else if c.AccidentResult1 > 0 {
rewardNum = +1
}
if c.AccidentResult2 < 0 {
faultNum = +1
} else if c.AccidentResult2 > 0 {
rewardNum = +1
}
if c.AccidentResult3 < 0 {
faultNum = +1
} else if c.AccidentResult3 > 0 {
rewardNum = +1
}
if c.YieldResult < 0 {
faultNum = +1
} else if c.YieldResult > 0 {
rewardNum = +1
}
if c.UpToStandardResult < 0 {
faultNum = +1
} else if c.UpToStandardResult > 0 {
rewardNum = +1
}
c.SummaryResult = rule.SumRewardAmount(rewardNum, faultNum)
}
// SummaryYield 汇总产效数据
func (c *RewardSummary) SummaryYield(yield float64, rewardStandard *RewardStandard) {
c.Yield = yield
if rewardStandard == nil {
c.YieldResult = 0
} else {
r := rewardStandard.VerdictTargetType1(c.Yield)
c.YieldResult = r
}
}
// SummaryUpToStandard 汇总合格率数据
func (c *RewardSummary) SummaryUpToStandard(param float64, rewardStandard *RewardStandard) {
c.UpToStandard = param
if rewardStandard == nil {
c.UpToStandard = 0
} else {
r := rewardStandard.VerdictTargetType2(c.Yield)
c.UpToStandardResult = r
}
}
... ...
... ... @@ -39,6 +39,13 @@ type Workshop struct {
Ext *Ext `json:"ext,omitempty"`
}
type SimpleWorkshop struct {
// 车间ID
WorkshopId int `json:"workshopId"`
// 车间名称
WorkshopName string `json:"workshopName"`
}
type WorkshopRepository interface {
Save(workshop *Workshop) (*Workshop, error)
Remove(workshop *Workshop) (*Workshop, error)
... ... @@ -301,3 +308,11 @@ func (workshop *Workshop) CloneSample() *Workshop {
WorkshopName: workshop.WorkshopName,
}
}
//SimpleWorkshop 输出简化的模型
func (workShop *Workshop) SimpleWorkshop() SimpleWorkshop {
return SimpleWorkshop{
WorkshopId: workShop.WorkshopId,
WorkshopName: workShop.WorkshopName,
}
}
... ...
package dao
import (
"fmt"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
//车间看板(生产)的展示数据
type BoardShowDao struct {
transactionContext *pgTransaction.TransactionContext
}
func NewBoardShowDao(transactionContext *pgTransaction.TransactionContext) (*BoardShowDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &BoardShowDao{
transactionContext: transactionContext,
}, nil
}
}
type BoardWorkshopDesc struct {
WorkshopName string `json:"workshopName"`
Uname string `json:"uname"`
Lines string `json:"lines"`
Workon string `json:"workon"`
}
// WorkshopDesc 车间描述
func (d *BoardShowDao) WorkshopDesc(companyId int, orgId int, workshopId int) (*BoardWorkshopDesc, error) {
sqlStr := `with workshop as (
select a.workshop_name,a.uname,a.line->>'lineName' linename from (
select workshop_name,principal->>'userName' uname
, jsonb_array_elements(product_lines) line
from manufacture.workshop where company_id = ?
and org_id = ?
and workshop_id=?
) a
where a.line->>'removed' = '1'
)
select max(workshop_name) workshop_name
,max(uname) uname
,string_agg(linename, '\') lines,
'全天' workon
from workshop`
tx := d.transactionContext.PgTx
var result BoardWorkshopDesc
_, err := tx.QueryOne(&result, sqlStr, companyId, orgId, workshopId)
if err != nil {
return nil, err
}
return &result, nil
}
// 在岗人数
func (d *BoardShowDao) OnDutyCount(companyId int, orgId int, workshopId int) (int, error) {
sqlStr := `select count(distinct product_worker->>'userId') from manufacture.product_attendance_record
where company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and sign_in>to_date(to_char(now(), 'YYYY-MM-DD'),'YYYY-MM-DD')`
var cnt int
tx := d.transactionContext.PgTx
_, err := tx.QueryOne(pg.Scan(&cnt), sqlStr, companyId, orgId, workshopId)
return cnt, err
}
// 员工效率排名
type BoardEmployeeWorkpieceRatio struct {
Uname string `json:"uname"`
Today string `json:"today"`
Yesterday string `json:"yesterday"`
History string `json:"history"`
}
// 员工效率排名
func (d *BoardShowDao) EmployeeWorkpieceRatio(companyId int, orgId int, workshopId int) (
[]BoardEmployeeWorkpieceRatio, error) {
sqlStr := `with employee_plan_product as(
select product_worker->>'userName' as uname,
(product_weigh - second_level_weigh - CAST(product_record_info->>'totalOtherSecondLevelWeigh' as decimal)) today
,CAST(product_record_info->>'yesterdayOutputWeight' as decimal) yesterday
,CAST(product_record_info->>'bestOutputWeight' as decimal) history
from manufacture.employee_product_record
where
company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and work_station->>'sectionName' = '包装'
and product_record_info->>'productDate'=to_char(now(), 'YYYY-MM-DD')
),group_employee_plan_product as (
select uname,sum(today) today,sum(yesterday) yesterday,sum(history) history from employee_plan_product
group by uname
)
select * from group_employee_plan_product
order by today desc`
result := make([]BoardEmployeeWorkpieceRatio, 0)
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, companyId, orgId, workshopId)
if err != nil {
return nil, err
}
return result, nil
}
// 时段产能
type BoardTimeSectionProductRecord struct {
Ts string `json:"ts"`
Total string `json:"total"`
Line string `json:"line"`
}
// TimeSectionProductRecord 时段产能
func (d *BoardShowDao) TimeSectionProductRecord(companyId int, orgId int, workshopId int, lineIdA int, lineIdB int) (
[]BoardTimeSectionProductRecord, error,
) {
sqlStr := `(WITH ts_product as(
select sum(a.weight) total,a.ts,max(line) line from (
select
cast(device_running_record_info->>'count' as DECIMAL) weight,
"replace"(to_char(created_at at time ZONE 'Asia/shanghai', 'HH24:') || cast(date_part('minute',created_at) as integer)/30*30, ':0', ':00') ts,
work_station->>'lineName' line
from manufacture.device_running_record
where
company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and work_station->>'lineId' = '?'
and device_running_record_info->>'deviceType'='CCJ'
and created_at >to_date(to_char(now(), 'YYYY-MM-DD'),'YYYY-MM-DD')
) a
group by a.ts
order by ts
)
, ts_product_list as (
select d.ts,ts_product.total,line from (
select to_char(c.ts::timestamp,'HH24:MI') ts from (
select generate_series(a.end - interval '2.5 hour',
"replace"(to_char(a.end, 'yyyy-mm-dd HH24:') || cast(date_part('minute',a.end) as integer)/30*30+30, ':0', ':00')::timestamp,
'30 minute') ts from (
select to_timestamp(to_char(now() at time ZONE 'Asia/shanghai','yyyy-mm-dd HH24'),'yyyy-mm-dd HH24') as end
) a
) c
) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total ,'南瓜饼1线' line
from ts_product_list
)
union all
(WITH ts_product as(
select sum(a.weight) total,a.ts,max(line) line from (
select
cast(device_running_record_info->>'count' as DECIMAL) weight,
"replace"(to_char(created_at at time ZONE 'Asia/shanghai', 'HH24:') || cast(date_part('minute',created_at) as integer)/30*30, ':0', ':00') ts,
work_station->>'lineName' line
from manufacture.device_running_record
where
company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and work_station->>'lineId' = '?'
and device_running_record_info->>'deviceType'='CCJ'
and created_at >to_date(to_char(now(), 'YYYY-MM-DD'),'YYYY-MM-DD')
) a
group by a.ts
order by ts
)
, ts_product_list as (
select d.ts,ts_product.total,line from (
select to_char(c.ts::timestamp,'HH24:MI') ts from (
select generate_series(a.end - interval '2.5 hour',
"replace"(to_char(a.end, 'yyyy-mm-dd HH24:') || cast(date_part('minute',a.end) as integer)/30*30+30, ':0', ':00')::timestamp,
'30 minute') ts from (
select to_timestamp(to_char(now() at time ZONE 'Asia/shanghai','yyyy-mm-dd HH24'),'yyyy-mm-dd HH24') as end
) a
) c
) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total ,'南瓜饼2线' line
from ts_product_list
)`
condition := []interface{}{
companyId, orgId, workshopId, lineIdA,
companyId, orgId, workshopId, lineIdB,
}
result := make([]BoardTimeSectionProductRecord, 0)
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, condition...)
return result, err
}
// 今日昨日历史最佳
type BoardTopShow struct {
Today string `json:"today"`
Yesterday string `json:"yesterday"`
History string `json:"history"`
}
// TopShop 今日昨日历史最佳
func (d *BoardShowDao) TopShow(companyId int, orgId int, workshopId int) (*BoardTopShow, error) {
sqlStr := `with today_product as (
select
(case when product_record_type=1 then cast(product_record_info->>'weigh' as DECIMAL)
ELSE -(cast(product_record_info->>'weigh' as DECIMAL))
END) as weight,
cast(product_record_info->>'productPlanId' as INTEGER) plan_id
from manufacture.product_records
where company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and product_record_type in (1,2)
and created_at>=to_date(to_char(now(), 'YYYY-MM-DD'),'YYYY-MM-DD')
) ,tmp_today_product as(
select
(select COALESCE(sum(weight),0) weight from today_product) today,
(select COALESCE(sum(real),0) from manufacture.workshop_plan_completion_record where
company_id =?
and org_id =?
and created_at > CURRENT_DATE -1
and workshop_id = ?
limit 1
) yesterday,
(select max(real) from manufacture.workshop_plan_completion_record where workshop_id = ?) history
)
select today,
cast(yesterday as DECIMAL) yesterday,
(case when today > history then today else history end) history
from tmp_today_product`
condition := []interface{}{
companyId, orgId, workshopId,
companyId, orgId, workshopId, workshopId,
}
var result BoardTopShow
tx := d.transactionContext.PgTx
_, err := tx.QueryOne(&result, sqlStr, condition...)
return &result, err
}
// 二级品占比
type BoardProportionOfSecondLevel struct {
Sname string `json:"sname"` //品名
Rate string `json:"rate"` //占比
}
// 二级品占比
func (d *BoardShowDao) ProportionOfSecondLevel(companyId int, orgId int, workshopId int) (
[]BoardProportionOfSecondLevel, error) {
sqlStr := `with item_product as (
select sum(a.weight) item_total,max(sname) sname from (
select cast(product_record_info->>'weigh' as DECIMAL) weight
,work_station->>'sectionName' sname
,work_station->>'workStationId' workStationId
from manufacture.product_records
where company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and product_record_type = 8
and product_record_info->>'approveStatus'='2'
and created_at >=to_date(to_char(now(), 'YYYY-MM-DD'),'YYYY-MM-DD')
and work_station->>'sectionName' in ('制模','成型','穿串','包装')
) a
group by a.workStationId
)
,item_product_rate as(
select sname,round(item_total/(select sum(item_total) from item_product)*100, 0) as rate from item_product
)
select b.sname, coalesce(b.rate,0) rate from item_product_rate b`
condition := []interface{}{
companyId, orgId, workshopId,
}
result := make([]BoardProportionOfSecondLevel, 0)
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, condition...)
return result, err
}
// 工段生产信息
type BoardSectionProductInfo struct {
Sname string `json:"sname"`
ProductWeight string `json:"productWeight"`
SecondLevelWeight string `json:"secondLevelWeight"`
TotalWeigh string `json:"totalWeigh"`
Qu string `json:"qu"`
Sort string `json:"sort"` //排名
}
// 工段生产信息
func (d *BoardShowDao) SectionProductInfo(companyId int, orgId int, workshopId int) (
[]BoardSectionProductInfo, error) {
sqlStr := `with section_product as(
select
work_station->>'sectionName' section, --工段
CAST(product_record_info->>'outputWeight' as decimal) product_weigh, --产出量
CAST(product_record_info->>'secondLevelWeight' as decimal) second_level_weigh,
CAST(product_record_info->>'qualificationRate' as decimal) qu
--二级品
from manufacture.workshop_product_record
where company_id = ?
and org_id = ?
and work_station->>'workshopId'='?'
and product_date =to_char(now(), 'YYYY-MM-DD')
),
all_section_product as(
select b.sname,
COALESCE(a.product_weigh,0) product_weigh,
COALESCE(a.second_level_weigh,0) second_level_weigh,
COALESCE(a.qu,0) qu
from section_product a right join (
select unnest(ARRAY ['制模','成型','穿串','包装']) sname
) b on a.section = b.sname
),group_section_product as(
select
sname,
sum(product_weigh) product_weigh,
sum(second_level_weigh) second_level_weigh
,sum(product_weigh+second_level_weigh) total_weigh
from all_section_product
GROUP BY sname
)
select *,
(case when product_weigh=0 or total_weigh=0 then 0 else round(product_weigh*100/total_weigh,1) end) qu,
(case when sname = '制模' then 1
when sname='成型' then 2
when sname='穿串' then 3 else 4 end) sort
from group_section_product
order by sort`
condition := []interface{}{
companyId, orgId, workshopId,
}
result := make([]BoardSectionProductInfo, 0)
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, condition...)
return result, err
}
// 当前计划达成率
func (d *BoardShowDao) WorkshopPlanCompletionCurrent(companyId int, orgId int, workshopId int) (string, error) {
sqlStr := `select rate rate from manufacture.workshop_plan_completion_record where
company_id = ?
and org_id = ?
and workshop_id=?
order by created_at desc
limit 1`
condition := []interface{}{
companyId, orgId, workshopId,
}
var result string
tx := d.transactionContext.PgTx
_, err := tx.QueryOne(pg.Scan(&result), sqlStr, condition...)
return result, err
}
type PlanCompletion5Day struct {
Ts string `jsonL:"ts"`
Total string `json:"total"`
}
// 近5天 计划达成率
func (d *BoardShowDao) WorkshopPlanCompletion5Day(companyId int, orgId int, workshopId int) ([]PlanCompletion5Day, error) {
sqlStr := `with ts_product as (
select rate,
to_char(created_at,'mm-dd') ts
from manufacture.workshop_plan_completion_record
where company_id = ?
and org_id = ?
and workshop_id= ?
and created_at > (now()-interval '6d')
)
,ts_product_list as (
select d.ts,ts_product.rate from (
select to_char(c.ts::timestamp,'mm-dd') ts from (
select generate_series(now() - interval '4 day',now(),'1 day') ts
) c ) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(rate,0) total
from ts_product_list`
result := make([]PlanCompletion5Day, 0)
condition := []interface{}{
companyId, orgId, workshopId,
}
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, condition...)
return result, err
}
// product_plan 批次产能
func (d *BoardShowDao) ProductPlan(companyId int, orgId int, workshopId int) ([]PlanCompletion5Day, error) {
sqlStr := `with product_record as (
select
(case when product_record_type=1 then cast(product_record_info->>'weigh' as DECIMAL)
ELSE -(cast(product_record_info->>'weigh' as DECIMAL))
END) as weight,
cast(product_record_info->>'productPlanId' as INTEGER) plan_id
from manufacture.product_records
where company_id =?
and org_id = ?
and work_station->>'workshopId'='?'
and work_station->>'sectionName'='包装'
and product_record_type in (1,2)
and created_at>to_date(to_char((now() -interval '3 day'), 'YYYY-MM-DD'),'YYYY-MM-DD') --'2022-01-01' --
), product_record_sum as(
select sum(weight) weight,plan_id
from product_record
GROUP BY plan_id
)
select
a.product_plan_id
,batch_number --批次号
,plan_product_name --品名
,machine --机台
,coalesce(plan_devoted->>'unit','') unit --规格
,cast(coalesce(plan_devoted->>'quantity','0') as DECIMAL) quantity -- 数量
,cast(coalesce(plan_devoted->>'weight','0')as DECIMAL) plan_weight -- 计划重量
, coalesce(b.weight,0) real_weight --批次实际产能
from manufacture.product_plan a left join product_record_sum b on a.product_plan_id = b.plan_id
where company_id = ?
and org_id = ?
and workshop->>'workshopId'='?'
and product_date >to_date(to_char(now() -interval '3 day', 'YYYY-MM-DD'),'YYYY-MM-DD')
and cast(coalesce(plan_devoted->>'weight','0')as DECIMAL) >0
order by created_at desc`
result := make([]PlanCompletion5Day, 0)
condition := []interface{}{
companyId, orgId, workshopId,
companyId, orgId, workshopId,
}
tx := d.transactionContext.PgTx
_, err := tx.Query(&result, sqlStr, condition...)
return result, err
}
... ...
package dao
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
)
type RewardSumaryDao struct {
transactionContext *pgTransaction.TransactionContext
}
func NewRewardSumaryDao(transactionContext *pgTransaction.TransactionContext) (*RewardSumaryDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &RewardSumaryDao{
transactionContext: transactionContext,
}, nil
}
}
// 功过看板-日榜
type RewardSummaryDay struct {
Id int `json:"id"` //id
RecordDateStr string `json:"record_date_str"`
SectionName string `json:"sectionName"` //工段名称
WorkerName string `json:"workerName"` //员工名称
SummaryResult string `json:"summaryResult"` //奖惩结果
YieldResult string `json:"yieldResult"` //产效功过结果
UpToStandardResult string `json:"upToStandardResult"` //合格率功过结果
AccidentResult1 string `json:"accidentResult1"` //质量事故功过结果
AccidentResult2 string `json:"accidentResul2"` //安全事故功过结果
AccidentResult3 string `json:"accidentResul3"` //异物 功过结果
}
// 功过看板-日榜
func (d *RewardSumaryDao) SeachRewardSummaryDay(companyId int, orgId int, recordDate string) ([]RewardSummaryDay, error) {
sqlStr := `SELECT
"id",record_date_str,
work_station->>'sectionName' as section_name,
worker->>'userName' as worker_name,
summary_result,
yield_result,
up_to_standard_result,
accident_result1,
accident_result2,
accident_result3
FROM manufacture."reward_summary"
WHERE company_id=?
and org_id=?
and record_date_str=?`
tx := d.transactionContext.PgTx
var result []RewardSummaryDay
_, err := tx.Query(&result, sqlStr, companyId, orgId, recordDate)
for i := range result {
switch result[i].AccidentResult1 {
case "1":
result[i].AccidentResult1 = "功"
case "0":
result[i].AccidentResult1 = "不奖不惩"
case "-1":
result[i].AccidentResult1 = "过"
}
switch result[i].AccidentResult2 {
case "1":
result[i].AccidentResult2 = "功"
case "0":
result[i].AccidentResult2 = "不奖不惩"
case "-1":
result[i].AccidentResult2 = "过"
}
switch result[i].AccidentResult3 {
case "1":
result[i].AccidentResult3 = "功"
case "0":
result[i].AccidentResult3 = "不奖不惩"
case "-1":
result[i].AccidentResult3 = "过"
}
switch result[i].UpToStandardResult {
case "1":
result[i].UpToStandardResult = "功"
case "0":
result[i].UpToStandardResult = "不奖不惩"
case "-1":
result[i].UpToStandardResult = "过"
}
switch result[i].YieldResult {
case "1":
result[i].YieldResult = "功"
case "0":
result[i].YieldResult = "不奖不惩"
case "-1":
result[i].YieldResult = "过"
}
}
return result, err
}
// 功过看板-产效
type RewardSummaryYield struct {
RecordDateStr string `json:"record_date_str"`
SectionName string `json:"sectionName"` //工段名称
WorkerName string `json:"workerName"` //员工名称
Yield string `json:"yield"` //产效
YieldResult string `json:"yieldResult"` //产效功过结果
YieldMax string `json:"yildMax"` //产效历史最佳
}
// 功过看板-产效
func (d *RewardSumaryDao) SeachRewardSummaryYield(companyId int, orgId int, recordDate string) ([]RewardSummaryYield, error) {
// sqlStr := `SELECT
// record_date_str,
// work_station->>'sectionName' as section_name,
// worker->>'userName' as worker_name,
// yield_result,
// yield,
// '24' as yield_max
// FROM manufacture."reward_summary"
// WHERE company_id=?
// and org_id=?
// and record_date_str=?`
sqlStr := `with
t1 as( SELECT
max(yield) as yield_max,
work_station->>'sectionId' AS section_id,
worker->>'userId' as worker_id
FROM manufacture."reward_summary"
WHERE company_id=? and org_id=?
GROUP BY section_id,worker_id
),
t2 as (SELECT
record_date_str,
work_station->>'sectionId' AS section_id,
worker->>'userId' as worker_id,
work_station->>'sectionName' as section_name,
worker->>'userName' as worker_name,
yield_result,
yield
FROM manufacture."reward_summary"
WHERE company_id=? and org_id=?
and record_date_str=?
)
SELECT t2.record_date_str,t2.section_name,t2.worker_name,
t2.yield_result,t2.yield,t1.yield_max
FROM t2
JOIN t1 on t2.section_id=t1.section_id AND t2.worker_id=t2.worker_id`
tx := d.transactionContext.PgTx
var result []RewardSummaryYield
params := []interface{}{
companyId, orgId,
companyId, orgId, recordDate,
}
_, err := tx.Query(&result, sqlStr, params...)
for i := range result {
switch result[i].YieldResult {
case "1":
result[i].YieldResult = "功"
case "0":
result[i].YieldResult = "不奖不惩"
case "-1":
result[i].YieldResult = "过"
}
}
return result, err
}
// 功过看板-合格率
type RewardSummaryUpToStandard struct {
RecordDateStr string `json:"record_date_str"`
SectionName string `json:"sectionName"` //工段名称
WorkerName string `json:"workerName"` //员工名称
UpToStandard string `json:"upToStandard"` //合格率
UpToStandardResult string `json:"upToStandardResult"` //合格率功过结果
UpToStandardMax string `json:"upToStandardMax"` //合格率历史最佳
}
// 功过看板-合格率
func (d *RewardSumaryDao) SeachRewardUpToStandard(companyId int, orgId int, recordDate string) ([]RewardSummaryUpToStandard, error) {
// sqlStr := `SELECT
// record_date_str,
// work_station->>'sectionName' as section_name,
// worker->>'userName' as worker_name,
// up_to_standard_result,
// up_to_standard,
// '90' as up_to_standard_max
// FROM manufacture."reward_summary"
// WHERE company_id=23
// and org_id=487
// and record_date_str='2022-10-29'`
sqlStr := `with
t1 as( SELECT
max(up_to_standard) as up_to_standard_max,
work_station->>'sectionId' AS section_id,
worker->>'userId' as worker_id
FROM manufacture."reward_summary"
WHERE company_id=? and org_id=?
GROUP BY section_id,worker_id
),
t2 as (SELECT
record_date_str,
work_station->>'sectionId' AS section_id,
worker->>'userId' as worker_id,
work_station->>'sectionName' as section_name,
worker->>'userName' as worker_name,
up_to_standard_result,
up_to_standard
FROM manufacture."reward_summary"
WHERE company_id=? and org_id=?
and record_date_str=?
)
SELECT t2.record_date_str,t2.section_name,t2.worker_name,
t2.up_to_standard_result,t2.up_to_standard,t1.up_to_standard_max
FROM t2
JOIN t1 on t2.section_id=t1.section_id AND t2.worker_id=t2.worker_id`
tx := d.transactionContext.PgTx
var result []RewardSummaryUpToStandard
params := []interface{}{
companyId, orgId,
companyId, orgId, recordDate,
}
_, err := tx.Query(&result, sqlStr, params...)
for i := range result {
switch result[i].UpToStandardResult {
case "1":
result[i].UpToStandardResult = "功"
case "0":
result[i].UpToStandardResult = "不奖不惩"
case "-1":
result[i].UpToStandardResult = "过"
}
}
return result, err
}
// 功过看板-异常
type RewardAccident struct {
Id string `json:"id"`
RecordDateStr string `json:"record_date_str"`
SectionName string `json:"sectionName"` //工段名称
WorkerName string `json:"workerName"` //员工名称
AccidentAmount1 string `json:"accidentAmount1"` //质量事故损失金额
AccidentNum1 string `json:"accidentNum1"` //质量事故次数
AccidentResult1 string `json:"accidentResult1"` //质量事故功过结果
AccidentAmount2 string `json:"accidentAmount2"` //安全事故 损失金额
AccidentResult2 string `json:"accidentResul2"` //安全事故功过结果
AccidentNum2 string `json:"accidentNum2"` //安全事故 次数
AccidentNum3 string `json:"accidentNum3"` //金属异物 次数
AccidentNum4 string `json:"accidentNum4"` //非属异物事故次数
AccidentResult3 string `json:"accidentResul3"` //异物 功过结果
}
// 功过看板-异常
func (d *RewardSumaryDao) SeachRewardAccident(companyId int, orgId int, recordDate string) ([]RewardAccident, error) {
sqlStr := `SELECT
"id",record_date_str,
work_station->>'sectionName' as section_name,
worker->>'userName' as worker_name,
accident_num1,accident_amount1,accident_result1,
accident_num2,accident_amount2,accident_result2,
accident_num3,accident_num4,accident_result3
FROM manufacture."reward_summary"
WHERE company_id=?
and org_id=?
and record_date_str=?`
tx := d.transactionContext.PgTx
var result []RewardAccident
_, err := tx.Query(&result, sqlStr, companyId, orgId, recordDate)
for i := range result {
switch result[i].AccidentResult1 {
case "1":
result[i].AccidentResult1 = "功"
case "0":
result[i].AccidentResult1 = "不奖不惩"
case "-1":
result[i].AccidentResult1 = "过"
}
switch result[i].AccidentResult2 {
case "1":
result[i].AccidentResult2 = "功"
case "0":
result[i].AccidentResult2 = "不奖不惩"
case "-1":
result[i].AccidentResult2 = "过"
}
switch result[i].AccidentResult3 {
case "1":
result[i].AccidentResult3 = "功"
case "0":
result[i].AccidentResult3 = "不奖不惩"
case "-1":
result[i].AccidentResult3 = "过"
}
}
return result, err
}
// 功过看板-月榜
type RewardSummaryMonth struct {
SectionId string `json:"sectionId"` //工段名称
SectionName string `json:"sectionName"` //工段名称
WorkerName string `json:"workerName"` //员工名称
WorkerId string `json:"workerId"` //员工名称
AccidentAmount1 string `json:"accidentAmount1"` //质量事故损失金额
AccidentNum1 string `json:"accidentNum1"` //质量事故次数
AccidentNum3 string `json:"accidentNum3"` //金属异物事故 次数
AccidentNum4 string `json:"accidentNum4"` //非属异物事故 次数
AccidentAmount2 string `json:"accidentAmount2"` //安全事故 损失金额
AccidentNum2 string `json:"accidentNum2"` //安全事故 次数
YieldAvg string `json:"yieldAvg"` //平均产效
YieldMax string `json:"yieldMax"` //产效历史最佳
UpToStandard string `json:"upToStandard"` //合格率
AmountFine string `json:"amountFine"` //惩,的金额
AmountReward string `json:"amountReward"` //奖,的金额
AmountFinal string `json:"amountFinal"` //最终的 奖惩结果
}
// 功过看板-月榜
func (d *RewardSumaryDao) SeachRewardSummaryMonth(companyId int, orgId int, recordMonth string) ([]RewardSummaryMonth, error) {
sqlStr := `
SELECT
work_station->>'sectionId' AS section_id,
work_station->>'sectionName' as section_name,
worker->>'userId' as worker_id,
worker->>'userName' as worker_name,
sum(accident_num1) as accident_num1,
sum(accident_num2) as accident_num2,
sum(accident_num3) as accident_num3,
sum(accident_num4) as accident_num4,
sum(accident_amount1) as accident_amount1,
sum(accident_amount2) as accident_amount2,
CAST(sum(summary_result) as decimal(10,2)) as amount_final,
CAST(
sum(CASE WHEN summary_result<0 THEN summary_result ELSE 0 END) as decimal(10,2)
) as amount_fine,
CAST(
sum(CASE WHEN summary_result>0 THEN summary_result ELSE 0 END) as decimal(10,2)
) as amount_reward,
max(yield) as yield_max,
CAST(avg(yield) as decimal(10,2)) as yield_avg,
CAST(avg(up_to_standard) as decimal(10,2) ) as up_to_standard
FROM manufacture.reward_summary
WHERE company_id=?
and org_id=?
and record_month_str=?
GROUP BY section_id,worker_id,worker_name,section_name
;
`
tx := d.transactionContext.PgTx
var result []RewardSummaryMonth
_, err := tx.Query(&result, sqlStr, companyId, orgId, recordMonth)
return result, err
}
... ...
... ... @@ -3,13 +3,14 @@ package domainService
import (
"errors"
"fmt"
"time"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
type PGProductRecordService struct {
... ... @@ -37,10 +38,12 @@ type SubmitOptions struct {
UnitConversionId int `cname:"物料ID" json:"unitConversionId"`
// 重量
Weigh float64 `cname:"重量" json:"weigh" valid:"Required"`
//日期
CreatedAt time.Time `cname:"日期" json:"createdAt" `
}
// SubmitProductRecord 提交生产记录
func (ptr *PGProductRecordService) SubmitProductRecord(productRecordType int, queryOptions map[string]interface{}) (interface{}, error) {
func (ptr *PGProductRecordService) SubmitProductRecord(productRecordType int, queryOptions map[string]interface{}) (*domain.ProductRecord, error) {
var request = &SubmitOptions{}
if err := utils.LoadQueryObject(queryOptions, request); err != nil {
return nil, err
... ... @@ -127,6 +130,12 @@ func (ptr *PGProductRecordService) SubmitProductRecord(productRecordType int, qu
},
Ext: domain.NewExt(org.OrgName),
}
if !request.CreatedAt.IsZero() {
//管理页面上手动添加记录时,有填写日期
record.CreatedAt = request.CreatedAt
}
if record, err = productRecordRepository.Save(record); err != nil {
return nil, err
}
... ... @@ -147,7 +156,7 @@ func (ptr *PGProductRecordService) SubmitProductRecord(productRecordType int, qu
// return nil, err
// }
//}
return nil, nil
return record, nil
}
// Approve 审核生产记录 (二级品审核)
... ...
... ... @@ -2,12 +2,13 @@ package domainService
import (
"fmt"
"time"
"github.com/mohae/deepcopy"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
const (
... ... @@ -21,7 +22,7 @@ const (
DefaultCCJUnitQuantity = 0.2 //kg 穿串机默认的换算数量 1串/0.1千克
)
//EmployeeProductStatics 员工产能统计
// EmployeeProductStatics 员工产能统计
func (ptr *PGProductRecordService) EmployeeProductStatics(productRecord *domain.ProductRecord) (interface{}, error) {
var (
... ... @@ -249,10 +250,18 @@ func (ptr *PGProductRecordService) personalProductStatics(productPlan *domain.Pr
if employeeProductRecord, err = employeeProductRecordRepository.Save(employeeProductRecord); err != nil {
log.Logger.Error(fmt.Sprintf("生产记录:[%v] 员工:[%v] 处理异常:%v", productRecord.ProductRecordId, productRecord.ProductWorker.UserId, err.Error()))
}
//TODO 记录奖惩明细
rewardSummarySrv, _ := NewPGRewardSummaryStaticService(ptr.transactionContext)
err = rewardSummarySrv.CreateRewardSummaryByEmployeeProductRecord(employeeProductRecord)
if err != nil {
log.Logger.Error(fmt.Sprintf("记录奖惩明细,生产记录:[%v] 员工:[%v] 处理异常:%v", productRecord.ProductRecordId, productRecord.ProductWorker.UserId, err.Error()))
}
return nil, nil
}
//WorkshopProductStatics 车间产能统计
// WorkshopProductStatics 车间产能统计
func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.ProductRecord) (interface{}, error) {
var (
workshopRepository, _ = repository.NewWorkshopRepository(ptr.transactionContext)
... ...
package domainService
import (
"fmt"
"time"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
)
//功过奖惩明细汇总
type PGRewardSummaryStaticService struct {
transactionContext *pgTransaction.TransactionContext
}
func NewPGRewardSummaryStaticService(transactionContext *pgTransaction.TransactionContext) (*PGRewardSummaryStaticService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PGRewardSummaryStaticService{
transactionContext: transactionContext,
}, nil
}
}
// 根据事故数据
func (c *PGRewardSummaryStaticService) CreateRewardSummaryByProductTrouble(param *domain.ProductTrouble) error {
rewardSummaryRepo, _ := repository.NewRewardSummaryRepository(c.transactionContext)
//查询是否已经有汇总数据
condtion := map[string]interface{}{
"orgId": param.OrgId,
"companyId": param.CompanyId,
"lineId": param.WorkStation.LineId,
"sectionId": param.WorkStation.SectionId,
"workshopId": param.WorkStation.WorkshopId,
"workerId": param.ProductWorker.UserId,
"recordDateStr": param.RecordDate.Format("200-01-02"),
}
_, summaryList, err := rewardSummaryRepo.Find(condtion)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var summaryData *domain.RewardSummary
nowTime := time.Now()
if len(summaryList) > 0 {
summaryData = summaryList[0]
} else {
summaryData = &domain.RewardSummary{
Id: 0,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
WorkStation: param.WorkStation,
Worker: param.ProductWorker,
RecordDate: param.RecordDate,
RecordDateStr: param.RecordDate.Format("2006-01-02"),
UpToStandard: 0.0,
Yield: 0.0,
AccidentNum1: 0,
AccidentAmount1: 0.0,
AccidentNum2: 0,
AccidentAmount2: 0.0,
AccidentNum3: 0,
AccidentNum4: 0,
SummaryResult: 0.0,
CreatedAt: nowTime,
UpdatedAt: nowTime,
}
}
var targetType int
switch param.Types {
case domain.TroubleType1:
targetType = domain.TargetType3
case domain.TroubleType2:
targetType = domain.TargetType4
case domain.TroubleType3:
targetType = domain.TargetType5
case domain.TroubleType4:
targetType = domain.TargetType5
}
//获取奖惩标准 按 车间 线别 工段 类型
rewardStandardRepo, _ := repository.NewRewardStandardRepository(c.transactionContext)
_, rewardStandardList, err := rewardStandardRepo.Find(map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
"workshopId": param.WorkStation.WorkshopId,
"lineId": param.WorkStation.LineId,
"sectionId": param.WorkStation.SectionId,
"targetType": targetType,
"limit": 1,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(rewardStandardList) > 0 {
summaryData.SummaryAccident(param, rewardStandardList[0])
} else {
summaryData.SummaryAccident(param, nil)
}
//获取奖惩规则
rewardRuleRepo, _ := repository.NewRewardRuleRepository(c.transactionContext)
_, rewardRuleList, err := rewardRuleRepo.Find(map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取奖惩规则"+err.Error())
}
if len(rewardRuleList) >= 0 {
summaryData.ApplySummaryResult(rewardRuleList[0])
}
summaryData.UpdatedAt = nowTime
_, err = rewardSummaryRepo.Save(summaryData)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
// CreateRewardSummaryByEmployeeProductRecord 通过员工生产记录 汇总奖惩结果
func (c *PGRewardSummaryStaticService) CreateRewardSummaryByEmployeeProductRecord(param *domain.EmployeeProductRecord) error {
rewardSummaryRepo, _ := repository.NewRewardSummaryRepository(c.transactionContext)
//查询是否已经有汇总数据
condtion := map[string]interface{}{
"orgId": param.OrgId,
"companyId": param.CompanyId,
"lineId": param.WorkStation.LineId,
"sectionId": param.WorkStation.SectionId,
"workshopId": param.WorkStation.WorkshopId,
"workerId": param.ProductWorker.UserId,
"recordDateStr": param.CreatedAt.Format("2006-01-02"),
}
_, summaryList, err := rewardSummaryRepo.Find(condtion)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var summaryData *domain.RewardSummary
nowTime := time.Now()
if len(summaryList) > 0 {
summaryData = summaryList[0]
} else {
summaryData = &domain.RewardSummary{
Id: 0,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
// WorkStation: *param.WorkStation,
// Worker: *param.ProductWorker,
RecordDate: param.CreatedAt,
RecordDateStr: param.CreatedAt.Format("2006-01-02"),
UpToStandard: 0.0,
Yield: 0.0,
AccidentNum1: 0,
AccidentAmount1: 0.0,
AccidentNum2: 0,
AccidentAmount2: 0.0,
AccidentNum3: 0,
AccidentNum4: 0,
SummaryResult: 0.0,
CreatedAt: nowTime,
UpdatedAt: nowTime,
}
if param.WorkStation != nil {
summaryData.WorkStation = *param.WorkStation
}
if param.ProductWorker != nil {
summaryData.Worker = *param.ProductWorker
}
}
//获取奖惩标准 按 车间 线别 工段 类型 ;合格率类型
rewardStandardRepo, _ := repository.NewRewardStandardRepository(c.transactionContext)
_, rewardStandardList, err := rewardStandardRepo.Find(map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
"workshopId": param.WorkStation.WorkshopId,
"lineId": param.WorkStation.LineId,
"sectionId": param.WorkStation.SectionId,
"targetType": domain.TargetType2,
"limit": 1,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(rewardStandardList) > 0 {
//汇总合格率
summaryData.SummaryUpToStandard(param.ProductRecordInfo.QualificationRate, rewardStandardList[0])
} else {
summaryData.SummaryUpToStandard(param.ProductRecordInfo.QualificationRate, nil)
}
//获取奖惩标准 按 车间 线别 工段 类型 ;产能类型
_, rewardStandardList, err = rewardStandardRepo.Find(map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
"workshopId": param.WorkStation.WorkshopId,
"lineId": param.WorkStation.LineId,
"sectionId": param.WorkStation.SectionId,
"targetType": domain.TargetType1,
"limit": 1,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(rewardStandardList) > 0 {
//汇总合格率
summaryData.SummaryYield(param.ProductRecordInfo.OutputWeight, rewardStandardList[0])
} else {
summaryData.SummaryYield(param.ProductRecordInfo.OutputWeight, nil)
}
//根据规则算 奖惩金额
//获取奖惩规则
rewardRuleRepo, _ := repository.NewRewardRuleRepository(c.transactionContext)
_, rewardRuleList, err := rewardRuleRepo.Find(map[string]interface{}{
"companyId": param.CompanyId,
"orgId": param.OrgId,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取奖惩规则"+err.Error())
}
if len(rewardRuleList) >= 0 {
summaryData.ApplySummaryResult(rewardRuleList[0])
}
summaryData.UpdatedAt = nowTime
_, err = rewardSummaryRepo.Save(summaryData)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
return nil
}
... ...
... ... @@ -3,10 +3,11 @@ package pg
import (
"context"
"fmt"
"github.com/beego/beego/v2/core/logs"
"log"
"reflect"
"github.com/beego/beego/v2/core/logs"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
... ... @@ -50,6 +51,10 @@ func init() {
(*models.WorkshopPlanCompletionRecord)(nil),
(*models.ProductMaterialGroup)(nil),
(*models.ProductMaterial)(nil),
(*models.RewardStandard)(nil),
(*models.RewardRule)(nil),
(*models.ProductTrouble)(nil),
(*models.RewardSummary)(nil),
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type EmployeeProductRecord struct {
... ...
package models
import (
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
// 事故管理数据结构
type ProductTrouble struct {
tableName string `comment:" 事故管理" pg:"manufacture.product_trouble,alias:product_trouble"`
Id int ` pg:"pk:id"` // id
CompanyId int //企业id
OrgId int //组织ID
WorkStation domain.WorkStation // 工作位置
ProductWorker domain.User // 生产工人
AmountLoss float64 // 损失的金额
Types string // 事故类型
RecordDate time.Time // 事故发生的日期
Remark string // 备注
ApproveStatus int // 审核状态 1:未审核 2:已审核 3.自动审核
ApproveAt *time.Time // 审核时间
ApproveUser *domain.User // 审核人
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time // 删除时间
}
... ...
package models
import (
"time"
)
//RewardRule 奖惩规则
type RewardRule struct {
tableName string `pg:"manufacture.reward_rule,alias:reward_rule"`
Id int `pg:"pk:id"` //奖惩标准 id
CompanyId int `comment:"企业id"` // 企业id
OrgId int `comment:"组织ID"` // 组织ID
RewardTag string
RewardNum int
RewardAmount string
FaultTag string
FaultNum int
FaultAmount string
Remark string
CreatedAt time.Time
UpdatedAt time.Time
}
... ...
package models
import (
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
//RewardStandard 奖惩标准
type RewardStandard struct {
tableName string `pg:"manufacture.reward_standard,alias:reward_standard"`
Id int `pg:"pk:id"` //奖惩标准 id
CompanyId int `comment:"企业id"` // 企业id
OrgId int `comment:"组织ID"` // 组织ID
Workshop domain.SimpleWorkshop //车间
ProductLine domain.SimpleProductLine //生产线
ProductSection domain.ProductSection //工段
Remark string //备注
TargetType int //指标类别 1:产效 2:合格率 3:安全事故 4:质量事故 5:异物次数
TargeVal1 string //填写的指标值1
TargeVal2 string //填写的指标值2
TargeVal3 string //填写的指标值3
TargeVal4 string //填写的指标值4
CreatedAt time.Time //创建时间
UpdatedAt time.Time //更新时间
DeletedAt *time.Time //删除时间
}
... ...
package models
import (
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
// RewardSummary 功过奖惩明细
type RewardSummary struct {
tableName string `pg:"manufacture.reward_summary,alias:reward_summary"`
Id int `pg:"pk:id"`
CompanyId int ``
OrgId int ``
RecordDate time.Time //日期
RecordDateStr string //日期 ;2006-01-02
RecordMonthStr string //月份 :200601
WorkStation domain.WorkStation // 工作位置
Worker domain.User //员工
UpToStandard float64 `comment:"合格率"` //合格率
UpToStandardResult int `comment:"合格率功过评定结果 1:功 -1:过 0:不奖不惩"` //合格率功过评定结果1:功 -1:过 0:不奖不惩
Yield float64 `comment:"产能"` //产能
YieldResult int `comment:"产能功过评定结果,1:功 -1:过 0:不奖不惩"` //产能功过评定结果,1:功 -1:过 0:不奖不惩
AccidentNum1 int `comment:"质量事故 次数"` //质量事故 次数
AccidentAmount1 float64 `comment:"质量事故 损失金额"` //质量事故 损失金额
AccidentResult1 int `comment:"质量事故 功过评定结果1:功 -1:过 0:不奖不惩"` //质量事故 功过评定结果1:功 -1:过 0:不奖不惩
AccidentNum2 int `comment:"安全事故 次数"` //安全事故 次数
AccidentAmount2 float64 `comment:"安全事故 损失金额"` //安全事故 损失金额
AccidentResult2 int `comment:"安全事故 功过评定结果 1:功 -1:过 0:不奖不惩"` //安全事故 功过评定结果 1:功 -1:过 0:不奖不惩
AccidentNum3 int `comment:"异物金属事故 次数"` //异物金属事故 次数
AccidentResult3 int `comment:"异物事故 功过评定结果 1:功 -1:过 0:不奖不惩"` //异物事故 功过评定结果 1:功 -1:过 0:不奖不惩
AccidentNum4 int `comment:"异物非金属事故 次数"` //异物非金属事故 次数
SummaryResult float64 `comment:"奖惩金额计算结果(元)"` //奖惩金额计算结果(元)
CreatedAt time.Time //
UpdatedAt time.Time //
}
... ...
... ... @@ -2,6 +2,7 @@ package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
... ...
... ... @@ -2,12 +2,13 @@ package repository
import (
"fmt"
"time"
"github.com/go-pg/pg/v10"
"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"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
... ... @@ -176,7 +177,7 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
query.Where("created_at>=?", v.(time.Time))
}
if v, ok := queryOptions["productEndTime"]; ok && !((v.(time.Time)).IsZero()) {
query.Where("created_at<?", v.(time.Time))
query.Where("created_at<=?", v.(time.Time))
}
if v, ok := queryOptions["batchNumber"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_record_info->>'batchNumber' like '%%%v%%'`, v))
... ...
package repository
import (
"fmt"
"time"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type ProductTroubleRepository struct {
transactionContext *pgTransaction.TransactionContext
}
var _ domain.ProductTroubleRepository = (*ProductTroubleRepository)(nil)
func NewProductTroubleRepository(transactionContext *pgTransaction.TransactionContext) (*ProductTroubleRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductTroubleRepository{
transactionContext: transactionContext,
}, nil
}
}
func (repo *ProductTroubleRepository) Save(param *domain.ProductTrouble) (*domain.ProductTrouble, error) {
m := models.ProductTrouble{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
WorkStation: param.WorkStation,
ProductWorker: param.ProductWorker,
AmountLoss: param.AmountLoss,
Types: string(param.Types),
RecordDate: param.RecordDate,
Remark: param.Remark,
ApproveStatus: int(param.ApproveStatus),
ApproveAt: param.ApproveAt,
ApproveUser: param.ApproveUser,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
DeletedAt: param.DeletedAt,
}
tx := repo.transactionContext.PgTx
if param.Id == 0 {
_, err := tx.Model(&m).Insert()
if err != nil {
return nil, err
}
param.Id = m.Id
} else {
_, err := tx.Model(&m).WherePK().Update()
if err != nil {
return nil, err
}
}
return param, nil
}
func (repo *ProductTroubleRepository) Remove(param *domain.ProductTrouble) (*domain.ProductTrouble, error) {
tx := repo.transactionContext.PgTx
m := new(models.ProductTrouble)
m.Id = param.Id
nowTime := time.Now()
param.DeletedAt = &nowTime
_, err := tx.Model(m).
WherePK().Set("deleted_at=?", nowTime).
Update()
if err != nil {
return param, err
}
return nil, nil
}
func (repo *ProductTroubleRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductTrouble, error) {
tx := repo.transactionContext.PgTx
m := new(models.ProductTrouble)
query := tx.Model(m).Where("deleted_at isnull")
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
err := query.First()
if err != nil {
if err == pg.ErrNoRows {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
result := repo.TransformToDomain(m)
return result, nil
}
func (repo *ProductTroubleRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductTrouble, error) {
tx := repo.transactionContext.PgTx
m := []models.ProductTrouble{}
query := tx.Model(&m).
Where("deleted_at isnull").
Limit(20)
if v, ok := queryOptions["limit"].(int); ok && v > 0 {
query.Limit(v)
}
if v, ok := queryOptions["offset"].(int); ok && v >= 0 {
query.Offset(v)
}
if v, ok := queryOptions["companyId"]; ok {
query.Where("company_id=?", v)
}
if v, ok := queryOptions["orgId"]; ok {
query.Where("org_id=?", v)
}
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`Work_station->>'workshopName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["productWorkerName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_worker->>'userName' like '%%%v%%'`, v))
}
query.Order("id DESC")
cnt, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var listData []*domain.ProductTrouble
for i := range m {
temp := repo.TransformToDomain(&m[i])
listData = append(listData, temp)
}
return int64(cnt), listData, nil
}
func (repo *ProductTroubleRepository) TransformToDomain(param *models.ProductTrouble) *domain.ProductTrouble {
return &domain.ProductTrouble{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
WorkStation: param.WorkStation,
ProductWorker: param.ProductWorker,
AmountLoss: param.AmountLoss,
Types: domain.TroubleType(param.Types),
RecordDate: param.RecordDate,
Remark: param.Remark,
ApproveStatus: domain.ProductTroubleApprove(param.ApproveStatus),
ApproveAt: param.ApproveAt,
ApproveUser: param.ApproveUser,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
DeletedAt: param.DeletedAt,
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type RewardRuleRepository struct {
transactionContext *pgTransaction.TransactionContext
}
var _ domain.RewardRuleRepository = (*RewardRuleRepository)(nil)
func NewRewardRuleRepository(transactionContext *pgTransaction.TransactionContext) (*RewardRuleRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &RewardRuleRepository{
transactionContext: transactionContext,
}, nil
}
}
// func (repo *RewardStandardRepository) nextIdentify() (int64, error) {
// IdWorker, err := snowflake.NewIdWorker(1)
// if err != nil {
// return 0, err
// }
// id, err := IdWorker.NextId()
// return id, err
// }
func (repo *RewardRuleRepository) Save(param *domain.RewardRule) (*domain.RewardRule, error) {
m := models.RewardRule{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
RewardTag: param.RewardTag,
RewardNum: param.RewardNum,
RewardAmount: param.RewardAmount,
FaultTag: param.FaultTag,
FaultNum: param.FaultNum,
FaultAmount: param.FaultAmount,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
Remark: param.Remark,
}
tx := repo.transactionContext.PgTx
if param.Id == 0 {
_, err := tx.Model(&m).Insert()
if err != nil {
return nil, err
}
param.Id = m.Id
} else {
_, err := tx.Model(&m).WherePK().Update()
if err != nil {
return nil, err
}
}
return param, nil
}
// func (repo *RewardRuleRepository) Remove(param *domain.RewardStandard) (*domain.RewardStandard, error) {
// tx := repo.transactionContext.PgTx
// m := new(models.RewardStandard)
// m.Id = param.Id
// nowTime := time.Now()
// param.DeletedAt = &nowTime
// _, err := tx.Model(m).
// WherePK().Set("deleted_at=?", nowTime).
// Update()
// if err != nil {
// return param, err
// }
// return nil, nil
// }
func (repo *RewardRuleRepository) FindOne(queryOptions map[string]interface{}) (*domain.RewardRule, error) {
tx := repo.transactionContext.PgTx
m := new(models.RewardRule)
query := tx.Model(m)
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
err := query.First()
if err != nil {
if err == pg.ErrNoRows {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
result := repo.TransformToDomain(m)
return result, nil
}
func (repo *RewardRuleRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.RewardRule, error) {
tx := repo.transactionContext.PgTx
m := []models.RewardRule{}
query := tx.Model(&m).
Limit(20)
if v, ok := queryOptions["limit"].(int); ok {
query.Limit(v)
}
if v, ok := queryOptions["offset"].(int); ok {
query.Offset(v)
}
if v, ok := queryOptions["companyId"]; ok {
query.Where("company_id=?", v)
}
if v, ok := queryOptions["orgId"]; ok {
query.Where("org_id=?", v)
}
cnt, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var listData []*domain.RewardRule
for i := range m {
temp := repo.TransformToDomain(&m[i])
listData = append(listData, temp)
}
return int64(cnt), listData, nil
}
func (repo *RewardRuleRepository) TransformToDomain(param *models.RewardRule) *domain.RewardRule {
return &domain.RewardRule{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
RewardTag: param.RewardTag,
RewardNum: param.RewardNum,
RewardAmount: param.RewardAmount,
FaultTag: param.FaultTag,
FaultNum: param.FaultNum,
FaultAmount: param.FaultAmount,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
Remark: param.Remark,
}
}
... ...
package repository
import (
"fmt"
"time"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type RewardStandardRepository struct {
transactionContext *pgTransaction.TransactionContext
}
var _ domain.RewardStandardRepository = (*RewardStandardRepository)(nil)
func NewRewardStandardRepository(transactionContext *pgTransaction.TransactionContext) (*RewardStandardRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &RewardStandardRepository{
transactionContext: transactionContext,
}, nil
}
}
// func (repo *RewardStandardRepository) nextIdentify() (int64, error) {
// IdWorker, err := snowflake.NewIdWorker(1)
// if err != nil {
// return 0, err
// }
// id, err := IdWorker.NextId()
// return id, err
// }
func (repo *RewardStandardRepository) Save(param *domain.RewardStandard) (*domain.RewardStandard, error) {
m := models.RewardStandard{
Id: param.Id,
Workshop: param.Workshop,
ProductLine: param.ProductLine,
ProductSection: param.ProductSection,
Remark: param.Remark,
TargetType: param.TargetType,
TargeVal1: param.TargeVal1,
TargeVal2: param.TargeVal2,
TargeVal3: param.TargeVal3,
TargeVal4: param.TargeVal4,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
DeletedAt: param.DeletedAt,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
}
tx := repo.transactionContext.PgTx
if param.Id == 0 {
_, err := tx.Model(&m).Insert()
if err != nil {
return nil, err
}
param.Id = m.Id
} else {
_, err := tx.Model(&m).WherePK().Update()
if err != nil {
return nil, err
}
}
return param, nil
}
func (repo *RewardStandardRepository) Remove(param *domain.RewardStandard) (*domain.RewardStandard, error) {
tx := repo.transactionContext.PgTx
m := new(models.RewardStandard)
m.Id = param.Id
nowTime := time.Now()
param.DeletedAt = &nowTime
_, err := tx.Model(m).
WherePK().Set("deleted_at=?", nowTime).
Update()
if err != nil {
return param, err
}
return nil, nil
}
func (repo *RewardStandardRepository) FindOne(queryOptions map[string]interface{}) (*domain.RewardStandard, error) {
tx := repo.transactionContext.PgTx
m := new(models.RewardStandard)
query := tx.Model(m).Where("deleted_at isnull")
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
err := query.First()
if err != nil {
if err == pg.ErrNoRows {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
result := repo.TransformToDomain(m)
return result, nil
}
func (repo *RewardStandardRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.RewardStandard, error) {
tx := repo.transactionContext.PgTx
m := []models.RewardStandard{}
query := tx.Model(&m).
Where("deleted_at isnull").
Limit(20)
if v, ok := queryOptions["limit"].(int); ok {
query.Limit(v)
}
if v, ok := queryOptions["companyId"]; ok {
query.Where("company_id=?", v)
}
if v, ok := queryOptions["orgId"]; ok {
query.Where("org_id=?", v)
}
if v, ok := queryOptions["offset"].(int); ok {
query.Offset(v)
}
if v, ok := queryOptions["workshopId"]; ok {
query.Where("workshop->>'workshopId'='?'", v)
}
if v, ok := queryOptions["lineId"]; ok {
query.Where("product_line->>'lineId'='?'", v)
}
if v, ok := queryOptions["sectionId"]; ok {
query.Where("product_section->>'sectionId'='?'", v)
}
if v, ok := queryOptions["targetType"]; ok {
query.Where("target_type=?", v)
}
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`workshop->>'workshopName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["lineName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_line->>'lineName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["sectionName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`product_section->>'sectionName' like '%%%v%%'`, v))
}
cnt, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var listData []*domain.RewardStandard
for i := range m {
temp := repo.TransformToDomain(&m[i])
listData = append(listData, temp)
}
return int64(cnt), listData, nil
}
func (repo *RewardStandardRepository) TransformToDomain(param *models.RewardStandard) *domain.RewardStandard {
return &domain.RewardStandard{
Id: param.Id,
Workshop: param.Workshop,
ProductLine: param.ProductLine,
ProductSection: param.ProductSection,
Remark: param.Remark,
TargetType: param.TargetType,
TargeVal1: param.TargeVal1,
TargeVal2: param.TargeVal2,
TargeVal3: param.TargeVal3,
TargeVal4: param.TargeVal4,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
DeletedAt: param.DeletedAt,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
}
}
... ...
package repository
import (
"fmt"
"time"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type RewardSummaryRepository struct {
transactionContext *pgTransaction.TransactionContext
}
var _ domain.RewardSummaryRepository = (*RewardSummaryRepository)(nil)
func NewRewardSummaryRepository(transactionContext *pgTransaction.TransactionContext) (*RewardSummaryRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &RewardSummaryRepository{
transactionContext: transactionContext,
}, nil
}
}
func (repo *RewardSummaryRepository) Save(param *domain.RewardSummary) (*domain.RewardSummary, error) {
m := models.RewardSummary{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
RecordDate: param.RecordDate,
RecordDateStr: param.RecordDateStr,
WorkStation: param.WorkStation,
Worker: param.Worker,
UpToStandard: param.UpToStandard,
Yield: param.Yield,
AccidentNum1: param.AccidentNum1,
AccidentAmount1: param.AccidentAmount1,
AccidentNum2: param.AccidentNum2,
AccidentAmount2: param.AccidentAmount2,
AccidentNum3: param.AccidentNum3,
AccidentNum4: param.AccidentNum4,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
SummaryResult: param.SummaryResult,
}
tx := repo.transactionContext.PgTx
if param.Id == 0 {
_, err := tx.Model(&m).Insert()
if err != nil {
return nil, err
}
param.Id = m.Id
} else {
_, err := tx.Model(&m).WherePK().Update()
if err != nil {
return nil, err
}
}
return param, nil
}
func (repo *RewardSummaryRepository) FindOne(queryOptions map[string]interface{}) (*domain.RewardSummary, error) {
tx := repo.transactionContext.PgTx
m := new(models.RewardSummary)
query := tx.Model(m)
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
err := query.First()
if err != nil {
if err == pg.ErrNoRows {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
result := repo.TransformToDomain(m)
return result, nil
}
func (repo *RewardSummaryRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.RewardSummary, error) {
tx := repo.transactionContext.PgTx
m := []models.RewardSummary{}
query := tx.Model(&m).
Limit(20)
if v, ok := queryOptions["limit"].(int); ok && v >= 0 {
query.Limit(v)
}
if v, ok := queryOptions["offset"].(int); ok && v >= 0 {
query.Offset(v)
}
if v, ok := queryOptions["companyId"]; ok {
query.Where("company_id=?", v)
}
if v, ok := queryOptions["orgId"]; ok {
query.Where("org_id=?", v)
}
//车间名称
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(`Work_station->>'workshopName' like ?`, fmt.Sprintf("%%%v%%", v))
}
//线别名称
if v, ok := queryOptions["lineName"]; ok && len(v.(string)) > 0 {
query.Where(`Work_station->>'lineName' like ?`, fmt.Sprintf("%%%v%%", v))
}
//工段id
if v, ok := queryOptions["sectionId"]; ok {
query.Where(`Work_station->>'sectionId' = '?'`, v)
}
//车间id
if v, ok := queryOptions["workshopId"]; ok {
query.Where(`Work_station->>'workshopId'='?'`, v)
}
//线别id
if v, ok := queryOptions["lineId"]; ok {
query.Where(`Work_station->>'lineId' = '?'`, v)
}
//日期开始
if v, ok := queryOptions["beginDate"]; ok {
if !(v.(time.Time)).IsZero() {
query.Where("record_date>=?", v)
}
}
//日期结束
if v, ok := queryOptions["endDate"]; ok {
if !(v.(time.Time)).IsZero() {
query.Where("record_date<=?", v)
}
}
//指定查询某个日期
if v, ok := queryOptions["recordDateStr"]; ok {
query.Where("record_date_str=?", v)
}
//用户id
if v, ok := queryOptions["workerId"]; ok {
query.Where(`worker->>'userId'='?'`, v)
}
cnt, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var listData []*domain.RewardSummary
for i := range m {
temp := repo.TransformToDomain(&m[i])
listData = append(listData, temp)
}
return int64(cnt), listData, nil
}
func (repo *RewardSummaryRepository) TransformToDomain(param *models.RewardSummary) *domain.RewardSummary {
return &domain.RewardSummary{
Id: param.Id,
CompanyId: param.CompanyId,
OrgId: param.OrgId,
RecordDate: param.RecordDate,
WorkStation: param.WorkStation,
Worker: param.Worker,
UpToStandard: param.UpToStandard,
Yield: param.Yield,
AccidentNum1: param.AccidentNum1,
AccidentAmount1: param.AccidentAmount1,
AccidentNum2: param.AccidentNum2,
AccidentAmount2: param.AccidentAmount2,
AccidentNum3: param.AccidentNum3,
AccidentNum4: param.AccidentNum4,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
SummaryResult: param.SummaryResult,
RecordDateStr: param.RecordDateStr,
}
}
... ...
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"
"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"
. "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/routers"
)
... ... @@ -17,7 +18,7 @@ func init() {
web.BConfig.AppName = "project"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev"
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.Listen.HTTPPort = 8083
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego/routers"
if os.Getenv("RUN_MODE") != "" {
... ... @@ -30,7 +31,7 @@ func init() {
}
}
//https支持
web.BConfig.Listen.EnableHTTPS = true
web.BConfig.Listen.EnableHTTPS = false
web.BConfig.Listen.HTTPSPort = 443
//进程内监控
... ... @@ -60,7 +61,7 @@ func init() {
web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeRouter, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/statistics/service"
)
type BoardDataController struct {
beego.BaseController
}
// 车间描述
func (c *BoardDataController) WorkshopDesc() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.WorkshopDesc()
c.Response(data, err)
}
func (c *BoardDataController) EmployeeWorkpieceRatio() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.EmployeeWorkpieceRatio()
c.Response(data, err)
}
// 时段产能
func (c *BoardDataController) TimeSectionProductRecord() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.TimeSectionProductRecord()
c.Response(data, err)
}
func (c *BoardDataController) TopShow() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.TopShow()
c.Response(data, err)
}
func (c *BoardDataController) ProportionOfSecondLevel() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.ProportionOfSecondLevel()
c.Response(data, err)
}
func (c *BoardDataController) SectionProductInfo() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.SectionProductInfo()
c.Response(data, err)
}
func (c *BoardDataController) WorkshopPlanCompletionCurrent() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.WorkshopPlanCompletionCurrent()
c.Response(data, err)
}
func (c *BoardDataController) WorkshopPlanCompletion5Day() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.WorkshopPlanCompletion5Day()
c.Response(data, err)
}
func (c *BoardDataController) ProductPlan() {
srv := service.NewCommonStatisticsService(nil)
data, err := srv.ProductPlan()
c.Response(data, err)
}
... ...
... ... @@ -2,14 +2,16 @@ package controllers
import (
"fmt"
"io"
"path/filepath"
"github.com/beego/beego/v2/server/web/context"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/excel"
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/ecelData/service"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"io"
"path/filepath"
)
type ExcelDataController struct {
... ... @@ -29,6 +31,7 @@ func (controller *ExcelDataController) responseExcelByFile(ctx *context.Context,
return nil
}
// FileImport 导入excel数据
func (controller *ExcelDataController) FileImport() {
var (
data interface{}
... ... @@ -36,10 +39,11 @@ func (controller *ExcelDataController) FileImport() {
r io.Reader
ext string
)
//excelService := service.NewExcelDataService(nil)
excelService := service.NewExcelDataService(nil)
r, ext, err = controller.GetFileWithExt()
if err != nil {
controller.Response(nil, err)
e := application.ThrowError(application.BUSINESS_ERROR, err.Error())
controller.Response(nil, e)
return
}
cmd := &command.ImportDataCommand{}
... ... @@ -54,8 +58,16 @@ func (controller *ExcelDataController) FileImport() {
// data, err = excelService.ImportCooperationUser(cmd)
//case domain.ImportOrganization:
// data, err = excelService.ImportOrganization(cmd)
case "ImportProductTrouble":
data, err = excelService.ImportProductTrouble(cmd)
case "ImportProductRecordLevel2":
data, err = excelService.ImportProductRecord(cmd)
case "ImportAttendance":
data, err = excelService.ImportDataAttendance(cmd)
case "ImportProductCapacities":
data, err = excelService.ImportProductCapacities(cmd)
default:
err = fmt.Errorf("导入不存在 Code:%v", cmd.Code)
err = application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("导入不存在 Code:%v", cmd.Code))
}
controller.Response(data, err)
}
... ... @@ -109,7 +121,7 @@ func (controller *ExcelDataController) FileExport() {
controller.responseExcelByFile(controller.Ctx, excelTool, filename)
}
//GetExcelDataFields 获取导出excel数据的可选字段
// GetExcelDataFields 获取导出excel数据的可选字段
func (controller *ExcelDataController) GetExcelDataFields() {
}
... ... @@ -129,8 +141,8 @@ func (controller *ExcelDataController) GetFileWithExt() (io.Reader, string, erro
func (controller *ExcelDataController) FileImportTemplate() {
excelService := service.NewExcelDataService(nil)
cmd := &command.ImportDataCommand{}
code := controller.GetString(":code")
cmd := &command.ImportDataCommand{}
cmd.Code = code
var data interface{}
data, err := excelService.FileImportTemplate(cmd)
... ...
... ... @@ -13,9 +13,10 @@ type ProductRecordController struct {
func (controller *ProductRecordController) CreateProductRecord() {
productRecordService := service.NewProductRecordService(nil)
createProductRecordCommand := &command.CreateProductRecordCommand{}
controller.Unmarshal(createProductRecordCommand)
data, err := productRecordService.CreateProductRecord(createProductRecordCommand)
createCommand := &command.CreateProductRecordCommand{}
Must(controller.Unmarshal(createCommand))
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.CreateProductRecord(operateInfo, createCommand)
controller.Response(data, err)
}
... ... @@ -127,3 +128,65 @@ func (controller *ProductRecordController) SearchWorkshopProductRecord() {
total, data, err := productPlanService.SearchWorkshopProductRecord(ParseOperateInfo(controller.BaseController), cmd)
ResponseGrid(controller.BaseController, total, data, err)
}
// 产能管理 添加产能
func (controller *ProductRecordController) CreateProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
saveCommand := &command.CreateProductCapacitiesCmd{}
controller.Unmarshal(saveCommand)
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.CreateProductCapacities(operateInfo, saveCommand)
controller.Response(data, err)
}
// 产能管理 编辑产能
func (controller *ProductRecordController) UpdateProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
saveCommand := &command.SaveProductCapacitiesCmd{}
controller.Unmarshal(saveCommand)
productRecordId, _ := controller.GetInt(":productRecordId")
saveCommand.ProductRecordId = productRecordId
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.SaveProductCapacities(operateInfo, saveCommand)
controller.Response(data, err)
}
// 产能管理 产能列表
func (controller *ProductRecordController) ListProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
listQury := &query.ListProductCapacitiesQuery{}
controller.Unmarshal(listQury)
operateInfo := ParseOperateInfo(controller.BaseController)
listQury.CompanyId = operateInfo.CompanyId
listQury.OrgId = operateInfo.OrgId
total, data, err := productRecordService.ListProductCapacities(operateInfo, listQury)
ResponseGrid(controller.BaseController, total, data, err)
}
// 产能管理 产能详情
func (controller *ProductRecordController) GetProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
productRecordId, _ := controller.GetInt(":productRecordId")
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.GetProductCapacities(operateInfo, productRecordId)
controller.Response(data, err)
}
// 产能管理 删除产能
func (controller *ProductRecordController) DeleteProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
productRecordId, _ := controller.GetInt(":productRecordId")
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.DeleteProductCapacities(operateInfo, productRecordId)
controller.Response(data, err)
}
// 产能管理 审核产能
func (controller *ProductRecordController) ApproveProductCapacities() {
productRecordService := service.NewProductRecordService(nil)
queryCommand := &query.GetProductCapacitiesQuery{}
controller.Unmarshal(queryCommand)
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productRecordService.ApproveProductCapacities(operateInfo, queryCommand.EmployeeProductRecordId)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productTrouble/service"
)
type ProductTroubleController struct {
beego.BaseController
}
// 创建事故记录
func (c *ProductTroubleController) CreatedProductTrouble() {
srv := service.NewProductTroubleService(nil)
createCommand := &command.CreateProductTroubleCommand{}
Must(c.Unmarshal(createCommand))
operater := ParseOperateInfo(c.BaseController)
data, err := srv.CreateProductTrouble(operater, createCommand)
c.Response(data, err)
}
// 更新事故记录
func (c *ProductTroubleController) UpdateProductTrouble() {
srv := service.NewProductTroubleService(nil)
createCommand := &command.SaveProductTroubleCommand{}
Must(c.Unmarshal(createCommand))
id, _ := c.GetInt(":id")
createCommand.Id = id
operater := ParseOperateInfo(c.BaseController)
data, err := srv.SaveProductTrouble(operater, createCommand)
c.Response(data, err)
}
// 获取事故记录
func (c *ProductTroubleController) GetProductTrouble() {
srv := service.NewProductTroubleService(nil)
id, _ := c.GetInt(":id")
data, err := srv.GetProductTrouble(id)
c.Response(data, err)
}
// 删除事故记录
func (c *ProductTroubleController) DeleteProductTrouble() {
srv := service.NewProductTroubleService(nil)
getQuery := &query.GetProductTroubleQuery{}
Must(c.Unmarshal(getQuery))
err := srv.DeleteProductTrouble(int64(getQuery.Id))
c.Response(nil, err)
}
// 获取事故记录列表
func (c *ProductTroubleController) ListProductTrouble() {
srv := service.NewProductTroubleService(nil)
getQuery := query.ListProductTrouble{}
Must(c.Unmarshal(&getQuery))
operater := ParseOperateInfo(c.BaseController)
getQuery.CompanyId = operater.CompanyId
getQuery.OrgId = operater.OrgId
total, data, err := srv.ListProductTrouble(&getQuery)
ResponseGrid(c.BaseController, total, data, err)
}
// 审核事故记录
func (c *ProductTroubleController) ApproveProductTrouble() {
srv := service.NewProductTroubleService(nil)
getQuery := &query.GetProductTroubleQuery{}
Must(c.Unmarshal(getQuery))
operater := ParseOperateInfo(c.BaseController)
err := srv.ApproveProductTrouble(operater, int64(getQuery.Id))
c.Response(nil, err)
}
func (c *ProductTroubleController) ListRewardSummary() {
srv := service.NewProductTroubleService(nil)
getQuery := query.ListRewardSummaryQuery{}
Must(c.Unmarshal(&getQuery))
operater := ParseOperateInfo(c.BaseController)
getQuery.CompanyId = operater.CompanyId
getQuery.OrgId = operater.OrgId
total, data, err := srv.ListRewardSummary(&getQuery)
ResponseGrid(c.BaseController, total, data, err)
}
// 功过看板 日榜
func (c *ProductTroubleController) RewardSummaryPublicNoticeDay() {
srv := service.NewProductTroubleService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.RewardSummaryPublicNoticeDay(operater)
c.Response(data, err)
}
// 功过看板 产效
func (c *ProductTroubleController) RewardSummaryPublicNoticeYield() {
srv := service.NewProductTroubleService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.RewardSummaryPublicNoticeYield(operater)
c.Response(data, err)
}
// 功过看板 合格率
func (c *ProductTroubleController) RewardSummaryPublicNoticeUpToStandard() {
srv := service.NewProductTroubleService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.RewardSummaryPublicNoticeUpToStandard(operater)
c.Response(data, err)
}
// 功过看板 异常
func (c *ProductTroubleController) RewardSummaryPublicNoticeAccident() {
srv := service.NewProductTroubleService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.RewardSummaryPublicNoticeAccident(operater)
c.Response(data, err)
}
// 功过看板 月榜
func (c *ProductTroubleController) RewardSummaryPublicNoticeMonth() {
srv := service.NewProductTroubleService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.RewardSummaryPublicNoticeMonth(operater)
c.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/rewardStandard/service"
)
type RewardStandardController struct {
beego.BaseController
}
// 创建奖惩标准
func (c *RewardStandardController) CreatedRewardStandard() {
srv := service.NewRewardStandardService(nil)
createCommand := &command.SaveRewardStandardCommand{}
Must(c.Unmarshal(createCommand))
operater := ParseOperateInfo(c.BaseController)
data, err := srv.SaveRewardStandard(operater, createCommand)
c.Response(data, err)
}
// 更新奖惩标准
func (c *RewardStandardController) UpdateRewardStandard() {
srv := service.NewRewardStandardService(nil)
createCommand := &command.SaveRewardStandardCommand{}
Must(c.Unmarshal(createCommand))
id, _ := c.GetInt(":id")
createCommand.Id = id
operater := ParseOperateInfo(c.BaseController)
data, err := srv.SaveRewardStandard(operater, createCommand)
c.Response(data, err)
}
// 获取奖惩标准
func (c *RewardStandardController) GetRewardStandard() {
srv := service.NewRewardStandardService(nil)
id, _ := c.GetInt(":id")
getQuery := &query.GetRewardStandard{
Id: id,
}
operater := ParseOperateInfo(c.BaseController)
data, err := srv.GetRewardStandard(operater, getQuery)
c.Response(data, err)
}
// 删除奖惩标准
func (c *RewardStandardController) DeleteRewardStandard() {
srv := service.NewRewardStandardService(nil)
getQuery := &query.GetRewardStandard{}
Must(c.Unmarshal(getQuery))
operater := ParseOperateInfo(c.BaseController)
data, err := srv.DeleteRewardStandard(operater, getQuery)
c.Response(data, err)
}
// 列表展示奖惩标准
func (c *RewardStandardController) ListRewardStandard() {
srv := service.NewRewardStandardService(nil)
cmd := &query.ListRewardStandard{}
Must(c.Unmarshal(cmd))
operateInfo := ParseOperateInfo(c.BaseController)
cmd.CompanyId = operateInfo.CompanyId
total, data, err := srv.ListRewardStandard(cmd)
ResponseGrid(c.BaseController, total, data, err)
}
// SaveRewardRule 保存奖惩规则
func (c *RewardStandardController) SaveRewardRule() {
srv := service.NewRewardStandardService(nil)
createCommand := &command.SaveRewardRuleCommand{}
Must(c.Unmarshal(createCommand))
operater := ParseOperateInfo(c.BaseController)
data, err := srv.SaveRewardRule(operater, createCommand)
c.Response(data, err)
}
// GetRewardRule 获取奖惩规则
func (c *RewardStandardController) GetRewardRule() {
srv := service.NewRewardStandardService(nil)
operater := ParseOperateInfo(c.BaseController)
data, err := srv.GetRewardRule(operater)
c.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/controllers"
)
func init() {
web.Router("/workshop-public-notice/workshop", &controllers.BoardDataController{}, "Get:WorkshopDesc")
web.Router("/workshop-public-notice/employee/workpiece-ratio", &controllers.BoardDataController{}, "Get:EmployeeWorkpieceRatio")
web.Router("/workshop-public-notice/section-product-info", &controllers.BoardDataController{}, "Get:TimeSectionProductRecord")
web.Router("/workshop-public-notice/proportion-of-second-level", &controllers.BoardDataController{}, "Get:ProportionOfSecondLevel")
web.Router("/workshop-public-notice/top-show", &controllers.BoardDataController{}, "Get:TopShow")
web.Router("/workshop-public-notice/product_plan", &controllers.BoardDataController{}, "Get:ProductPlan")
web.Router("/workshop-public-notice/workshop-plan-completion/current", &controllers.BoardDataController{}, "Get:WorkshopPlanCompletionCurrent")
web.Router("/workshop-public-notice/workshop-plan-completion/5day", &controllers.BoardDataController{}, "Get:WorkshopPlanCompletion5Day")
}
... ...
... ... @@ -9,4 +9,5 @@ func init() {
web.Router("/file-import", &controllers.ExcelDataController{}, "Post:FileImport")
web.Router("/file-export", &controllers.ExcelDataController{}, "Post:FileExport")
web.Router("/file-import-template/:code", &controllers.ExcelDataController{}, "Get:FileImportTemplate")
}
... ...
... ... @@ -18,4 +18,19 @@ func init() {
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")
//产能管理 列表
web.Router("/product-records/product-capacities/search", &controllers.ProductRecordController{}, "Post:ListProductCapacities")
//产能管理 添加产能
web.Router("/product-records/product-capacities", &controllers.ProductRecordController{}, "Post:CreateProductCapacities")
//产能管理 编辑产能
web.Router("/product-records/product-capacities/:productRecordId", &controllers.ProductRecordController{}, "Put:UpdateProductCapacities")
//产能管理 列表-产能详情
web.Router("/product-records/product-capacities/:productRecordId", &controllers.ProductRecordController{}, "Get:GetProductCapacities")
//产能管理 列表 -删除产能
web.Router("/product-records/product-capacities/:productRecordId", &controllers.ProductRecordController{}, "Delete:DeleteProductCapacities")
//产能管理 列表 -审核产能
web.Router("/product-records/product-capacities/approve", &controllers.ProductRecordController{}, "Post:ApproveProductCapacities")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/controllers"
)
func init() {
web.Router("/product_trouble/", &controllers.ProductTroubleController{}, "Post:CreatedProductTrouble")
web.Router("/product_trouble/:id", &controllers.ProductTroubleController{}, "Put:UpdateProductTrouble")
web.Router("/product_trouble/:id", &controllers.ProductTroubleController{}, "Get:GetProductTrouble")
web.Router("/product_trouble/remove", &controllers.ProductTroubleController{}, "Post:DeleteProductTrouble")
web.Router("/product_trouble/search", &controllers.ProductTroubleController{}, "Post:ListProductTrouble")
web.Router("/product_trouble/approve", &controllers.ProductTroubleController{}, "Post:ApproveProductTrouble")
web.Router("/product_trouble/reward_summary/seach", &controllers.ProductTroubleController{}, "Post:ListRewardSummary")
web.Router("/reward-summary/public-notice/day", &controllers.ProductTroubleController{}, "Get:RewardSummaryPublicNoticeDay")
web.Router("/reward-summary/public-notice/yield", &controllers.ProductTroubleController{}, "Get:RewardSummaryPublicNoticeYield")
web.Router("/reward-summary/public-notice/up-to-standard", &controllers.ProductTroubleController{}, "Get:RewardSummaryPublicNoticeUpToStandard")
web.Router("/reward-summary/public-notice/accident", &controllers.ProductTroubleController{}, "Get:RewardSummaryPublicNoticeAccident")
web.Router("/reward-summary/public-notice/month", &controllers.ProductTroubleController{}, "Get:RewardSummaryPublicNoticeMonth")
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego/controllers"
)
func init() {
web.Router("/reward-standard/", &controllers.RewardStandardController{}, "Post:CreatedRewardStandard")
web.Router("/reward-standard/:id", &controllers.RewardStandardController{}, "Put:UpdateRewardStandard")
web.Router("/reward-standard/:id", &controllers.RewardStandardController{}, "Get:GetRewardStandard")
web.Router("/reward-standard/remove", &controllers.RewardStandardController{}, "Post:DeleteRewardStandard")
web.Router("/reward-standard/search", &controllers.RewardStandardController{}, "Post:ListRewardStandard")
web.Router("/reward-rule/", &controllers.RewardStandardController{}, "Post:SaveRewardRule")
web.Router("/reward-rule/", &controllers.RewardStandardController{}, "Get:GetRewardRule")
}
... ...