作者 yangfu

Merge branch 'feature_material' into test

正在显示 83 个修改的文件 包含 4123 行增加140 行删除

要显示太多修改。

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

select count(*) from manufacture.device_running_record where device_running_record_id <=2000000
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
--1.备份设备运行数据-按数量
-- 备份数据 2000000
select * into table manufacture.device_running_record_0_2000
from manufacture.device_running_record
where device_running_record_id <=2000000
-- 删除数据
delete from manufacture.device_running_record where device_running_record_id <=2000000;
-- 重建索引
reindex table manufacture.device_running_record;
--2.备份设备采集数据-按时间
-- 备份数据 2000000
select * into table manufacture.device_collections_history
from manufacture.device_collections
where created_at <'2022-6-01 16:00:00'
-- 删除数据
delete from manufacture.device_collections where created_at <'2022-6-01 16:00:00';
-- 重建索引
reindex table manufacture.device_collections;
--3.查看备份情况
select count(*) from manufacture.device_running_record_0_2000
select count(*) from manufacture.device_collections_history
select count(*) from manufacture.device_collections where created_at <'2022-6-01 16:00:00'
\ No newline at end of file
... ...
delete FROM "dictionarys" where dictionary_id in (3812266576427090944);
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972873532463383552, 'ACM-001', '天联共创-生产制造-物料属性', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "外购"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "自制"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "委外"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972875981165167616, 'ACM-002', '天联共创-生产制造-物料管理-物料类别', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "原材料"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "半成品"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "成品"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3972882719129994240, 'ACM-003', '天联共创-生产制造-单位', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "千克"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "个"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "包"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "箱"}, {"sort": 5, "isShow": 1, "itemCode": "5", "itemLabel": "", "itemValue": "片"}, {"sort": 6, "isShow": 1, "itemCode": "6", "itemLabel": "", "itemValue": "套"}, {"sort": 7, "isShow": 1, "itemCode": "7", "itemLabel": "", "itemValue": "份"}, {"sort": 8, "isShow": 1, "itemCode": "8", "itemLabel": "", "itemValue": "台"}, {"sort": 9, "isShow": 1, "itemCode": "9", "itemLabel": "", "itemValue": "米"}, {"sort": 10, "isShow": 1, "itemCode": "10", "itemLabel": "", "itemValue": "升"}, {"sort": 11, "isShow": 1, "itemCode": "11", "itemLabel": "", "itemValue": "辆"}, {"sort": 12, "isShow": 1, "itemCode": "12", "itemLabel": "", "itemValue": "秒"}, {"sort": 13, "isShow": 1, "itemCode": "13", "itemLabel": "", "itemValue": "栋"}, {"sort": 14, "isShow": 1, "itemCode": "14", "itemLabel": "", "itemValue": "袋"}, {"sort": 15, "isShow": 1, "itemCode": "15", "itemLabel": "", "itemValue": "kg"}, {"sort": 16, "isShow": 1, "itemCode": "16", "itemLabel": "", "itemValue": "串"}, {"sort": 17, "isShow": 1, "itemCode": "17", "itemLabel": "", "itemValue": "件"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3978995238135399424, 'ACM-004', '天联共创-生产制造-单位换算-物料类别', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "南瓜饼串"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "包装袋(空)"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "包装袋(件数)"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "装箱(件数)"}]');
INSERT INTO "public"."dictionarys"("dictionary_id", "dict_code", "dict_name", "describe", "dict_items") VALUES (3812266576427090944, 'XTZD-003', '生产制造-单位', '', '[{"sort": 1, "isShow": 1, "itemCode": "1", "itemLabel": "", "itemValue": "个"}, {"sort": 2, "isShow": 1, "itemCode": "2", "itemLabel": "", "itemValue": "袋"}, {"sort": 3, "isShow": 1, "itemCode": "3", "itemLabel": "", "itemValue": "kg"}, {"sort": 4, "isShow": 1, "itemCode": "4", "itemLabel": "", "itemValue": "串"}, {"sort": 5, "isShow": 1, "itemCode": "5", "itemLabel": "", "itemValue": "箱"}, {"sort": 6, "isShow": 1, "itemCode": "6", "itemLabel": "", "itemValue": "件"}]');
... ...
-- 表product_material_group 增加唯一索引 idx_unq_product_material_group_company_id_org_id_material_group_number
create UNIQUE INDEX idx_unq_product_material_group_company_id_org_id_material_group_number on manufacture.product_material_group using btree(company_id,org_id,material_group_number,deleted_at);
-- 表product_material 增加唯一索引 idx_unq_product_material_company_id_material_number
create UNIQUE INDEX idx_unq_product_material_company_id_material_number on manufacture.product_material using btree(company_id,material_number,deleted_at);
\ No newline at end of file
... ...
... ... @@ -3,6 +3,7 @@ package main
import (
"fmt"
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
... ... @@ -10,7 +11,6 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/crontab"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
... ...
... ... @@ -60,6 +60,12 @@ func (crontabService *CrontabService) initTask() {
syncProductPlan := task.NewTask("定时同步车间计划", "0 5 * * * *", SyncProductPlan)
task.AddTask("SyncProductPlan", syncProductPlan)
syncMaterialGroup := task.NewTask("定时同步物料分组", "0 0 0/2 * * *", SyncMaterialGroup)
task.AddTask("syncMaterialGroup", syncMaterialGroup)
syncMaterial := task.NewTask("定时同步物料", "0 0 0/2 * * *", SyncMaterial)
task.AddTask("syncMaterial", syncMaterial)
}
func (crontabService *CrontabService) StartCrontabTask() {
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"runtime/debug"
"time"
)
// SyncMaterial 定时同步物料
func SyncMaterial(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料", "stack": string(debug.Stack())})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时同步物料】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
var pullType string = ""
if val := ctx.Value("pullType"); val != nil {
pullType = val.(string)
}
log.Logger.Debug("【定时同步物料】 启动")
pullK3CloudService := syncdata.PullDataK3CloudService{}
if err := pullK3CloudService.SyncDataMaterial(transactionContext.(*pg.TransactionContext), pullType, time.Time{}); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料"})
return nil
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
package crontab
import (
"context"
"fmt"
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"runtime/debug"
)
// SyncMaterialGroup 定时同步物料分组
func SyncMaterialGroup(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "定时同步物料分组", "stack": string(debug.Stack())})
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时同步物料分组】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【定时同步物料分组】 启动")
pullK3CloudService := syncdata.PullDataK3CloudService{}
if err := pullK3CloudService.SyncDataMaterialGroup(transactionContext.(*pg.TransactionContext)); err != nil {
log.Logger.Error(err.Error(), map[string]interface{}{"task": "定时同步物料分组"})
return nil
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
... ... @@ -413,6 +413,58 @@ func FastPgDeviceDailyRunningRecord(transactionContext application.TransactionCo
return rep, mod, err
}
// FastProductMaterialGroup 快速返回物料
//
// transactionContext 事务
// id 对象唯一标识
func FastProductMaterialGroup(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialGroupRepository, *domain.ProductMaterialGroup, error) {
var rep domain.ProductMaterialGroupRepository
var mod *domain.ProductMaterialGroup
var err error
if value, err := CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if id > 0 {
if mod, err = rep.FindOne(map[string]interface{}{"productMaterialGroupId": id}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
return rep, mod, err
}
// FastProductMaterialGroup 快速返回物料
//
// transactionContext 事务
// id 对象唯一标识
func FastProductMaterial(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductMaterialRepository, *domain.ProductMaterial, error) {
var rep domain.ProductMaterialRepository
var mod *domain.ProductMaterial
var err error
if value, err := CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if id > 0 {
if mod, err = rep.FindOne(map[string]interface{}{"productMaterialId": id}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该物料分组不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
return rep, mod, err
}
/***** 2.配置 *****/
type FastOptions struct {
... ...
... ... @@ -141,3 +141,19 @@ func CreateDeviceDailyRunningRecordRepository(options map[string]interface{}) (d
}
return repository.NewDeviceDailyRunningRecordRepository(transactionContext)
}
func CreateProductMaterialGroupRepository(options map[string]interface{}) (domain.ProductMaterialGroupRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewProductMaterialGroupRepository(transactionContext)
}
func CreateProductMaterialRepository(options map[string]interface{}) (domain.ProductMaterialRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewProductMaterialRepository(transactionContext)
}
... ...
... ... @@ -14,19 +14,15 @@ type CreateProductCommand struct {
// 组织ID
OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
// 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode" valid:"Required"`
// 产品名称
ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
// ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 数量(保留两位小数)
//Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"`
// ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// Unit string `cname:"单位" json:"unit" valid:"Required"`
// 单份重量(原材料)
UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
// 重量
//Weight float64 `cname:"重量" json:"weight" valid:"Required"`
}
func (createProductCommand *CreateProductCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -12,19 +12,15 @@ type UpdateProductCommand struct {
// 产品ID
ProductId int `cname:"产品ID" json:"productId" valid:"Required"`
// 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
//ProductCode string `cname:"产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001" json:"productCode"`
// 产品名称
ProductName string `cname:"产品名称" json:"productName" valid:"Required"`
ProductName string `cname:"产品名称" json:"productName" `
// 产品类别
ProductCategory string `cname:"产品类别" json:"productCategory" valid:"Required"`
// 数量(保留两位小数)
//Quantity float64 `cname:"数量(保留两位小数)" json:"quantity" valid:"Required"`
ProductCategory string `cname:"产品类别" json:"productCategory"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
Unit string `cname:"单位" json:"unit"`
// 单份重量(原材料)
UnitWeight float64 `cname:"单份重量(原材料)" json:"unitWeight" valid:"Required"`
// 重量
//Weight float64 `cname:"重量" json:"weight" valid:"Required"`
}
func (updateProductCommand *UpdateProductCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -14,7 +14,6 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
// 产品服务
... ... @@ -22,7 +21,7 @@ type ProductService struct {
}
// 创建产品服务
func (productService *ProductService) CreateProduct(createProductCommand *command.CreateProductCommand) (interface{}, error) {
func (productService *ProductService) CreateProduct(opt *domain.OperateInfo, createProductCommand *command.CreateProductCommand) (interface{}, error) {
if err := createProductCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
... ... @@ -37,50 +36,23 @@ func (productService *ProductService) CreateProduct(createProductCommand *comman
transactionContext.RollbackTransaction()
}()
if len(createProductCommand.ProductCode) == 0 {
generator := redis.NewProductCodeCache(createProductCommand.CompanyId)
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
createProductCommand.ProductCode = code
batchAddProductService, _ := domainService.NewPGBatchAddProductService(transactionContext.(*pgTransaction.TransactionContext))
item := &domain.ImportProductItem{
ProductCode: createProductCommand.ProductCode,
UnitWeight: utils.AssertString(createProductCommand.UnitWeight),
}
var userService = domainService.NewUserService()
var org *domain.Org
org, err = userService.Organization(createProductCommand.OrgId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
if _, err = batchAddProductService.BatchAddProduct(opt, []*domain.ImportProductItem{
item,
}, false); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
newProduct := &domain.Product{
CompanyId: createProductCommand.CompanyId,
OrgId: createProductCommand.OrgId,
ProductCode: createProductCommand.ProductCode,
ProductName: createProductCommand.ProductName,
ProductCategory: createProductCommand.ProductCategory,
ProductSpec: &domain.UnitQuantity{
Unit: createProductCommand.Unit,
UnitWeight: createProductCommand.UnitWeight,
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
productRepository, _, _ := factory.FastPgProduct(transactionContext, 0)
if item, err := productRepository.FindOne(map[string]interface{}{"companyId": createProductCommand.CompanyId, "productCode": createProductCommand.ProductCode}); err == nil && item != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交")
if len(item.FailReason) > 0 {
return nil, application.ThrowError(application.TRANSACTION_ERROR, item.FailReason)
}
if product, err := productRepository.Save(newProduct); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return product, nil
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 返回产品服务
... ... @@ -242,7 +214,7 @@ func (productService *ProductService) BatchRemoveProduct(cmd *command.BatchRemov
}
// 更新产品服务
func (productService *ProductService) UpdateProduct(updateProductCommand *command.UpdateProductCommand) (interface{}, error) {
func (productService *ProductService) UpdateProduct(opt *domain.OperateInfo, updateProductCommand *command.UpdateProductCommand) (interface{}, error) {
if err := updateProductCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
... ... @@ -260,19 +232,11 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(updateProductCommand.ProductCode) == 0 {
generator := redis.NewProductCodeCache(product.CompanyId)
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
updateProductCommand.ProductCode = code
}
if updateProductCommand.ProductCode != product.ProductCode {
if item, err := productRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "productCode": updateProductCommand.ProductCode}); err == nil && item != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "产品编号重复,请重新提交")
}
var material *domain.ProductMaterial
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
if material, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": product.CompanyId, "materialNumber": product.ProductCode}); err != nil || material == nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "物料不存在")
}
var userService = domainService.NewUserService()
... ... @@ -281,8 +245,13 @@ func (productService *ProductService) UpdateProduct(updateProductCommand *comman
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
updateProductCommand.ProductName = material.MaterialName
updateProductCommand.Unit = material.ProductMaterialExt.Unit
updateProductCommand.ProductCategory = material.MaterialCategory.Category
data := tool_funs.SimpleStructToMap(updateProductCommand)
data["orgName"] = org.OrgName
if err := product.Update(data); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type BatchRemoveProductMaterialCommand struct {
// 物料ID们
ProductMaterialIds []int `cname:"物料ID" json:"productMaterialIds" valid:"Required"`
}
func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (batchRemoveProductMaterialCommand *BatchRemoveProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchRemoveProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchRemoveProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
"reflect"
"regexp"
"strings"
)
type CreateProductMaterialCommand struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId"`
// 组织ID
OrgId int `cname:"组织ID" json:"orgId"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
// 物料编码
MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
// 物料属性
MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
// 规格
Specification string `cname:"规格" json:"specification" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// 保质期 单位:天
ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
// 备注
Remark string `cname:"备注" json:"remark"`
}
func (createProductMaterialCommand *CreateProductMaterialCommand) Valid(validation *validation.Validation) {
createProductMaterialCommand.MaterialNumber = strings.ToUpper(createProductMaterialCommand.MaterialNumber)
match, err := regexp.MatchString("^[A-Z0-9]+$", createProductMaterialCommand.MaterialNumber)
if !match {
validation.Error("物料编码只允许数字加大写字母组合")
return
}
if err != nil {
validation.Error(err.Error())
return
}
if len([]rune(createProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (createProductMaterialCommand *CreateProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveProductMaterialCommand struct {
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
}
func (removeProductMaterialCommand *RemoveProductMaterialCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeProductMaterialCommand *RemoveProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateProductMaterialCommand struct {
// 企业id
//CompanyId int `cname:"企业id" json:"companyId"`
// 组织ID
//OrgId int `cname:"组织ID" json:"orgId"`
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
//// 物料编码
//MaterialNumber string `cname:"物料编码" json:"materialNumber" valid:"Required"`
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName" valid:"Required"`
// 物料属性
MaterialAttribute string `cname:"物料属性" json:"materialAttribute" valid:"Required"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory" valid:"Required"`
// 规格
Specification string `cname:"规格" json:"specification" valid:"Required"`
// 单位
Unit string `cname:"单位" json:"unit" valid:"Required"`
// 保质期 单位:天
ExpiredDay int `cname:"保质期 单位:天" json:"expiredDay"`
// 备注
Remark string `cname:"备注" json:"remark"`
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) Valid(validation *validation.Validation) {
if len([]rune(updateProductMaterialCommand.Specification)) > 50 {
validation.Error("规格最多允许50个字符")
return
}
}
func (updateProductMaterialCommand *UpdateProductMaterialCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateProductMaterialCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateProductMaterialCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
type DtoMaterial struct {
ProductMaterialId int `json:"productMaterialId"` // 物料ID
MaterialNumber string `json:"materialNumber"` //物料编码
MaterialName string `json:"materialName"` //物料名称
Specification string `json:"specification"` //规格型号
MaterialCategory string `json:"materialCategory"` //物料类别
Unit string `json:"unit"` //单位
MaterialAttribute string `json:"materialAttribute"` //物料属性
ProductMaterialGroupId int `json:"productMaterialGroupId"` //物料分组 string/string/string
ExpiredDay int `json:"expiredDay"` //保质期
Remark string `json:"remark"` //备注
ProductMaterialGroups []int `json:"productMaterialGroups"`
}
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
func DtoProductMaterial(productMaterialModel *domain.ProductMaterial) *DtoMaterial {
return &DtoMaterial{
ProductMaterialId: productMaterialModel.ProductMaterialId,
ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
MaterialNumber: productMaterialModel.MaterialNumber,
MaterialName: productMaterialModel.MaterialName,
MaterialAttribute: productMaterialModel.MaterialAttribute.Attribute,
MaterialCategory: productMaterialModel.MaterialCategory.Category,
Specification: productMaterialModel.ProductMaterialExt.Specification,
Remark: productMaterialModel.ProductMaterialExt.Remark,
Unit: productMaterialModel.ProductMaterialExt.Unit,
ExpiredDay: productMaterialModel.ProductMaterialExt.ExpiredDay,
}
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetProductMaterialQuery struct {
// 物料ID
ProductMaterialId int `cname:"物料ID" json:"productMaterialId" valid:"Required"`
}
func (getProductMaterialQuery *GetProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getProductMaterialQuery *GetProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListProductMaterialQuery struct {
PageNumber int64 `json:"pageNumber"`
PageSize int64 `json:"pageSize"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
// 物料分组ID数组
ProductMaterialGroupIds []int
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory"`
CompanyId int
}
func (listProductMaterialQuery *ListProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listProductMaterialQuery *ListProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SearchProductMaterialQuery struct {
PageNumber int64 `json:"pageNumber"`
PageSize int64 `json:"pageSize"`
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId"`
// 物料分组ID数组
ProductMaterialGroupIds []int
// 物料名称
MaterialName string `cname:"物料名称" json:"materialName"`
// 物料类别
MaterialCategory string `cname:"物料类别" json:"materialCategory"`
CompanyId int
}
func (listProductMaterialQuery *SearchProductMaterialQuery) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listProductMaterialQuery *SearchProductMaterialQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"time"
)
// 生产物料服务
type ProductMaterialService struct {
}
// 创建生产物料服务
func (productMaterialService *ProductMaterialService) CreateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.CreateProductMaterialCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newProductMaterial := &domain.ProductMaterial{
CompanyId: cmd.CompanyId,
OrgId: cmd.OrgId,
ProductMaterialGroupId: cmd.ProductMaterialGroupId,
MaterialNumber: cmd.MaterialNumber,
MaterialName: cmd.MaterialName,
MaterialAttribute: &domain.MaterialAttribute{Attribute: cmd.MaterialAttribute},
MaterialCategory: &domain.MaterialCategory{Category: cmd.MaterialCategory},
ProductMaterialExt: &domain.MaterialExt{
Specification: cmd.Specification,
Unit: cmd.Unit,
ExpiredDay: cmd.ExpiredDay,
Remark: cmd.Remark,
},
}
//var productMaterial *domain.ProductMaterial
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if _, err := materialService.AddMaterial(operateInfo, newProductMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 返回生产物料服务单个
func (productMaterialService *ProductMaterialService) GetProductMaterial(operateInfo *domain.OperateInfo, getProductMaterialQuery *query.GetProductMaterialQuery) (interface{}, error) {
if err := getProductMaterialQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"productMaterialId": getProductMaterialQuery.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialQuery.ProductMaterialId)))
} else {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
productMaterialGroupIdNames, _, err := materialService.AllMaterialGroupParentByBacktracking(operateInfo, productMaterial.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if len(productMaterialGroupIdNames) == 0 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var productMaterialGroups []int
for _, productMaterialGroupIdName := range productMaterialGroupIdNames {
productMaterialGroups = append(productMaterialGroups, productMaterialGroupIdName.ProductMaterialGroupId)
}
one := dto.DtoProductMaterial(productMaterial)
one.ProductMaterialGroups = productMaterialGroups
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return one, nil
}
}
// 返回生产物料服务列表,未用
func (productMaterialService *ProductMaterialService) ListProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.ListProductMaterialQuery) (interface{}, error) {
if err := listProductMaterialQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
var results []*dto.DtoMaterial
if listProductMaterialQuery.ProductMaterialGroupId != 0 {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
}
listProductMaterialQuery.CompanyId = operateInfo.CompanyId
if count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
for _, productMaterial := range productMaterials {
results = append(results, dto.DtoProductMaterial(productMaterial))
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"productMaterials": results,
}, nil
}
}
// 返回生产物料服务列表
func (productMaterialService *ProductMaterialService) SearchProductMaterial(operateInfo *domain.OperateInfo, listProductMaterialQuery *query.SearchProductMaterialQuery) (int64, []*dto.DtoMaterial, error) {
if err := listProductMaterialQuery.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
results := make([]*dto.DtoMaterial, 0)
if listProductMaterialQuery.ProductMaterialGroupId != 0 {
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
_, ProductMaterialGroupIds, err := materialService.AllMaterialGroupChild(operateInfo, listProductMaterialQuery.ProductMaterialGroupId)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
listProductMaterialQuery.ProductMaterialGroupIds = ProductMaterialGroupIds
}
listProductMaterialQuery.CompanyId = operateInfo.CompanyId
count, productMaterials, err := productMaterialRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialQuery))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
for _, productMaterial := range productMaterials {
results = append(results, dto.DtoProductMaterial(productMaterial))
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, results, err
}
// 移除生产物料服务
func (productMaterialService *ProductMaterialService) RemoveProductMaterial(operateInfo *domain.OperateInfo, removeProductMaterialCommand *command.RemoveProductMaterialCommand) (interface{}, error) {
if err := removeProductMaterialCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": removeProductMaterialCommand.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeProductMaterialCommand.ProductMaterialId)))
}
if productMaterial, err := productMaterialRepository.Remove(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterial, nil
}
}
// 更新生产物料服务
func (productMaterialService *ProductMaterialService) UpdateProductMaterial(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": cmd.ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
productMaterial.ProductMaterialGroupId = cmd.ProductMaterialGroupId
productMaterial.MaterialName = cmd.MaterialName
productMaterial.MaterialAttribute.Attribute = cmd.MaterialAttribute
productMaterial.MaterialCategory.Category = cmd.MaterialCategory
productMaterial.ProductMaterialExt = &domain.MaterialExt{
Specification: cmd.Specification,
Unit: cmd.Unit,
ExpiredDay: cmd.ExpiredDay,
Remark: cmd.Remark,
}
productMaterial.UpdatedAt = time.Now()
if _, err := productMaterialRepository.Save(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 批量移除生产物料服务
func (productMaterialService *ProductMaterialService) BatchRemoveProductMaterial(operateInfo *domain.OperateInfo, batchRemoveProductMaterialCommand *command.BatchRemoveProductMaterialCommand) (interface{}, error) {
if err := batchRemoveProductMaterialCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialRepository domain.ProductMaterialRepository
if value, err := factory.CreateProductMaterialRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialRepository = value
}
for i := range batchRemoveProductMaterialCommand.ProductMaterialIds {
ProductMaterialId := batchRemoveProductMaterialCommand.ProductMaterialIds[i]
productMaterial, err := productMaterialRepository.FindOne(map[string]interface{}{"companyId": operateInfo.CompanyId, "productMaterialId": ProductMaterialId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterial == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(ProductMaterialId)))
}
if _, err := productMaterialRepository.Remove(productMaterial); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewProductMaterialService(options map[string]interface{}) *ProductMaterialService {
newProductMaterialService := &ProductMaterialService{}
return newProductMaterialService
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type CreateProductMaterialGroupCommand struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
// 组织ID
OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
// 父级ID
Pid int `cname:"父级ID" json:"pid"`
// 物料分组名称
MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
// 物料分组编码
MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber,omitempty"`
}
func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (createProductMaterialGroupCommand *CreateProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(createProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type RemoveProductMaterialGroupCommand struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
}
func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (removeProductMaterialGroupCommand *RemoveProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(removeProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type UpdateProductMaterialGroupCommand struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
// 物料分组名称
MaterialGroupName string `cname:"物料分组名称" json:"materialGroupName" valid:"Required"`
// 物料分组编码
MaterialGroupNumber string `cname:"物料分组编码" json:"materialGroupNumber"`
}
func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) Valid(validation *validation.Validation) {
}
func (updateProductMaterialGroupCommand *UpdateProductMaterialGroupCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateProductMaterialGroupCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(updateProductMaterialGroupCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package dto
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
type MaterialGroupDto struct {
// 物料分组ID
ProductMaterialGroupId int `json:"id"`
// 企业id
//CompanyId int `json:"companyId"`
// 组织ID
//OrgId int `json:"orgId"`
// 父级ID
Pid int `json:"pid"`
// 路径 (不使用,如果父级改变的话,子级的Path要做更新)
//Path string `json:"path"`
// 物料分组名称
MaterialGroupName string `json:"materialGroupName"`
// 物料分组编码
MaterialGroupNumber string `json:"materialGroupNumber"`
}
func (d *MaterialGroupDto) LoadDto(m *domain.ProductMaterialGroup, orgId int) *MaterialGroupDto {
d.ProductMaterialGroupId = m.ProductMaterialGroupId
d.Pid = m.Pid
d.MaterialGroupName = m.MaterialGroupName
d.MaterialGroupNumber = m.MaterialGroupNumber
return d
}
func (productMaterialGroup *MaterialGroupDto) PID() string {
return fmt.Sprintf("%d", productMaterialGroup.Pid)
}
func (productMaterialGroup *MaterialGroupDto) ID() string {
return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
}
type MaterialGroupDtos []*MaterialGroupDto
func (tree MaterialGroupDtos) Len() int {
return len(tree)
}
func (tree MaterialGroupDtos) Less(i, j int) bool {
if tree[i].Pid < tree[j].Pid {
return true
}
if tree[i].Pid == tree[j].Pid {
return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
}
return false
}
func (tree MaterialGroupDtos) Swap(i, j int) {
tree[i], tree[j] = tree[j], tree[i]
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type GetProductMaterialGroupQuery struct {
// 物料分组ID
ProductMaterialGroupId int `cname:"物料分组ID" json:"productMaterialGroupId" valid:"Required"`
}
func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) Valid(validation *validation.Validation) {
}
func (getProductMaterialGroupQuery *GetProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getProductMaterialGroupQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(getProductMaterialGroupQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type ListProductMaterialGroupQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
// 查询限制
Limit int `cname:"查询限制" json:"limit" valid:"Required"`
}
func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) Valid(validation *validation.Validation) {
}
func (listProductMaterialGroupQuery *ListProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductMaterialGroupQuery)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductMaterialGroupQuery).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SearchProductMaterialGroupQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
Limit int `cname:"查询限制" json:"limit"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 当前登录的组织
//OrgId int `cname:"当前登录的组织" json:"orgId,omitempty"`
// 匹配多个组织
//InOrgIds []int `cname:"匹配多个组织" json:"inOrgIds,omitempty" valid:"Required"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
}
func (cmd *SearchProductMaterialGroupQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
}
func (cmd *SearchProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package query
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SelectorProductMaterialGroupQuery struct {
// 查询偏离量
//Offset int `cname:"查询偏离量" json:"offset"`
// 查询限制
//Limit int `cname:"查询限制" json:"limit"`
// options 'tree' 'list' default tree
Style string `json:"style"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 页码
//PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
//PageSize int `cname:"页数" json:"pageSize,omitempty"`
}
func (cmd *SelectorProductMaterialGroupQuery) Valid(validation *validation.Validation) {
//cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
cmd.Style = "tree"
}
func (cmd *SelectorProductMaterialGroupQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package service
import (
"fmt"
"github.com/linmadan/egglib-go/core/application"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"sort"
)
// 物料分组服务
type ProductMaterialGroupService struct {
}
// 创建物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) CreateProductMaterialGroup(operateInfo *domain.OperateInfo, createProductMaterialGroupCommand *command.CreateProductMaterialGroupCommand) (interface{}, error) {
if err := createProductMaterialGroupCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newProductMaterialGroup := &domain.ProductMaterialGroup{
Pid: createProductMaterialGroupCommand.Pid,
MaterialGroupName: createProductMaterialGroupCommand.MaterialGroupName,
MaterialGroupNumber: createProductMaterialGroupCommand.MaterialGroupNumber,
}
var productMaterialGroup *domain.ProductMaterialGroup
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if productMaterialGroup, err = materialService.AddMaterialGroup(operateInfo, newProductMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterialGroup, nil
}
// 返回物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) GetProductMaterialGroup(getProductMaterialGroupQuery *query.GetProductMaterialGroupQuery) (interface{}, error) {
if err := getProductMaterialGroupQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
productMaterialGroup, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"productMaterialGroupId": getProductMaterialGroupQuery.ProductMaterialGroupId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterialGroup == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductMaterialGroupQuery.ProductMaterialGroupId)))
}
//测试
//materialService,_:= domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
//nodes,child,_:=materialService.AllMaterialGroupChild(&domain.OperateInfo{CompanyId: productMaterialGroup.CompanyId},productMaterialGroup.ProductMaterialGroupId)
//log.Logger.Debug("节点的Child", map[string]interface{}{"data":child,"nodes":nodes})
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
materialGroupDto := dto.MaterialGroupDto{}
return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
}
// 返回物料分组服务列表
func (productMaterialGroupService *ProductMaterialGroupService) ListProductMaterialGroup(listProductMaterialGroupQuery *query.ListProductMaterialGroupQuery) (interface{}, error) {
if err := listProductMaterialGroupQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
if count, productMaterialGroups, err := productMaterialGroupRepository.Find(tool_funs.SimpleStructToMap(listProductMaterialGroupQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"productMaterialGroups": productMaterialGroups,
}, nil
}
}
// 移除物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) RemoveProductMaterialGroup(removeProductMaterialGroupCommand *command.RemoveProductMaterialGroupCommand) (interface{}, error) {
if err := removeProductMaterialGroupCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
if value, err := factory.CreateProductMaterialGroupRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productMaterialGroupRepository = value
}
productMaterialGroup, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"productMaterialGroupId": removeProductMaterialGroupCommand.ProductMaterialGroupId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productMaterialGroup == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("已删除 %s", string(removeProductMaterialGroupCommand.ProductMaterialGroupId)))
}
if productMaterialGroup, err := productMaterialGroupRepository.Remove(productMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productMaterialGroup, nil
}
}
// 更新物料分组服务
func (productMaterialGroupService *ProductMaterialGroupService) UpdateProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *command.UpdateProductMaterialGroupCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
productMaterialGroup := &domain.ProductMaterialGroup{
ProductMaterialGroupId: cmd.ProductMaterialGroupId,
MaterialGroupName: cmd.MaterialGroupName,
//MaterialGroupNumber: cmd.MaterialGroupNumber,
}
materialService, _ := domainService.NewPGMaterialService(transactionContext.(*pgTransaction.TransactionContext))
if productMaterialGroup, err := materialService.UpdateMaterialGroup(operateInfo, productMaterialGroup); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
materialGroupDto := dto.MaterialGroupDto{}
return materialGroupDto.LoadDto(productMaterialGroup, 0), nil
}
}
// 搜索物料分组服务列表
func (productMaterialGroupService *ProductMaterialGroupService) SearchProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SearchProductMaterialGroupQuery) (int64, interface{}, error) {
if err := cmd.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
queryOptions := utils.ObjectToMap(cmd)
count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var results = make([]*dto.MaterialGroupDto, 0)
for i := range productGroups {
newItem := &dto.MaterialGroupDto{}
newItem.LoadDto(productGroups[i], operateInfo.OrgId)
results = append(results, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, results, nil
}
func (productMaterialGroupService *ProductMaterialGroupService) SelectorProductMaterialGroup(operateInfo *domain.OperateInfo, cmd *query.SelectorProductMaterialGroupQuery) (int64, interface{}, error) {
if err := cmd.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productMaterialGroupRepository domain.ProductMaterialGroupRepository
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(transactionContext, 0)
queryOptions := utils.ObjectToMap(cmd)
count, productGroups, err := productMaterialGroupRepository.Find(queryOptions)
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var results = make([]*dto.MaterialGroupDto, 0)
for i := range productGroups {
newItem := &dto.MaterialGroupDto{}
newItem.LoadDto(productGroups[i], operateInfo.OrgId)
results = append(results, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if cmd.Style == "tree" {
sort.Stable(dto.MaterialGroupDtos(results))
nodes := make([]utils.TreeNode, 0)
for i := range results {
nodes = append(nodes, results[i])
}
tree := utils.NewTree(nodes)
return count, tree.Nodes, nil
}
return count, results, nil
}
func NewProductMaterialGroupService(options map[string]interface{}) *ProductMaterialGroupService {
newProductMaterialGroupService := &ProductMaterialGroupService{}
return newProductMaterialGroupService
}
... ...
package syncdata
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
... ... @@ -209,6 +210,101 @@ func (srv *PullDataK3CloudService) PullMaterial(timeFilter time.Time) error {
return nil
}
func (srv *PullDataK3CloudService) pullMaterial(timeFilter time.Time) ([]models.MaterialK3cloud, error) {
//拉取数据
var filterString []string
if !timeFilter.IsZero() {
str := timeFilter.Format("2006-01-02T15:04:05")
filterString = append(filterString, "FModifyDate>='"+str+"'")
}
client, err := newK3cloudClient()
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fieldKeys := []string{
"FMATERIALID", "FSpecification", "FName", "FNumber",
"FDocumentStatus", "FForbidStatus", "FErpClsID",
"FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
"FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName", "FCategoryID",
}
var (
startRow int
allResult []map[string]string
queryErr error
)
for {
result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
FormId: "BD_MATERIAL",
Data: k3cloud.ExecuteBillQueryData{
FormId: "BD_MATERIAL",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
StartRow: startRow,
Limit: 1000,
FilterString: strings.Join(filterString, " and "),
},
})
if err != nil {
queryErr = err
break
}
mp := result.ToMapString()
if len(mp) == 0 {
break
}
allResult = append(allResult, mp...)
startRow += 1000
}
if queryErr != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
materialModels []models.MaterialK3cloud
materialTemp models.MaterialK3cloud
)
nowTime := time.Now()
for _, item := range allResult {
materialId, err := strconv.Atoi(item["FMATERIALID"])
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fErpClsID, _ := strconv.Atoi(item["FErpClsID"])
fBaseUnitId, _ := strconv.Atoi(item["FBaseUnitId"])
materialGroup, _ := strconv.Atoi(item["MaterialGroup"])
fUseOrgId, _ := strconv.Atoi(item["FUseOrgId"])
refStatus, _ := strconv.Atoi(item["RefStatus"])
fCreateDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FCreateDate"])
fModifyDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FModifyDate"])
fForbidDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FForbidDate"])
fApproveDate, _ := time.Parse("2006-01-02T15:04:05.999", item["FApproveDate"])
materialTemp = models.MaterialK3cloud{
MaterialId: materialId,
Name: item["FName"],
Number: item["FNumber"],
Specification: item["FSpecification"],
ForbidStatus: item["FForbidStatus"],
ErpClsId: fErpClsID,
BaseUnitId: fBaseUnitId,
BaseUnitName: item["FBaseUnitId.FName"],
CreateDate: fCreateDate,
ModifyDate: fModifyDate,
ForbidDate: fForbidDate,
ApproveDate: fApproveDate,
MaterialGroup: materialGroup,
MaterialGroupNumber: item["FMaterialGroup.FNumber"],
MaterialGroupName: item["FMaterialGroup.FName"],
RefStatus: refStatus,
UseOrgId: fUseOrgId,
UseOrgName: item["FUseOrgId.FName"],
JoinProductId: 0,
DataVersion: nowTime.Unix(),
FCategoryID: item["FCategoryID"],
}
materialModels = append(materialModels, materialTemp)
}
return materialModels, nil
}
//PullMaterialGroup 拉取物料分组
func (srv *PullDataK3CloudService) PullMaterialGroup() error {
client, err := newK3cloudClient()
... ... @@ -462,6 +558,33 @@ func (srv *PullDataK3CloudService) PullPrdMo(timeFilter time.Time) error {
return nil
}
// PullMaterialCategory 拉取物料分类
func (srv *PullDataK3CloudService) PullMaterialCategory() (map[string]string, error) {
client, err := newK3cloudClient()
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fieldKeys := []string{
"FName", "FNUMBER", "FMasterId",
}
result, err := client.ExecuteBillQuery(k3cloud.RequestExecuteBillQuery{
FormId: "BD_MATERIALCATEGORY",
Data: k3cloud.ExecuteBillQueryData{
FormId: "BD_MATERIALCATEGORY",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
//TopRowCount: 4,
FilterString: "",
},
})
categorys := result.ToMapString()
var categorysById = make(map[string]string)
for _, v := range categorys {
categorysById[v["FMasterId"]] = v["FName"]
}
return categorysById, nil
}
// 同步产品
func (srv *PullDataK3CloudService) SyncDataProduct(ptr *pgTransaction.TransactionContext, fromTime time.Time) error {
prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
... ... @@ -612,3 +735,165 @@ func (srv *PullDataK3CloudService) SyncDataProductPlan(ptr *pgTransaction.Transa
}
return nil
}
// 同步产品
func (srv *PullDataK3CloudService) SyncDataMaterialGroup(ptr *pgTransaction.TransactionContext) error {
prdMoDao, err := dao.NewMaterialK3cloudDao(ptr)
if err != nil {
return err
}
var userService = domainService.NewUserService()
org, err := userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
fromMaterialGroups, err := prdMoDao.SearchMaterialGroup() // 默认企业名称素天下、或者使用组织ID
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
cid = constant.MANUFACTURE_DEFAULT_COMPANYID
oid = constant.MANUFACTURE_DEFAULT_ORGID
)
productMaterialGroupRepository, _, _ := factory.FastProductMaterialGroup(ptr, 0)
_, materialGroups, err := productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
if err != nil {
return err
}
mapMaterialGroups := domain.ProductMaterialGroups(materialGroups).ToMapByGroupNumber()
mapFromMaterialGroups := models.MaterialGroupK3clouds(fromMaterialGroups).ToMapId()
for _, from := range fromMaterialGroups {
to, ok := mapMaterialGroups[from.Number]
if ok {
// 更新
if to.MaterialGroupName != from.Name {
log.Logger.Info(fmt.Sprintf("更新物料分组 old:%v new:%v", to.MaterialGroupName, from.Name), map[string]interface{}{"material": to})
to.MaterialGroupName = from.Name
}
continue
}
var parentId int
if from.ParentId > 0 {
parent, ok := mapFromMaterialGroups[from.ParentId]
if !ok {
log.Logger.Warn("parent node not exits", map[string]interface{}{"material": to})
continue
}
toParent, ok := mapMaterialGroups[parent.Number]
if !ok {
log.Logger.Warn("to parent node not exits", map[string]interface{}{"material": to})
continue
}
parentId = toParent.ProductMaterialGroupId
}
productMaterialGroup := &domain.ProductMaterialGroup{
CompanyId: cid,
OrgId: oid,
Pid: parentId,
MaterialGroupName: from.Name,
MaterialGroupNumber: from.Number,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
if productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup); err != nil {
return err
}
mapMaterialGroups[productMaterialGroup.MaterialGroupNumber] = productMaterialGroup
}
return nil
}
// SyncDataMaterial 同步物料数据
// pullType 拉取数据方式 full:全量 其他:增量
func (srv *PullDataK3CloudService) SyncDataMaterial(ptr *pgTransaction.TransactionContext, pullType string, fromTime time.Time) error {
var (
lastTime = utils.GetZeroTime(time.Now()).Add(-time.Hour * 24) //前一天有修改的记录
org *domain.Org
err error
)
if pullType == "full" {
lastTime = time.Time{}
}
var userService = domainService.NewUserService()
org, err = userService.Organization(constant.MANUFACTURE_DEFAULT_ORGID)
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var (
cid = constant.MANUFACTURE_DEFAULT_COMPANYID
oid = constant.MANUFACTURE_DEFAULT_ORGID
productMaterialRepository, _, _ = factory.FastProductMaterial(ptr, 0)
productMaterialGroupRepository, _, _ = factory.FastProductMaterialGroup(ptr, 0)
materialGroups domain.ProductMaterialGroups
)
_, materialGroups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": cid})
if err != nil {
return err
}
mapMaterialGroup := materialGroups.ToMapByGroupNumber()
records, err := srv.pullMaterial(lastTime)
if err != nil {
return err
}
mapMaterialCategory, err := srv.PullMaterialCategory()
if err != nil {
return err
}
log.Logger.Debug(fmt.Sprintf("【同步物料数据】查询数据条数:%v", len(records)))
_, materialsFromDb, _ := productMaterialRepository.Find(map[string]interface{}{"companyId": cid, "limit": 20000})
mapMaterialsFromDb := domain.ProductMaterials(materialsFromDb).ToMapByNumber()
for index, item := range records {
var (
material *domain.ProductMaterial
materialGroup *domain.ProductMaterialGroup
ok bool
attribute string //物料属性
category string //物料类别
)
if item.UseOrgName != "素天下" {
continue
}
if materialGroup, ok = mapMaterialGroup[item.MaterialGroupNumber]; !ok {
continue
}
if _, ok := mapMaterialsFromDb[item.Number]; ok {
continue
}
if v, ok := mapMaterialCategory[item.FCategoryID]; ok {
category = v
}
attribute = domain.MaterialAttributeDescription(item.ErpClsId)
material = &domain.ProductMaterial{
CompanyId: cid,
OrgId: oid,
ProductMaterialGroupId: materialGroup.ProductMaterialGroupId,
MaterialName: item.Name,
MaterialNumber: item.Number,
MaterialAttribute: &domain.MaterialAttribute{Attribute: attribute},
MaterialCategory: &domain.MaterialCategory{Category: category},
ProductMaterialExt: &domain.MaterialExt{
Specification: item.Specification,
Unit: item.BaseUnitName,
ExpiredDay: 0,
Remark: "",
Source: "k3cloud",
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName),
}
if material, err = productMaterialRepository.Save(material); err != nil {
log.Logger.Debug(fmt.Sprintf("同步失败 序号:%v 物料数据 id:%v number:%v name:%v 错误:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName, err.Error()))
continue
}
log.Logger.Debug(fmt.Sprintf("同步 序号:%v 物料数据 id:%v number:%v name:%v", index, material.ProductMaterialId, material.MaterialNumber, material.MaterialName))
}
return nil
}
... ...
... ... @@ -13,10 +13,13 @@ type MaterialUnitConversionDto struct {
ToUnitQuantity *domain.UnitQuantity `json:"toUnitQuantity,omitempty"`
}
func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion) *MaterialUnitConversionDto {
func (d *MaterialUnitConversionDto) LoadDto(m *domain.UnitConversion, material *domain.ProductMaterial) *MaterialUnitConversionDto {
d.UnitConversionId = m.UnitConversionId
d.MaterialName = m.Material.MaterialName
d.FromUnitQuantity = m.FromUnitQuantity
d.ToUnitQuantity = m.ToUnitQuantity
if material != nil {
d.MaterialName = material.MaterialName
}
return d
}
... ...
... ... @@ -25,7 +25,7 @@ type UnitConversionDto struct {
AuthFlag bool `json:"authFlag"`
}
func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitConversionDto {
func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int, productMaterial *domain.ProductMaterial) *UnitConversionDto {
d.UnitConversionId = m.UnitConversionId
d.WorkStation = m.WorkStation
d.Material = m.Material
... ... @@ -36,5 +36,8 @@ func (d *UnitConversionDto) LoadDto(m *domain.UnitConversion, orgId int) *UnitCo
if m.Ext != nil {
d.OrgName = m.Ext.OrgName
}
if productMaterial != nil {
d.Material.MaterialName = productMaterial.MaterialName
}
return d
}
... ...
... ... @@ -91,12 +91,21 @@ func (unitConversionService *UnitConversionService) GetUnitConversion(getUnitCon
//var unitConversionRepository domain.UnitConversionRepository
var unitConversion *domain.UnitConversion
_, unitConversion, err = factory.FastPgUnitConversion(transactionContext, getUnitConversionQuery.UnitConversionId)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var productMaterial *domain.ProductMaterial
if unitConversion.Material.ProductMaterialId > 0 {
_, productMaterial, err = factory.FastProductMaterial(transactionContext, unitConversion.Material.ProductMaterialId)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
result := &dto.UnitConversionDto{}
result.LoadDto(unitConversion, 0)
result.LoadDto(unitConversion, 0, productMaterial)
return result, nil
}
... ... @@ -293,17 +302,29 @@ func (unitConversionService *UnitConversionService) SearchUnitConversion(operate
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
if len(productMaterialIds) > 0 {
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
}
var result = make([]*dto.UnitConversionDto, 0)
for i := range unitConversions {
item := unitConversions[i]
newItem := &dto.UnitConversionDto{}
newItem.LoadDto(item, operateInfo.OrgId)
newItem.LoadDto(item, operateInfo.OrgId, mapProductMaterial[item.Material.ProductMaterialId])
result = append(result, newItem)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, result, nil
}
... ... @@ -331,11 +352,22 @@ func (unitConversionService *UnitConversionService) SearchMaterial(operateInfo *
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var mapProductMaterial = make(map[int]*domain.ProductMaterial, 0)
productMaterialIds := domain.UnitConversions(unitConversions).ProductMaterialIds()
if len(productMaterialIds) > 0 {
productMaterialRepository, _, _ := factory.FastProductMaterial(transactionContext, 0)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"productMaterialIds": productMaterialIds})
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapProductMaterial = domain.ProductMaterials(productMaterials).ToMapById()
}
var result = make([]*dto.MaterialUnitConversionDto, 0)
for i := range unitConversions {
item := unitConversions[i]
newItem := &dto.MaterialUnitConversionDto{}
newItem.LoadDto(item)
newItem.LoadDto(item, mapProductMaterial[item.Material.ProductMaterialId])
result = append(result, newItem)
}
return count, map[string]interface{}{
... ...
... ... @@ -7,6 +7,8 @@ import (
const MaxQueryRow = 10000
const PathSegment = ","
// 班次
const (
WorkOnFullDay = 1 //全天
... ...
... ... @@ -2,6 +2,9 @@ package domain
// 冗余附加数据
type Ext struct {
// 操作人
Operator *User `json:"operator,omitempty"`
// 组织名称
OrgName string `json:"orgName,omitempty"`
... ... @@ -35,3 +38,8 @@ func (e *Ext) WithProductPlanExt(ext *ProductPlanExt) *Ext {
e.ProductPlanExt = ext
return e
}
func (e *Ext) WithOperator(ext *User) *Ext {
e.Operator = ext
return e
}
... ...
... ... @@ -2,8 +2,36 @@ package domain
// 物料
type Material struct {
// 物料名称
// 物料ID
ProductMaterialId int `json:"productMaterialId"`
// 物料名称 (最新数据需要查询物料表)
MaterialName string `json:"materialName,omitempty"`
// 物料类别
// 物料类别 ‘南瓜饼串’、‘ 包装袋(空)’、‘包装袋(件数)’、装箱(件数)
MaterialCategory string `json:"materialCategory,omitempty"`
}
// 物料类别
type MaterialCategory struct {
//Id int `json:"id"`
Category string `json:"category"`
}
// 物料属性
type MaterialAttribute struct {
//Id int `json:"id"`
Attribute string `json:"attribute"`
}
// 物料扩展数据
type MaterialExt struct {
// 规格
Specification string `json:"specification"`
// 单位
Unit string `json:"unit"`
// 保质期 单位:天
ExpiredDay int `json:"expiredDay"`
// 备注
Remark string `json:"remark"`
// 来源 k3cloud
Source string `json:"source"`
}
... ...
... ... @@ -2,6 +2,7 @@ package domain
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"strconv"
"time"
)
... ... @@ -99,15 +100,18 @@ type ImportProductItem struct {
}
func (item *ImportProductItem) Valid() error {
if len(item.ProductName) == 0 {
return fmt.Errorf("品名不能为空")
}
if len(item.Unit) == 0 {
return fmt.Errorf("规格不能为空")
}
if len(item.ProductCategory) == 0 {
return fmt.Errorf("类别不能为空")
if len(item.ProductCode) == 0 {
return fmt.Errorf("产品编号不能为空")
}
//if len(item.ProductName) == 0 {
// return fmt.Errorf("品名不能为空")
//}
//if len(item.Unit) == 0 {
// return fmt.Errorf("规格不能为空")
//}
//if len(item.ProductCategory) == 0 {
// return fmt.Errorf("类别不能为空")
//}
if len(item.UnitWeight) == 0 {
item.UnitWeight = "0"
}
... ... @@ -116,3 +120,13 @@ func (item *ImportProductItem) Valid() error {
}
return nil
}
type Products []*Product
func (products Products) ProductCodes() []string {
var result = utils.NewSet()
for _, v := range products {
result.Add(v.ProductCode)
}
return result.KeysStr()
}
... ...
package domain
import "time"
// 生产物料
type ProductMaterial struct {
// 物料ID
ProductMaterialId int `json:"productMaterialId"`
// 企业id
CompanyId int `json:"companyId"`
// 组织ID
OrgId int `json:"orgId"`
// 物料分组ID
ProductMaterialGroupId int `json:"productMaterialGroupId"`
// 物料编码
MaterialNumber string `json:"materialNumber"`
// 物料名称
MaterialName string `json:"materialName"`
// 物料属性
MaterialAttribute *MaterialAttribute `json:"materialAttribute"`
// 物料类别
MaterialCategory *MaterialCategory `json:"materialCategory"`
// 物料扩展
ProductMaterialExt *MaterialExt `json:"productMaterialExt"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 扩展
Ext *Ext `json:"ext"`
}
type ProductMaterialRepository interface {
Save(productMaterial *ProductMaterial) (*ProductMaterial, error)
Remove(productMaterial *ProductMaterial) (*ProductMaterial, error)
FindOne(queryOptions map[string]interface{}) (*ProductMaterial, error)
Find(queryOptions map[string]interface{}) (int64, []*ProductMaterial, error)
}
func (productMaterial *ProductMaterial) Identify() interface{} {
if productMaterial.ProductMaterialId == 0 {
return nil
}
return productMaterial.ProductMaterialId
}
func (productMaterial *ProductMaterial) Update(data map[string]interface{}) error {
return nil
}
type ProductMaterials []*ProductMaterial
func (productMaterials ProductMaterials) ToMapById() map[int]*ProductMaterial {
var mapProductMaterial = make(map[int]*ProductMaterial, 0)
for _, v := range productMaterials {
mapProductMaterial[v.ProductMaterialId] = v
}
return mapProductMaterial
}
func (productMaterials ProductMaterials) ToMapByNumber() map[string]*ProductMaterial {
var mapProductMaterial = make(map[string]*ProductMaterial, 0)
for _, v := range productMaterials {
mapProductMaterial[v.MaterialNumber] = v
}
return mapProductMaterial
}
// 10:资产,9:配置,2:自制,11:费用,12:模型,5:虚拟,7:一次性,13:产品系列 12:模型,3:委外,4:特征,6:服务,1:外购
var mapMaterialCategory = map[int]string{
1: "外购",
2: "自制",
3: "委外",
4: "特征",
5: "虚拟",
6: "服务",
7: "一次性",
8: "",
9: "配置",
10: "资产",
11: "费用",
12: "模型",
13: "产品系列",
}
func MaterialAttributeDescription(code int) string {
if v, ok := mapMaterialCategory[code]; ok {
return v
}
return ""
}
... ...
package domain
import (
"fmt"
"strconv"
"time"
)
// 物料分组
type ProductMaterialGroup struct {
// 物料分组ID
ProductMaterialGroupId int `json:"productMaterialGroupId"`
// 企业id
CompanyId int `json:"companyId"`
// 组织ID
OrgId int `json:"orgId"`
// 父级ID
Pid int `json:"pid"`
// 路径 (不使用,如果父级改变的话,子级的Path要做更新)
//Path string `json:"path"`
// 物料分组名称
MaterialGroupName string `json:"materialGroupName"`
// 物料分组编码
MaterialGroupNumber string `json:"materialGroupNumber"`
// 创建时间
CreatedAt time.Time `json:"createdAt"`
// 更新时间
UpdatedAt time.Time `json:"updatedAt"`
// 删除时间
DeletedAt time.Time `json:"deletedAt"`
// 扩展数据
Ext *Ext `json:"ext,omitempty"`
}
type ProductMaterialGroupRepository interface {
Save(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
Remove(productMaterialGroup *ProductMaterialGroup) (*ProductMaterialGroup, error)
FindOne(queryOptions map[string]interface{}) (*ProductMaterialGroup, error)
Find(queryOptions map[string]interface{}) (int64, []*ProductMaterialGroup, error)
}
func (productMaterialGroup *ProductMaterialGroup) Identify() interface{} {
if productMaterialGroup.ProductMaterialGroupId == 0 {
return nil
}
return productMaterialGroup.ProductMaterialGroupId
}
func (productMaterialGroup *ProductMaterialGroup) Update(data map[string]interface{}) error {
return nil
}
func (productMaterialGroup *ProductMaterialGroup) GroupNumberComposeUp(parent *ProductMaterialGroup, latestNumber string, total int) string {
iNumber, err := strconv.ParseInt(latestNumber, 10, 64)
if err == nil {
iNumber += 1
return formatFunc(iNumber)
}
if parent != nil {
return parent.MaterialGroupNumber + formatFunc(int64(total+1))
}
return formatFunc(int64(total + 1))
}
func formatFunc(iNumber int64) string {
sNumber := fmt.Sprintf("%d", iNumber)
if len(sNumber)%2 == 1 {
return "0" + sNumber
}
return sNumber
}
/***** 1.实现树 *****/
func (productMaterialGroup *ProductMaterialGroup) PID() string {
return fmt.Sprintf("%d", productMaterialGroup.Pid)
}
func (productMaterialGroup *ProductMaterialGroup) ID() string {
return fmt.Sprintf("%d", productMaterialGroup.ProductMaterialGroupId)
}
type ProductMaterialGroups []*ProductMaterialGroup
func (tree ProductMaterialGroups) Len() int {
return len(tree)
}
func (tree ProductMaterialGroups) Less(i, j int) bool {
if tree[i].Pid < tree[j].Pid {
return true
}
if tree[i].Pid == tree[j].Pid {
return tree[i].ProductMaterialGroupId < tree[j].ProductMaterialGroupId
}
return false
}
func (tree ProductMaterialGroups) Swap(i, j int) {
tree[i], tree[j] = tree[j], tree[i]
}
func (tree ProductMaterialGroups) ToMapByGroupNumber() map[string]*ProductMaterialGroup {
var result = make(map[string]*ProductMaterialGroup)
for i := range tree {
result[tree[i].MaterialGroupNumber] = tree[i]
}
return result
}
... ...
package domain
import "time"
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
)
// 单位换算
type UnitConversion struct {
... ... @@ -57,3 +60,16 @@ func (unitConversion *UnitConversion) Update(data map[string]interface{}) error
unitConversion.UpdatedAt = time.Now()
return nil
}
type UnitConversions []*UnitConversion
func (unitConversions UnitConversions) ProductMaterialIds() []int {
set := utils.NewSet()
for i := range unitConversions {
if unitConversions[i].Material.ProductMaterialId == 0 {
continue
}
set.Add(unitConversions[i].Material.ProductMaterialId)
}
return set.KeysInt()
}
... ...
... ... @@ -25,7 +25,6 @@ func (dao *DeviceDailyRunningRecordDao) TimeSectionRunningRecord(companyId, orgI
tx := dao.transactionContext.PgTx
sql := fmt.Sprintf(`
WITH ts_product as(
select sum(a.weight) total,a.ts from (
select
... ... @@ -38,7 +37,7 @@ WITH ts_product as(
and work_station->>'workshopId'='?'
and work_station->>'lineId'='?'
and work_station->>'sectionName'=?
and created_at >?
and created_at >=?
and created_at <?
) a
group by a.ts
... ... @@ -47,14 +46,14 @@ WITH ts_product as(
-- select * from ts_product
, ts_product_list as (
select d.ts,ts_product.total from (
select to_char(c.ts::timestamp,'mm-dd') ts from (
select generate_series(to_timestamp(?),to_timestamp(?),'1 day') ts
select to_char(c.ts,'mm-dd') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai',to_timestamp(?,'YYYY-MM-DD HH24:MI:SS') at time ZONE 'Asia/shanghai','1 day') ts
) c ) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total
from ts_product_list
`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime.Unix(), endTime.Unix()); err != nil {
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime); err != nil {
return err
}
return nil
... ... @@ -120,7 +119,7 @@ select * from device_running_oee
}
// 时段产能
func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, result interface{}) error {
func (dao *DeviceDailyRunningRecordDao) TimeSectionProductRecord(companyId, orgId, workshopId int, lineId int, sectionName string, beginTime time.Time, endTime time.Time, result interface{}) error {
tx := dao.transactionContext.PgTx
sql := fmt.Sprintf(`
... ... @@ -137,7 +136,8 @@ WITH ts_product as(
and work_station->>'lineId'='?'
and work_station->>'sectionName'=?
and device_running_record_info->>'deviceType'='CCJ'
and created_at >?
and created_at >=?
and created_at < ?
) a
group by a.ts
order by ts
... ... @@ -145,19 +145,15 @@ WITH ts_product as(
-- select * from ts_product
, ts_product_list as (
select d.ts,ts_product.total from (
select to_char(c.ts::timestamp,'HH24:MI') ts from (
select generate_series(a.end - interval '5 hour',
"replace"(to_char(a.end, 'yyyy-mm-dd HH24:') || cast(date_part('minute',a.end) as integer)/30*30+30, ':0', ':00')::timestamp,
'30 minute') ts from (
select to_timestamp(to_char(now() at time ZONE 'Asia/shanghai','yyyy-mm-dd HH24'),'yyyy-mm-dd HH24') as end
) a
) c
select "replace"(to_char(created_at at time ZONE 'Asia/shanghai', 'HH24:') || cast(date_part('minute',created_at) as integer)/30*30, ':0', ':00') ts from (
select generate_series(to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),to_timestamp(?,'YYYY-MM-DD HH24:MI:SS'),'30 minute') created_at
) a
) d left join ts_product on d.ts = ts_product.ts
)
SELECT ts, coalesce(total,0) total
from ts_product_list
`)
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime); err != nil {
if _, err := tx.Query(result, sql, companyId, orgId, workshopId, lineId, sectionName, beginTime, endTime, beginTime, endTime.Add(-time.Minute*1)); err != nil {
return err
}
return nil
... ...
... ... @@ -178,3 +178,13 @@ func (d *MaterialK3cloudDao) GetLastVersion() (int64, error) {
}
return materialData[0].DataVersion, nil
}
func (d *MaterialK3cloudDao) SearchMaterialGroup() ([]*models.MaterialGroupK3cloud, error) {
var materialData []*models.MaterialGroupK3cloud
query := d.transactionContext.PgTx.Model(&materialData)
query.OrderExpr("number asc")
if err := query.Select(); err != nil {
return nil, err
}
return materialData, nil
}
... ...
... ... @@ -170,3 +170,18 @@ func (d *PrdMoK3cloudDao) GetLatestData(fromTime time.Time) ([]*models.PrdMoK3cl
}
return result, nil
}
// GetLatestMaterialData 增量获取物料数据
func (d *PrdMoK3cloudDao) GetLatestMaterialData(fromTime time.Time, offset, limit int) ([]*models.MaterialK3cloud, int, error) {
m := new(models.MaterialK3cloud)
result := make([]*models.MaterialK3cloud, 0)
query := d.transactionContext.PgTx.Model(m)
if !fromTime.IsZero() {
query.Where("modify_date>=?", fromTime)
}
err := query.Select(&result)
if err != nil {
return nil, 0, err
}
return result, len(result), nil
}
... ...
package dao
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
type ProductMaterialGroupDao struct {
transactionContext *pgTransaction.TransactionContext
}
func (dao *ProductMaterialGroupDao) CurrentGroupLatestNumber(companyId int, productMaterialGroupId int) (string, int, error) {
m := new(models.ProductMaterialGroup)
var result string
var total int
query := dao.transactionContext.PgTx.Model(m).Where("company_id = ?", companyId)
query.Where("pid = ?", productMaterialGroupId)
query.ColumnExpr("max(material_group_number) number")
query.ColumnExpr("count(material_group_number) total")
query.AllWithDeleted()
err := query.Select(&result, &total)
return result, total, err
}
func NewProductMaterialGroupDao(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialGroupDao{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -3,6 +3,6 @@ package domainService
import "testing"
func TestSectionProductive(t *testing.T) {
svr := NewByteBankService()
svr.SectionProductive()
//svr := NewByteBankService()
//svr.SectionProductive()
}
... ...
... ... @@ -6,8 +6,8 @@ import (
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"strconv"
"time"
... ... @@ -36,10 +36,22 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var generator = redis.NewProductCodeCache(opt.CompanyId)
var materials domain.ProductMaterials
if materials, err = ptr.GetProductMaterialByImportItems(opt.CompanyId, list); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
mapMaterials := materials.ToMapByNumber()
for i := range list {
item := list[i]
if v, ok := mapMaterials[item.ProductCode]; !ok {
item.FailReason = "导入的产品编号不存在"
failRows = append(failRows, item)
continue
} else {
item.Unit = v.ProductMaterialExt.Unit
item.ProductName = v.MaterialName
item.ProductCategory = v.MaterialCategory.Category
}
if err := item.Valid(); err != nil {
item.FailReason = err.Error()
failRows = append(failRows, item)
... ... @@ -69,14 +81,6 @@ func (ptr *PGBatchAddProductService) BatchAddProduct(opt *domain.OperateInfo, li
continue
}
}
if len(newItem.ProductCode) == 0 {
code, err := redis.GenCode(generator)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
}
newItem.ProductCode = code
}
if _, ok := mapProduct[newItem.ProductCode]; !ok {
mapProduct[newItem.ProductCode] = newItem
... ... @@ -105,6 +109,28 @@ func (ptr *PGBatchAddProductService) updateProduct(opt *domain.OperateInfo, item
return nil
}
func (ptr *PGBatchAddProductService) GetProductMaterialByProductCodes(companyId int, productCodes []string) ([]*domain.ProductMaterial, error) {
productMaterialRepository, _ := repository.NewProductMaterialRepository(ptr.transactionContext)
_, productMaterials, err := productMaterialRepository.Find(map[string]interface{}{"companyId": companyId, "materialNumbers": productCodes})
return productMaterials, err
}
func (ptr *PGBatchAddProductService) GetProductMaterialByImportItems(companyId int, list []*domain.ImportProductItem) ([]*domain.ProductMaterial, error) {
productCodes := ptr.GetProductCodesByImportItems(list)
if len(productCodes) == 0 {
return []*domain.ProductMaterial{}, nil
}
return ptr.GetProductMaterialByProductCodes(companyId, productCodes)
}
func (ptr *PGBatchAddProductService) GetProductCodesByImportItems(list []*domain.ImportProductItem) []string {
var result = utils.NewSet()
for _, v := range list {
result.Add(v.ProductCode)
}
return result.KeysStr()
}
func NewPGBatchAddProductService(transactionContext *pgTransaction.TransactionContext) (*PGBatchAddProductService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -94,11 +94,19 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
}
productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
var response = make([]interface{}, 0)
var tmpXData = make([]string, 0)
var (
response = make([]interface{}, 0)
tmpXData = make([]string, 0)
beginTime = xtime.BeginningOfDay() //time.Now().Add(-time.Hour*5)
endTime = time.Now()
)
if !xtime.IsZero(request.Date.Time()) && !request.Date.Time().Equal(beginTime) {
beginTime = request.Date.Time().AddDate(0, 0, -1)
endTime = request.Date.Time()
}
for _, v := range workshop.GetProductLines(domain.NotDeleted) {
var result = make([]*record, 0)
if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, time.Now().Add(-time.Hour*5), &result); err != nil {
if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beginTime, endTime, &result); err != nil {
log.Logger.Error(err.Error())
continue
}
... ... @@ -123,10 +131,10 @@ func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[
}
type HourProductiveStatisticsRequest struct {
CompanyId int `json:"companyId" valid:"Required"`
OrgId int `json:"orgId" valid:"Required"`
WorkshopId int `json:"workshopId" valid:"Required"`
Date time.Time `json:"date"`
CompanyId int `json:"companyId" valid:"Required"`
OrgId int `json:"orgId" valid:"Required"`
WorkshopId int `json:"workshopId" valid:"Required"`
Date utils.TimeString `json:"date"`
}
func NewXYData(xData []string, values interface{}) interface{} {
... ... @@ -141,7 +149,7 @@ func NewXYData(xData []string, values interface{}) interface{} {
return values
}
// 时段产能-统计 (传串设备)
// DailyProductiveStatistics 每日产能-统计 (传串设备)
func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) {
var request = &HourProductiveStatisticsRequest{}
if err := utils.LoadQueryObject(queryOptions, request); err != nil {
... ... @@ -153,9 +161,13 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
Ts string `json:"ts"`
Total float64 `json:"total"`
}
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
var (
beingTime = xtime.BeginningOfDay().AddDate(0, 0, -6)
endTime = xtime.BeginningOfDay().AddDate(0, 0, 1).Add(-time.Second)
)
if !xtime.IsZero(time.Time(request.Date)) {
beingTime = request.Date.Time().AddDate(0, 0, -6)
endTime = request.Date.Time().AddDate(0, 0, 1).Add(-time.Second)
}
workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
if err != nil || workshop == nil {
... ... @@ -168,7 +180,7 @@ func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map
for _, v := range workshop.GetProductLines(domain.NotDeleted) {
var result = make([]*record, 0)
if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, date.Add(-time.Hour*24*7), date, &result); err != nil {
if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, beingTime, endTime, &result); err != nil {
log.Logger.Error(err.Error())
continue
}
... ... @@ -213,8 +225,8 @@ func (ptr *PGCommonStatisticsService) ProportionOfSecondLevelStatistics(queryOpt
}
productRecordDao, _ := dao.NewProductRecordDao(ptr.transactionContext)
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
if !xtime.IsZero(time.Time(request.Date)) {
date = request.Date.Time()
}
var input = []struct {
name string
... ... @@ -262,8 +274,8 @@ func (ptr *PGCommonStatisticsService) WorkshopProductionEfficiencyStatistics(que
}
productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)
var date = time.Now()
if !xtime.IsZero(request.Date) {
date = request.Date
if !xtime.IsZero(time.Time(request.Date)) {
date = time.Time(request.Date)
}
var input = []struct {
name string
... ...
package domainService
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"sort"
"time"
)
type PGMaterialService struct {
transactionContext *pgTransaction.TransactionContext
}
// 物料
func (ptr *PGMaterialService) AddMaterial(opt *domain.OperateInfo, item *domain.ProductMaterial) (*domain.ProductMaterial, error) {
var (
user *domain.User
org *domain.Org
err error
newProductMaterial *domain.ProductMaterial
productMaterialRepository, _ = repository.NewProductMaterialRepository(ptr.transactionContext)
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
_, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId})
if err != nil {
return nil, err
}
if newProductMaterial, err = productMaterialRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialNumber": item.MaterialNumber}); err == nil || newProductMaterial != nil {
return nil, fmt.Errorf("物料编码已存在")
}
newProductMaterial = &domain.ProductMaterial{
CompanyId: item.CompanyId,
OrgId: item.OrgId,
ProductMaterialGroupId: item.ProductMaterialGroupId,
MaterialName: item.MaterialName,
MaterialNumber: item.MaterialNumber,
MaterialAttribute: item.MaterialAttribute,
MaterialCategory: item.MaterialCategory,
ProductMaterialExt: item.ProductMaterialExt,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithOperator(user),
}
return productMaterialRepository.Save(newProductMaterial)
}
// 物料分组
func (ptr *PGMaterialService) AddMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
var (
user *domain.User
org *domain.Org
err error
parent *domain.ProductMaterialGroup
newProductMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
productMaterialGroupDao *dao.ProductMaterialGroupDao
latestNumber string
total int
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
if item.Pid != 0 {
if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
return nil, fmt.Errorf("上级物料分组不存在")
}
}
if newProductMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || newProductMaterialGroup != nil {
return nil, fmt.Errorf("物料分组编码已存在")
}
productMaterialGroupDao, _ = dao.NewProductMaterialGroupDao(ptr.transactionContext)
latestNumber, total, err = productMaterialGroupDao.CurrentGroupLatestNumber(opt.CompanyId, item.Pid)
if err != nil {
return nil, err
}
newProductMaterialGroup = &domain.ProductMaterialGroup{
CompanyId: opt.CompanyId,
OrgId: opt.OrgId,
Pid: item.Pid,
//Path: item.GetPath(parent),
MaterialGroupName: item.MaterialGroupName,
MaterialGroupNumber: item.MaterialGroupNumber,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Ext: domain.NewExt(org.OrgName).WithOperator(user),
}
newProductMaterialGroup.MaterialGroupNumber = newProductMaterialGroup.GroupNumberComposeUp(parent, latestNumber, total)
newProductMaterialGroup, err = productMaterialGroupRepository.Save(newProductMaterialGroup)
return newProductMaterialGroup, err
}
func (ptr *PGMaterialService) UpdateMaterialGroup(opt *domain.OperateInfo, item *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
var (
user *domain.User
org *domain.Org
err error
//parent *domain.ProductMaterialGroup
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
)
if user, err = NewUserService().User(opt.UserId); err != nil {
return nil, err
}
if org, err = NewUserService().Organization(opt.OrgId); err != nil {
return nil, err
}
//if item.ProductMaterialGroupId == item.Pid {
// return nil, fmt.Errorf("当前物料分组不能做为自己上级")
//}
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.ProductMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, fmt.Errorf("物料分组不存在")
}
//if item.Pid != productMaterialGroup.ProductMaterialGroupId && item.Pid != 0 {
// if parent, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": item.Pid}); err != nil || parent == nil {
// return nil, fmt.Errorf("上级物料分组不存在")
// }
//}
//if productMaterialGroup.MaterialGroupNumber != item.MaterialGroupNumber {
// if group, err := productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "materialGroupNumber": item.MaterialGroupNumber}); err == nil || group != nil {
// return nil, fmt.Errorf("物料分组编码已存在")
// }
//}
//productMaterialGroup.MaterialGroupNumber = item.MaterialGroupNumber
productMaterialGroup.MaterialGroupName = item.MaterialGroupName
productMaterialGroup.UpdatedAt = item.UpdatedAt
productMaterialGroup.Ext = domain.NewExt(org.OrgName).WithOperator(user)
productMaterialGroup, err = productMaterialGroupRepository.Save(productMaterialGroup)
return productMaterialGroup, err
}
func (ptr *PGMaterialService) AllMaterialGroupChild(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
groups domain.ProductMaterialGroups
)
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
_, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
if len(groups) == 0 || err != nil {
return nil, listId, err
}
// 先排序 sort pid,id asc
sort.Stable(groups)
var treeNodes = make([]utils.TreeNode, len(groups))
for i := 0; i < len(groups); i++ {
treeNodes[i] = groups[i]
}
tree := utils.NewTree(treeNodes)
child := tree.AllChildNode(productMaterialGroup)
var result = make([]*domain.ProductMaterialGroup, 0)
for i := range child {
if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
result = append(result, v)
listId = append(listId, v.ProductMaterialGroupId)
}
}
return result, listId, err
}
func (ptr *PGMaterialService) AllMaterialGroupParent(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
groups domain.ProductMaterialGroups
)
if productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": productMaterialGroupId}); err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
_, groups, err = productMaterialGroupRepository.Find(map[string]interface{}{"companyId": opt.CompanyId}) //,"orderByProductMaterialGroupId":"asc"
if len(groups) == 0 || err != nil {
return nil, listId, err
}
// 先排序 sort pid,id asc
sort.Stable(groups)
var treeNodes = make([]utils.TreeNode, len(groups))
for i := 0; i < len(groups); i++ {
treeNodes[i] = groups[i]
}
tree := utils.NewTree(treeNodes)
child := tree.TreeNodePaths(productMaterialGroup)
var result = make([]*domain.ProductMaterialGroup, 0)
for i := range child {
if v, ok := child[i].(*domain.ProductMaterialGroup); ok {
result = append(result, v)
listId = append(listId, v.ProductMaterialGroupId)
}
}
return result, listId, err
}
func (ptr *PGMaterialService) AllMaterialGroupParentByBacktracking(opt *domain.OperateInfo, productMaterialGroupId int) ([]*domain.ProductMaterialGroup, []int, error) {
var (
err error
listId []int
productMaterialGroup *domain.ProductMaterialGroup
productMaterialGroupRepository, _ = repository.NewProductMaterialGroupRepository(ptr.transactionContext)
pid = productMaterialGroupId
mapExists = make(map[int]int)
)
var result = make([]*domain.ProductMaterialGroup, 0)
for {
if pid == 0 {
break
}
if _, exists := mapExists[pid]; exists {
break
}
mapExists[pid] = pid
productMaterialGroup, err = productMaterialGroupRepository.FindOne(map[string]interface{}{"companyId": opt.CompanyId, "productMaterialGroupId": pid, "allWithDeleted": "1"})
if err != nil || productMaterialGroup == nil {
return nil, listId, fmt.Errorf("物料分组不存在")
}
pid = productMaterialGroup.Pid
result = append([]*domain.ProductMaterialGroup{productMaterialGroup}, result...)
}
return result, listId, err
}
func NewPGMaterialService(transactionContext *pgTransaction.TransactionContext) (*PGMaterialService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PGMaterialService{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -67,7 +67,7 @@ func (ptr *PGWorkerAttendanceReportService) Report(cid, oid int, report *domain.
productCalendar, _ = productCalendarRepository.FindOne(map[string]interface{}{"companyId": cid, "orgId": oid, "workStationId": workStation.WorkStationId})
}
beginTime := report.ActionTime.Add(-time.Hour * 13)
beginTime := report.ActionTime.Add(-time.Hour * 16)
endTime := report.ActionTime
_, records, _ := attendanceRecordDao.WorkerAttendanceRecords(cid, oid, worker.UserId, "", beginTime, endTime)
for i := 0; i < len(records); i++ {
... ...
... ... @@ -48,6 +48,8 @@ func init() {
(*models.DeviceDailyRunningRecord)(nil),
(*models.DeviceRunningRecord)(nil),
(*models.WorkshopPlanCompletionRecord)(nil),
(*models.ProductMaterialGroup)(nil),
(*models.ProductMaterial)(nil),
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
... ...
... ... @@ -9,3 +9,13 @@ type MaterialGroupK3cloud struct {
ParentId int `comment:"父级id" pg:"parent_id"`
DataVersion int64 `comment:"数据版本" pg:"data_version"`
}
type MaterialGroupK3clouds []*MaterialGroupK3cloud
func (materialGroupK3clouds MaterialGroupK3clouds) ToMapId() map[int]*MaterialGroupK3cloud {
var result = make(map[int]*MaterialGroupK3cloud)
for i := range materialGroupK3clouds {
result[materialGroupK3clouds[i].Id] = materialGroupK3clouds[i]
}
return result
}
... ...
... ... @@ -25,6 +25,7 @@ type MaterialK3cloud struct {
UseOrgName string `comment:"使用组织" pg:"use_org_name"`
JoinProductId int64 `comment:"关联的product表id" pg:"join_product_id"`
DataVersion int64 `comment:"数据版本" pg:"data_version"`
FCategoryID string `pg:"-"`
}
//批量处理sql脚本样例
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"time"
)
type ProductMaterial struct {
tableName string `comment:"生产物料" pg:"manufacture.product_material"`
// 物料ID
ProductMaterialId int `comment:"物料ID" pg:"pk:product_material_id"`
// 企业id
CompanyId int `comment:"企业id"`
// 组织ID
OrgId int `comment:"组织ID"`
// 物料分组ID
ProductMaterialGroupId int `comment:"物料分组ID"`
// 物料编码
MaterialNumber string `comment:"物料编码"`
// 物料名称
MaterialName string `comment:"物料名称"`
// 物料属性
MaterialAttribute *domain.MaterialAttribute `comment:"物料属性"`
// 物料类别
MaterialCategory *domain.MaterialCategory `comment:"物料类别"`
// 物料扩展
ProductMaterialExt *domain.MaterialExt `comment:"物料扩展"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
// 扩展
Ext *domain.Ext `comment:"扩展"`
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"time"
)
type ProductMaterialGroup struct {
tableName string `comment:"物料分组" pg:"manufacture.product_material_group"`
// 物料分组ID
ProductMaterialGroupId int `comment:"物料分组ID" pg:"pk:product_material_group_id"`
// 企业id
CompanyId int `comment:"企业id"`
// 组织ID
OrgId int `comment:"组织ID"`
// 父级ID
Pid int `comment:"父级ID"`
// 路径
// Path string `comment:"路径"`
// 物料分组名称
MaterialGroupName string `comment:"物料分组名称"`
// 物料分组编码
MaterialGroupNumber string `comment:"物料分组编码"`
// 创建时间
CreatedAt time.Time `comment:"创建时间"`
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
// 扩展
Ext *domain.Ext `comment:"扩展"`
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
func TransformToProductMaterialDomainModelFromPgModels(productMaterialModel *models.ProductMaterial) (*domain.ProductMaterial, error) {
return &domain.ProductMaterial{
ProductMaterialId: productMaterialModel.ProductMaterialId,
CompanyId: productMaterialModel.CompanyId,
OrgId: productMaterialModel.OrgId,
ProductMaterialGroupId: productMaterialModel.ProductMaterialGroupId,
MaterialNumber: productMaterialModel.MaterialNumber,
MaterialName: productMaterialModel.MaterialName,
MaterialAttribute: productMaterialModel.MaterialAttribute,
MaterialCategory: productMaterialModel.MaterialCategory,
ProductMaterialExt: productMaterialModel.ProductMaterialExt,
CreatedAt: productMaterialModel.CreatedAt,
UpdatedAt: productMaterialModel.UpdatedAt,
DeletedAt: productMaterialModel.DeletedAt,
Ext: productMaterialModel.Ext,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)
func TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel *models.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
return &domain.ProductMaterialGroup{
ProductMaterialGroupId: productMaterialGroupModel.ProductMaterialGroupId,
CompanyId: productMaterialGroupModel.CompanyId,
OrgId: productMaterialGroupModel.OrgId,
Pid: productMaterialGroupModel.Pid,
//Path: productMaterialGroupModel.Path,
MaterialGroupName: productMaterialGroupModel.MaterialGroupName,
MaterialGroupNumber: productMaterialGroupModel.MaterialGroupNumber,
CreatedAt: productMaterialGroupModel.CreatedAt,
UpdatedAt: productMaterialGroupModel.UpdatedAt,
DeletedAt: productMaterialGroupModel.DeletedAt,
Ext: productMaterialGroupModel.Ext,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)
type ProductMaterialGroupRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ProductMaterialGroupRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *ProductMaterialGroupRepository) Save(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
sqlBuildFields := []string{
"product_material_group_id",
"company_id",
"org_id",
"pid",
//"path",
"material_group_name",
"material_group_number",
"created_at",
"updated_at",
"deleted_at",
"ext",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_group_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if productMaterialGroup.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterialGroup.ProductMaterialGroupId,
&productMaterialGroup.CompanyId,
&productMaterialGroup.OrgId,
&productMaterialGroup.Pid,
//&productMaterialGroup.Path,
&productMaterialGroup.MaterialGroupName,
&productMaterialGroup.MaterialGroupNumber,
&productMaterialGroup.CreatedAt,
&productMaterialGroup.UpdatedAt,
&productMaterialGroup.DeletedAt,
&productMaterialGroup.Ext,
),
fmt.Sprintf("INSERT INTO manufacture.product_material_group (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productMaterialGroup.CompanyId,
productMaterialGroup.OrgId,
productMaterialGroup.Pid,
//productMaterialGroup.Path,
productMaterialGroup.MaterialGroupName,
productMaterialGroup.MaterialGroupNumber,
productMaterialGroup.CreatedAt,
productMaterialGroup.UpdatedAt,
productMaterialGroup.Ext,
); err != nil {
return productMaterialGroup, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterialGroup.ProductMaterialGroupId,
&productMaterialGroup.CompanyId,
&productMaterialGroup.OrgId,
&productMaterialGroup.Pid,
//&productMaterialGroup.Path,
&productMaterialGroup.MaterialGroupName,
&productMaterialGroup.MaterialGroupNumber,
&productMaterialGroup.CreatedAt,
&productMaterialGroup.UpdatedAt,
&productMaterialGroup.DeletedAt,
&productMaterialGroup.Ext,
),
fmt.Sprintf("UPDATE manufacture.product_material_group SET %s WHERE product_material_group_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productMaterialGroup.CompanyId,
productMaterialGroup.OrgId,
productMaterialGroup.Pid,
//productMaterialGroup.Path,
productMaterialGroup.MaterialGroupName,
productMaterialGroup.MaterialGroupNumber,
productMaterialGroup.CreatedAt,
productMaterialGroup.UpdatedAt,
productMaterialGroup.Ext,
productMaterialGroup.Identify(),
); err != nil {
return productMaterialGroup, err
}
}
return productMaterialGroup, nil
}
func (repository *ProductMaterialGroupRepository) Remove(productMaterialGroup *domain.ProductMaterialGroup) (*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
productMaterialGroupModel := new(models.ProductMaterialGroup)
productMaterialGroupModel.ProductMaterialGroupId = productMaterialGroup.Identify().(int)
if _, err := tx.Model(productMaterialGroupModel).WherePK().Delete(); err != nil {
return productMaterialGroup, err
}
return productMaterialGroup, nil
}
func (repository *ProductMaterialGroupRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
productMaterialGroupModel := new(models.ProductMaterialGroup)
query := sqlbuilder.BuildQuery(tx.Model(productMaterialGroupModel), queryOptions)
query.SetWhereByQueryOption("product_material_group_id = ?", "productMaterialGroupId")
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("material_group_number = ?", "materialGroupNumber")
if _, ok := queryOptions["allWithDeleted"]; ok {
query.AllWithDeleted()
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productMaterialGroupModel.ProductMaterialGroupId == 0 {
return nil, nil
} else {
return transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel)
}
}
func (repository *ProductMaterialGroupRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductMaterialGroup, error) {
tx := repository.transactionContext.PgTx
var productMaterialGroupModels []*models.ProductMaterialGroup
productMaterialGroups := make([]*domain.ProductMaterialGroup, 0)
query := sqlbuilder.BuildQuery(tx.Model(&productMaterialGroupModels), queryOptions)
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetWhereByQueryOption("company_id = ?", "companyId")
if v, ok := queryOptions["orderByProductMaterialGroupId"]; ok {
query.SetOrderDirect("product_material_group_id", v.(string))
} else {
query.SetOrderDirect("product_material_group_id", "DESC")
}
if count, err := query.SelectAndCount(); err != nil {
return 0, productMaterialGroups, err
} else {
for _, productMaterialGroupModel := range productMaterialGroupModels {
if productMaterialGroup, err := transform.TransformToProductMaterialGroupDomainModelFromPgModels(productMaterialGroupModel); err != nil {
return 0, productMaterialGroups, err
} else {
productMaterialGroups = append(productMaterialGroups, productMaterialGroup)
}
}
return int64(count), productMaterialGroups, nil
}
}
func NewProductMaterialGroupRepository(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialGroupRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialGroupRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)
type ProductMaterialRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *ProductMaterialRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *ProductMaterialRepository) Save(productMaterial *domain.ProductMaterial) (*domain.ProductMaterial, error) {
sqlBuildFields := []string{
"product_material_id",
"company_id",
"org_id",
"product_material_group_id",
"material_number",
"material_name",
"material_attribute",
"material_category",
"product_material_ext",
"created_at",
"updated_at",
"deleted_at",
"ext",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_material_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if productMaterial.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterial.ProductMaterialId,
&productMaterial.CompanyId,
&productMaterial.OrgId,
&productMaterial.ProductMaterialGroupId,
&productMaterial.MaterialNumber,
&productMaterial.MaterialName,
&productMaterial.MaterialAttribute,
&productMaterial.MaterialCategory,
&productMaterial.ProductMaterialExt,
&productMaterial.CreatedAt,
&productMaterial.UpdatedAt,
&productMaterial.DeletedAt,
&productMaterial.Ext,
),
fmt.Sprintf("INSERT INTO manufacture.product_material (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productMaterial.CompanyId,
productMaterial.OrgId,
productMaterial.ProductMaterialGroupId,
productMaterial.MaterialNumber,
productMaterial.MaterialName,
productMaterial.MaterialAttribute,
productMaterial.MaterialCategory,
productMaterial.ProductMaterialExt,
productMaterial.CreatedAt,
productMaterial.UpdatedAt,
productMaterial.Ext,
); err != nil {
return productMaterial, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&productMaterial.ProductMaterialId,
&productMaterial.CompanyId,
&productMaterial.OrgId,
&productMaterial.ProductMaterialGroupId,
&productMaterial.MaterialNumber,
&productMaterial.MaterialName,
&productMaterial.MaterialAttribute,
&productMaterial.MaterialCategory,
&productMaterial.ProductMaterialExt,
&productMaterial.CreatedAt,
&productMaterial.UpdatedAt,
&productMaterial.DeletedAt,
&productMaterial.Ext,
),
fmt.Sprintf("UPDATE manufacture.product_material SET %s WHERE product_material_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productMaterial.CompanyId,
productMaterial.OrgId,
productMaterial.ProductMaterialGroupId,
productMaterial.MaterialNumber,
productMaterial.MaterialName,
productMaterial.MaterialAttribute,
productMaterial.MaterialCategory,
productMaterial.ProductMaterialExt,
productMaterial.CreatedAt,
productMaterial.UpdatedAt,
productMaterial.Ext,
productMaterial.Identify(),
); err != nil {
return productMaterial, err
}
}
return productMaterial, nil
}
func (repository *ProductMaterialRepository) Remove(productMaterial *domain.ProductMaterial) (*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
productMaterialModel := new(models.ProductMaterial)
productMaterialModel.ProductMaterialId = productMaterial.Identify().(int)
if _, err := tx.Model(productMaterialModel).WherePK().Delete(); err != nil {
return productMaterial, err
}
return productMaterial, nil
}
// query compose
// 1. company_id,material_number
func (repository *ProductMaterialRepository) FindOne(queryOptions map[string]interface{}) (*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
productMaterialModel := new(models.ProductMaterial)
query := sqlbuilder.BuildQuery(tx.Model(productMaterialModel), queryOptions)
query.SetWhereByQueryOption("product_material.product_material_id = ?", "productMaterialId")
query.SetWhereByQueryOption("product_material.company_id = ?", "companyId")
query.SetWhereByQueryOption("product_material.material_number = ?", "materialNumber")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if productMaterialModel.ProductMaterialId == 0 {
return nil, nil
} else {
return transform.TransformToProductMaterialDomainModelFromPgModels(productMaterialModel)
}
}
func (repository *ProductMaterialRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ProductMaterial, error) {
tx := repository.transactionContext.PgTx
var productMaterialModels []*models.ProductMaterial
productMaterials := make([]*domain.ProductMaterial, 0)
query := sqlbuilder.BuildQuery(tx.Model(&productMaterialModels), queryOptions)
query.SetWhereByQueryOption("company_id = ?", "companyId")
if v, ok := queryOptions["productMaterialIds"]; ok && len(v.([]int)) > 0 {
query.Where("product_material_id in (?)", pg.In(v))
}
if v, ok := queryOptions["productMaterialGroupIds"]; ok && len(v.([]int)) > 0 {
query.Where("product_material_group_id in (?)", pg.In(v))
}
if v, ok := queryOptions["materialName"]; ok && v != "" {
query.Where("material_name like ?", fmt.Sprintf("%%%v%%", v))
}
if v, ok := queryOptions["materialCategory"]; ok && v != "" {
query.Where(fmt.Sprintf(`material_category->>'category' like '%%%v%%'`, v))
}
if v, ok := queryOptions["materialNumbers"]; ok && len(v.([]string)) > 0 {
query.Where("material_number in (?)", pg.In(v))
}
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("product_material_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, productMaterials, err
} else {
for _, productMaterialModel := range productMaterialModels {
if productMaterial, err := transform.TransformToProductMaterialDomainModelFromPgModels(productMaterialModel); err != nil {
return 0, productMaterials, err
} else {
productMaterials = append(productMaterials, productMaterial)
}
}
return int64(count), productMaterials, nil
}
}
func NewProductMaterialRepository(transactionContext *pgTransaction.TransactionContext) (*ProductMaterialRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &ProductMaterialRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -2,6 +2,7 @@ package k3cloud
import (
"errors"
"fmt"
"io"
"time"
... ... @@ -87,3 +88,20 @@ func (c *Client) ExecuteBillQuery(param RequestExecuteBillQuery) (*BillQueryResu
queryResult := newBillQueryResult(dataByte, param.Data.FieldKeys)
return queryResult, queryResult.Error()
}
// ExecuteMetaDataQuery 元数据查询
func (c *Client) ExecuteMetaDataQuery(param RequestMetaDataQuery) ([]byte, error) {
api := "/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo.common.kdsvc"
resp, err := c.PostRequest(api, param)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var dataByte []byte
dataByte, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
fmt.Println("data ", string(dataByte))
return dataByte, nil
}
... ...
package k3cloud
import (
"fmt"
"strings"
"testing"
"time"
)
var (
... ... @@ -40,7 +42,7 @@ func TestExecuteBillQuery(t *testing.T) {
"FDocumentStatus", "FForbidStatus", "FErpClsID",
"FBaseUnitId", "FBaseUnitId.FName", "FCreateDate", "FModifyDate",
"FForbidDate", "FApproveDate", "FMaterialGroup", "FMaterialGroup.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName",
"FRefStatus", "FMaterialGroup.FNumber", "FUseOrgId", "FUseOrgId.FName", "FCategoryID",
}
result, err := client.ExecuteBillQuery(RequestExecuteBillQuery{
FormId: "BD_MATERIAL",
... ... @@ -85,3 +87,52 @@ func TestExecuteBillQuery2(t *testing.T) {
return
}
}
func TestMetaDataQuery(t *testing.T) {
client, err := NewClient(hostUrl, acctID, username, password)
if err != nil {
t.Error(err)
return
}
inputs := []struct {
formId string
desc string
}{
{"BD_MATERIALCATEGORY", "货类别没"},
{"BD_MATERIALCATEGORY", "货类别没"},
}
for _, v := range inputs {
result, err := client.ExecuteMetaDataQuery(RequestMetaDataQuery{Data{FormId: v.formId}, v.formId})
if err != nil {
fmt.Println(err.Error())
}
t.Log(v.formId, v.desc, string(result))
}
time.Sleep(time.Second)
}
func TestExecuteMATERIALCATEGORYQuery(t *testing.T) {
client, err := NewClient(hostUrl, acctID, username, password)
if err != nil {
t.Error(err)
return
}
fieldKeys := []string{
"FName", "FNUMBER", "FMasterId",
}
result, err := client.ExecuteBillQuery(RequestExecuteBillQuery{
FormId: "PRD_MO",
Data: ExecuteBillQueryData{
FormId: "BD_MATERIALCATEGORY",
FieldKeys: strings.Join(fieldKeys, ","), //查询的字段
//TopRowCount: 4,
FilterString: "",
},
})
t.Logf("result buf===> %s \n", string(result.Buf))
if err != nil {
t.Error(err)
return
}
}
... ...
... ... @@ -51,3 +51,13 @@ type (
Data ExecuteBillQueryData `json:"data"`
}
)
type (
RequestMetaDataQuery struct {
Data Data `json:"data"`
FormId string `json:"FormId"` //必录,查询表单元数据唯一标识
}
Data struct {
FormId string `json:"FormId"` //必录,查询表单元数据唯一标识
}
)
... ...
package utils
const (
unmanaged = iota
untyped
intType
int64Type
uintType
uint64Type
stringType
)
type PlaceholderType = struct{}
// Set is not thread-safe, for concurrent use, make sure to use it with synchronization.
type Set struct {
data map[interface{}]PlaceholderType
tp int
}
// NewSet returns a managed Set, can only put the values with the same type.
func NewSet() *Set {
return &Set{
data: make(map[interface{}]PlaceholderType),
tp: untyped,
}
}
// NewUnmanagedSet returns a unmanaged Set, which can put values with different types.
func NewUnmanagedSet() *Set {
return &Set{
data: make(map[interface{}]PlaceholderType),
tp: unmanaged,
}
}
// Add adds i into s.
func (s *Set) Add(i ...interface{}) {
for _, each := range i {
s.add(each)
}
}
// AddInt adds int values ii into s.
func (s *Set) AddInt(ii ...int) {
for _, each := range ii {
s.add(each)
}
}
// AddInt64 adds int64 values ii into s.
func (s *Set) AddInt64(ii ...int64) {
for _, each := range ii {
s.add(each)
}
}
// AddUint adds uint values ii into s.
func (s *Set) AddUint(ii ...uint) {
for _, each := range ii {
s.add(each)
}
}
// AddUint64 adds uint64 values ii into s.
func (s *Set) AddUint64(ii ...uint64) {
for _, each := range ii {
s.add(each)
}
}
// AddStr adds string values ss into s.
func (s *Set) AddStr(ss ...string) {
for _, each := range ss {
s.add(each)
}
}
// Contains checks if i is in s.
func (s *Set) Contains(i interface{}) bool {
if len(s.data) == 0 {
return false
}
s.validate(i)
_, ok := s.data[i]
return ok
}
// Keys returns the keys in s.
func (s *Set) Keys() []interface{} {
var keys []interface{}
for key := range s.data {
keys = append(keys, key)
}
return keys
}
// KeysInt returns the int keys in s.
func (s *Set) KeysInt() []int {
var keys []int
for key := range s.data {
if intKey, ok := key.(int); ok {
keys = append(keys, intKey)
}
}
return keys
}
// KeysInt64 returns int64 keys in s.
func (s *Set) KeysInt64() []int64 {
var keys []int64
for key := range s.data {
if intKey, ok := key.(int64); ok {
keys = append(keys, intKey)
}
}
return keys
}
// KeysUint returns uint keys in s.
func (s *Set) KeysUint() []uint {
var keys []uint
for key := range s.data {
if intKey, ok := key.(uint); ok {
keys = append(keys, intKey)
}
}
return keys
}
// KeysUint64 returns uint64 keys in s.
func (s *Set) KeysUint64() []uint64 {
var keys []uint64
for key := range s.data {
if intKey, ok := key.(uint64); ok {
keys = append(keys, intKey)
}
}
return keys
}
// KeysStr returns string keys in s.
func (s *Set) KeysStr() []string {
var keys []string
for key := range s.data {
if strKey, ok := key.(string); ok {
keys = append(keys, strKey)
}
}
return keys
}
// Remove removes i from s.
func (s *Set) Remove(i interface{}) {
s.validate(i)
delete(s.data, i)
}
// Count returns the number of items in s.
func (s *Set) Count() int {
return len(s.data)
}
func (s *Set) add(i interface{}) {
switch s.tp {
case unmanaged:
// do nothing
case untyped:
s.setType(i)
default:
s.validate(i)
}
s.data[i] = PlaceholderType{}
}
func (s *Set) setType(i interface{}) {
// s.tp can only be untyped here
switch i.(type) {
case int:
s.tp = intType
case int64:
s.tp = int64Type
case uint:
s.tp = uintType
case uint64:
s.tp = uint64Type
case string:
s.tp = stringType
}
}
func (s *Set) validate(i interface{}) {
if s.tp == unmanaged {
return
}
switch i.(type) {
case int:
if s.tp != intType {
//logx.Errorf("Error: element is int, but set contains elements with type %d", s.tp)
}
case int64:
if s.tp != int64Type {
//logx.Errorf("Error: element is int64, but set contains elements with type %d", s.tp)
}
case uint:
if s.tp != uintType {
//logx.Errorf("Error: element is uint, but set contains elements with type %d", s.tp)
}
case uint64:
if s.tp != uint64Type {
//logx.Errorf("Error: element is uint64, but set contains elements with type %d", s.tp)
}
case string:
if s.tp != stringType {
//logx.Errorf("Error: element is string, but set contains elements with type %d", s.tp)
}
}
}
... ...
package utils
import (
"github.com/linmadan/egglib-go/utils/xtime"
"strconv"
"time"
)
... ... @@ -103,3 +104,32 @@ func TimeBeforeEqual(t1, t2 time.Time) bool {
}
return false
}
type TimeString time.Time
func (timeString *TimeString) UnmarshalJSON(data []byte) error {
if len(data) == 2 {
return nil
}
t, err := xtime.Parse(string(data[1 : len(data)-1]))
if err != nil {
return err
}
*timeString = TimeString(t)
return nil
}
func (timeString TimeString) MarshalJSON() ([]byte, error) {
if xtime.IsZero(time.Time(timeString)) {
return []byte(`""`), nil
}
b := make([]byte, 0)
b = append(b, '"')
b = time.Time(timeString).AppendFormat(b, time.RFC3339)
b = append(b, '"')
return b, nil
}
func (timeString TimeString) Time() time.Time {
return time.Time(timeString)
}
... ...
... ... @@ -24,6 +24,20 @@ func NewTree(nodes []TreeNode) *Tree {
return tree
}
func NewTreeWithNodes(nodes ...TreeNode) *Tree {
var tree = &Tree{
Node: nil,
Nodes: make([]*Tree, 0),
}
for i := range nodes {
match := traverseAdd(tree, nodes[i])
if !match {
tree.Nodes = append(tree.Nodes, newTree(nodes[i]))
}
}
return tree
}
func newTree(node TreeNode) *Tree {
return &Tree{
Node: node,
... ...
... ... @@ -144,6 +144,16 @@ func (controller *StatisticsController) TaskHandler() func(ctx *context.Context)
})
}
}
case "11":
crontab.SyncMaterialGroup(nil)
case "12":
bc := c.Background()
bc = c.WithValue(bc, "pullType", "full")
err := crontab.SyncMaterial(bc)
if err != nil {
Response(ctx, nil, err)
return
}
}
Response(ctx, nil, nil)
}
... ...
... ... @@ -19,7 +19,7 @@ func (controller *ProductController) CreateProduct() {
op := ParseOperateInfo(controller.BaseController)
createProductCommand.CompanyId = op.CompanyId
createProductCommand.OrgId = op.OrgId
data, err := productService.CreateProduct(createProductCommand)
data, err := productService.CreateProduct(ParseOperateInfo(controller.BaseController), createProductCommand)
controller.Response(data, err)
}
... ... @@ -29,7 +29,7 @@ func (controller *ProductController) UpdateProduct() {
Must(controller.Unmarshal(updateProductCommand))
productId, _ := controller.GetInt(":productId")
updateProductCommand.ProductId = productId
data, err := productService.UpdateProduct(updateProductCommand)
data, err := productService.UpdateProduct(ParseOperateInfo(controller.BaseController), updateProductCommand)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterial/service"
)
type ProductMaterialController struct {
beego.BaseController
}
func (controller *ProductMaterialController) CreateProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
cmd := &command.CreateProductMaterialCommand{}
controller.Unmarshal(cmd)
operateInfo := ParseOperateInfo(controller.BaseController)
cmd.CompanyId = operateInfo.CompanyId
cmd.OrgId = operateInfo.OrgId
data, err := productMaterialService.CreateProductMaterial(operateInfo, cmd)
controller.Response(data, err)
}
func (controller *ProductMaterialController) UpdateProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
updateProductMaterialCommand := &command.UpdateProductMaterialCommand{}
controller.Unmarshal(updateProductMaterialCommand)
productMaterialId, _ := controller.GetInt(":productMaterialId")
updateProductMaterialCommand.ProductMaterialId = productMaterialId
operateInfo := ParseOperateInfo(controller.BaseController)
//updateProductMaterialCommand.CompanyId = operateInfo.CompanyId
//updateProductMaterialCommand.OrgId = operateInfo.OrgId
data, err := productMaterialService.UpdateProductMaterial(operateInfo, updateProductMaterialCommand)
controller.Response(data, err)
}
func (controller *ProductMaterialController) GetProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
getProductMaterialQuery := &query.GetProductMaterialQuery{}
productMaterialId, _ := controller.GetInt(":productMaterialId")
getProductMaterialQuery.ProductMaterialId = productMaterialId
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialService.GetProductMaterial(operateInfo, getProductMaterialQuery)
controller.Response(data, err)
}
func (controller *ProductMaterialController) RemoveProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
removeProductMaterialCommand := &command.RemoveProductMaterialCommand{}
controller.Unmarshal(removeProductMaterialCommand)
productMaterialId, _ := controller.GetInt(":productMaterialId")
removeProductMaterialCommand.ProductMaterialId = productMaterialId
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialService.RemoveProductMaterial(operateInfo, removeProductMaterialCommand)
controller.Response(data, err)
}
//没用到
func (controller *ProductMaterialController) ListProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
listProductMaterialQuery := &query.ListProductMaterialQuery{}
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialService.ListProductMaterial(operateInfo, listProductMaterialQuery)
controller.Response(data, err)
}
func (controller *ProductMaterialController) SearchProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
listProductMaterialQuery := &query.SearchProductMaterialQuery{}
controller.Unmarshal(listProductMaterialQuery)
operateInfo := ParseOperateInfo(controller.BaseController)
total, data, err := productMaterialService.SearchProductMaterial(operateInfo, listProductMaterialQuery)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductMaterialController) BatchRemoveProductMaterial() {
productMaterialService := service.NewProductMaterialService(nil)
batchremoveProductMaterialCommand := &command.BatchRemoveProductMaterialCommand{}
controller.Unmarshal(batchremoveProductMaterialCommand)
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialService.BatchRemoveProductMaterial(operateInfo, batchremoveProductMaterialCommand)
controller.Response(data, err)
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productMaterialGroup/service"
)
type ProductMaterialGroupController struct {
beego.BaseController
}
func (controller *ProductMaterialGroupController) CreateProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
cmd := &command.CreateProductMaterialGroupCommand{}
controller.Unmarshal(cmd)
operateInfo := ParseOperateInfo(controller.BaseController)
cmd.CompanyId = operateInfo.CompanyId
cmd.OrgId = operateInfo.OrgId
data, err := productMaterialGroupService.CreateProductMaterialGroup(operateInfo, cmd)
controller.Response(data, err)
}
func (controller *ProductMaterialGroupController) UpdateProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
updateProductMaterialGroupCommand := &command.UpdateProductMaterialGroupCommand{}
controller.Unmarshal(updateProductMaterialGroupCommand)
productMaterialGroupId, _ := controller.GetInt(":productMaterialGroupId")
updateProductMaterialGroupCommand.ProductMaterialGroupId = productMaterialGroupId
operateInfo := ParseOperateInfo(controller.BaseController)
data, err := productMaterialGroupService.UpdateProductMaterialGroup(operateInfo, updateProductMaterialGroupCommand)
controller.Response(data, err)
}
func (controller *ProductMaterialGroupController) GetProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
getProductMaterialGroupQuery := &query.GetProductMaterialGroupQuery{}
productMaterialGroupId, _ := controller.GetInt(":productMaterialGroupId")
getProductMaterialGroupQuery.ProductMaterialGroupId = productMaterialGroupId
data, err := productMaterialGroupService.GetProductMaterialGroup(getProductMaterialGroupQuery)
controller.Response(data, err)
}
func (controller *ProductMaterialGroupController) RemoveProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
removeProductMaterialGroupCommand := &command.RemoveProductMaterialGroupCommand{}
controller.Unmarshal(removeProductMaterialGroupCommand)
productMaterialGroupId, _ := controller.GetInt(":productMaterialGroupId")
removeProductMaterialGroupCommand.ProductMaterialGroupId = productMaterialGroupId
data, err := productMaterialGroupService.RemoveProductMaterialGroup(removeProductMaterialGroupCommand)
controller.Response(data, err)
}
func (controller *ProductMaterialGroupController) ListProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
listProductMaterialGroupQuery := &query.ListProductMaterialGroupQuery{}
offset, _ := controller.GetInt("offset")
listProductMaterialGroupQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listProductMaterialGroupQuery.Limit = limit
data, err := productMaterialGroupService.ListProductMaterialGroup(listProductMaterialGroupQuery)
controller.Response(data, err)
}
func (controller *ProductMaterialGroupController) SearchProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
cmd := &query.SearchProductMaterialGroupQuery{}
offset, _ := controller.GetInt("offset")
cmd.Offset = offset
limit, _ := controller.GetInt("limit")
cmd.Limit = limit
operateInfo := ParseOperateInfo(controller.BaseController)
cmd.CompanyId = operateInfo.CompanyId
total, data, err := productMaterialGroupService.SearchProductMaterialGroup(ParseOperateInfo(controller.BaseController), cmd)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *ProductMaterialGroupController) SelectorProductMaterialGroup() {
productMaterialGroupService := service.NewProductMaterialGroupService(nil)
cmd := &query.SelectorProductMaterialGroupQuery{}
operateInfo := ParseOperateInfo(controller.BaseController)
cmd.CompanyId = operateInfo.CompanyId
count, data, err := productMaterialGroupService.SelectorProductMaterialGroup(ParseOperateInfo(controller.BaseController), cmd)
controller.Response(map[string]interface{}{
"groups": data,
"count": count,
}, 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("/product-material-groups/", &controllers.ProductMaterialGroupController{}, "Post:CreateProductMaterialGroup")
web.Router("/product-material-groups/:productMaterialGroupId", &controllers.ProductMaterialGroupController{}, "Put:UpdateProductMaterialGroup")
web.Router("/product-material-groups/:productMaterialGroupId", &controllers.ProductMaterialGroupController{}, "Get:GetProductMaterialGroup")
web.Router("/product-material-groups/:productMaterialGroupId", &controllers.ProductMaterialGroupController{}, "Delete:RemoveProductMaterialGroup")
web.Router("/product-material-groups/", &controllers.ProductMaterialGroupController{}, "Get:ListProductMaterialGroup")
web.Router("/product-material-groups/search", &controllers.ProductMaterialGroupController{}, "Post:SearchProductMaterialGroup")
web.Router("/product-material-groups/selector", &controllers.ProductMaterialGroupController{}, "Post:SelectorProductMaterialGroup")
}
... ...
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-materials/", &controllers.ProductMaterialController{}, "Post:CreateProductMaterial") //新增单个物料
web.Router("/product-materials/:productMaterialId", &controllers.ProductMaterialController{}, "Put:UpdateProductMaterial") //更新单个物料
web.Router("/product-materials/:productMaterialId", &controllers.ProductMaterialController{}, "Get:GetProductMaterial") //获取单个物料
web.Router("/product-materials/:productMaterialId", &controllers.ProductMaterialController{}, "Delete:RemoveProductMaterial") //删除单个物料
web.Router("/product-materials/", &controllers.ProductMaterialController{}, "Get:ListProductMaterial")
web.Router("/product-materials/search", &controllers.ProductMaterialController{}, "Post:SearchProductMaterial") //搜索返回列表
web.Router("/product-materials/batch-remove", &controllers.ProductMaterialController{}, "Post:BatchRemoveProductMaterial") //批量删除物料
}
... ...
package product_material
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("创建生产物料服务", func() {
Describe("提交数据创建生产物料服务", func() {
Context("提交正确的新生产物料数据", func() {
It("返回生产物料数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"productMaterialGroupId": "int",
"materialNumber": "string",
"materialName": "string",
"materialAttribute": "string",
"materialCategory": "string",
"productMaterialExt": "string",
}
httpExpect.POST("/product-materials/").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("productMaterialId").ValueNotEqual("productMaterialId", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_materials WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回生产物料服务", func() {
var productMaterialId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialId),
"INSERT INTO product_materials (product_material_id, company_id, org_id, product_material_group_id, material_number, material_name, material_attribute, material_category, product_material_ext, created_at, updated_at, deleted_at, ext) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_id",
"testProductMaterialId", "testCompanyId", "testOrgId", "testProductMaterialGroupId", "testMaterialNumber", "testMaterialName", "testMaterialAttribute", "testMaterialCategory", "testProductMaterialExt", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testExt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据productMaterialId参数返回生产物料", func() {
Context("传入有效的productMaterialId", func() {
It("返回生产物料数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/product-materials/{productMaterialId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_materials WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回生产物料服务列表", func() {
var productMaterialId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialId),
"INSERT INTO product_materials (product_material_id, company_id, org_id, product_material_group_id, material_number, material_name, material_attribute, material_category, product_material_ext, created_at, updated_at, deleted_at, ext) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_id",
"testProductMaterialId", "testCompanyId", "testOrgId", "testProductMaterialGroupId", "testMaterialNumber", "testMaterialName", "testMaterialAttribute", "testMaterialCategory", "testProductMaterialExt", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testExt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数返回生产物料列表", func() {
Context("传入有效的参数", func() {
It("返回生产物料数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/product-materials/").
WithQuery("offset", "int").
WithQuery("limit", "int").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("count").ValueEqual("count", 1).
ContainsKey("productMaterials").Value("productMaterials").Array()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_materials WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego"
)
func TestProductMaterial(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port ProductMaterial Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package product_material
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("移除生产物料服务", func() {
var productMaterialId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialId),
"INSERT INTO product_materials (product_material_id, company_id, org_id, product_material_group_id, material_number, material_name, material_attribute, material_category, product_material_ext, created_at, updated_at, deleted_at, ext) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_id",
"testProductMaterialId", "testCompanyId", "testOrgId", "testProductMaterialGroupId", "testMaterialNumber", "testMaterialName", "testMaterialAttribute", "testMaterialCategory", "testProductMaterialExt", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testExt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数移除生产物料服务", func() {
Context("传入有效的productMaterialId", func() {
It("返回被移除生产物料的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/product-materials/{productMaterialId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_materials WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("更新生产物料服务", func() {
var productMaterialId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialId),
"INSERT INTO product_materials (product_material_id, company_id, org_id, product_material_group_id, material_number, material_name, material_attribute, material_category, product_material_ext, created_at, updated_at, deleted_at, ext) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_id",
"testProductMaterialId", "testCompanyId", "testOrgId", "testProductMaterialGroupId", "testMaterialNumber", "testMaterialName", "testMaterialAttribute", "testMaterialCategory", "testProductMaterialExt", "testCreatedAt", "testUpdatedAt", "testDeletedAt", "testExt")
Expect(err).NotTo(HaveOccurred())
})
Describe("提交数据更新生产物料服务", func() {
Context("提交正确的生产物料数据", func() {
It("返回更新后的生产物料数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.PUT("/product-materials/{productMaterialId}").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("productMaterialId").ValueEqual("productMaterialId", productMaterialId)
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_materials WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material_group
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("创建物料分组服务", func() {
Describe("提交数据创建物料分组服务", func() {
Context("提交正确的新物料分组数据", func() {
It("返回物料分组数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"pid": "int",
"materialGroupName": "string",
"materialGroupNumber": "string",
}
httpExpect.POST("/product-material-groups/").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("productMaterialGroupId").ValueNotEqual("productMaterialGroupId", BeZero())
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_material_groups WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material_group
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回物料分组服务", func() {
var productMaterialGroupId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialGroupId),
"INSERT INTO product_material_groups (product_material_group_id, company_id, org_id, pid, path, material_group_name, material_group_number, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_group_id",
"testProductMaterialGroupId", "testCompanyId", "testOrgId", "testPid", "testPath", "testMaterialGroupName", "testMaterialGroupNumber", "testCreatedAt", "testUpdatedAt", "testDeletedAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据productMaterialGroupId参数返回物料分组", func() {
Context("传入有效的productMaterialGroupId", func() {
It("返回物料分组数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/product-material-groups/{productMaterialGroupId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_material_groups WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material_group
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("返回物料分组服务列表", func() {
var productMaterialGroupId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialGroupId),
"INSERT INTO product_material_groups (product_material_group_id, company_id, org_id, pid, path, material_group_name, material_group_number, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_group_id",
"testProductMaterialGroupId", "testCompanyId", "testOrgId", "testPid", "testPath", "testMaterialGroupName", "testMaterialGroupNumber", "testCreatedAt", "testUpdatedAt", "testDeletedAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数返回物料分组列表", func() {
Context("传入有效的参数", func() {
It("返回物料分组数据列表", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.GET("/product-material-groups/").
WithQuery("offset", "int").
WithQuery("limit", "int").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object().
ContainsKey("count").ValueEqual("count", 1).
ContainsKey("productMaterialGroups").Value("productMaterialGroups").Array()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_material_groups WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package product_material_group
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/beego"
)
func TestProductMaterialGroup(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port ProductMaterialGroup Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package product_material_group
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg"
)
var _ = Describe("移除物料分组服务", func() {
var productMaterialGroupId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&productMaterialGroupId),
"INSERT INTO product_material_groups (product_material_group_id, company_id, org_id, pid, path, material_group_name, material_group_number, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING product_material_group_id",
"testProductMaterialGroupId", "testCompanyId", "testOrgId", "testPid", "testPath", "testMaterialGroupName", "testMaterialGroupNumber", "testCreatedAt", "testUpdatedAt", "testDeletedAt")
Expect(err).NotTo(HaveOccurred())
})
Describe("根据参数移除物料分组服务", func() {
Context("传入有效的productMaterialGroupId", func() {
It("返回被移除物料分组的数据", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
httpExpect.DELETE("/product-material-groups/{productMaterialGroupId}").
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM product_material_groups WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...