From 6f6da3f4813a5c6c08de9da7768ae73d88d77448 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 14:05:27 +0800 Subject: [PATCH 1/6] fix --- ddl/fs_order.sql | 44 +++++ ddl/fs_order_detail.sql | 32 ++++ ddl/fs_order_detail_template.sql | 22 +++ model/fsorderdetailmodel.go | 24 +++ model/fsorderdetailmodel_gen.go | 121 ++++++++++++ model/fsorderdetailtemplatemodel.go | 24 +++ model/fsorderdetailtemplatemodel_gen.go | 108 +++++++++++ model/fsordermodel.go | 24 +++ model/fsordermodel_gen.go | 134 ++++++++++++++ model/gmodel/fsaddressmodel.go | 13 +- model/gmodel/fsorderdetailmodel.go | 48 +++++ model/gmodel/fsorderdetailtemplatemodel.go | 38 ++++ model/gmodel/fsordermodel.go | 62 +++++++ .../logic/savecanteentypeproductlogic.go | 2 +- .../handler/cartorderdetailhandler.go | 67 +++++++ .../internal/handler/routes.go | 5 + .../internal/logic/cartaddlogic.go | 6 +- .../internal/logic/cartdeletelogic.go | 2 +- .../internal/logic/cartorderdetaillogic.go | 175 ++++++++++++++++++ .../internal/types/types.go | 40 ++++ server_api/shopping-cart-confirmation.api | 40 ++++ utils/basic/basic.go | 3 +- 22 files changed, 1027 insertions(+), 7 deletions(-) create mode 100644 ddl/fs_order.sql create mode 100644 ddl/fs_order_detail.sql create mode 100644 ddl/fs_order_detail_template.sql create mode 100755 model/fsorderdetailmodel.go create mode 100755 model/fsorderdetailmodel_gen.go create mode 100755 model/fsorderdetailtemplatemodel.go create mode 100755 model/fsorderdetailtemplatemodel_gen.go create mode 100755 model/fsordermodel.go create mode 100755 model/fsordermodel_gen.go create mode 100755 model/gmodel/fsorderdetailmodel.go create mode 100755 model/gmodel/fsorderdetailtemplatemodel.go create mode 100755 model/gmodel/fsordermodel.go create mode 100644 server/shopping-cart-confirmation/internal/handler/cartorderdetailhandler.go create mode 100644 server/shopping-cart-confirmation/internal/logic/cartorderdetaillogic.go diff --git a/ddl/fs_order.sql b/ddl/fs_order.sql new file mode 100644 index 00000000..da11f6d3 --- /dev/null +++ b/ddl/fs_order.sql @@ -0,0 +1,44 @@ +-- fusentest.fs_order definition + +CREATE TABLE `fs_order` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sn` char(16) NOT NULL COMMENT '订单编号 FS211224OL2XDKNP', + `user_id` int(11) DEFAULT NULL COMMENT '用户ID', + `seller_user_id` int(11) DEFAULT NULL COMMENT '销售员ID 0:自主下单', + `total_amount` int(11) NOT NULL COMMENT '总价', + `payed_amount` int(11) NOT NULL COMMENT '已支付金额', + `pay_method` tinyint(1) NOT NULL DEFAULT '0' COMMENT '支付方式 1paypal 2strip', + `ctime` int(11) DEFAULT NULL COMMENT '添加时间', + `utime` int(11) DEFAULT NULL COMMENT '更新时间', + `ptime` int(11) DEFAULT NULL COMMENT '最后一次 支付时间(可能多次支付)', + `address_id` int(11) NOT NULL COMMENT '地址ID或者云仓ID', + `delivery_method` int(11) NOT NULL COMMENT '配送方式 1:直接发货到收获地址 2:云仓', + `customer_mark` varchar(255) DEFAULT NULL COMMENT '客户备注', + `mark` text COMMENT '后台订单备注', + `address_info` text COMMENT '详细地址信息JSON', + `is_sup` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0不是补货 1是补货', + `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭)', + `is_part_pay` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否部分支付(0:否,1:是)', + `is_pay_completed` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否支付完成(0:否,1:是)', + `is_part_product` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否部分生产(0:否,1:是)', + `is_part_product_completed` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否部分生产完成(0:否,1:是)', + `is_all_product` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否全部生产(0:否,1:是)', + `is_all_product_completed` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否全部生产完成(0:否,1:是)', + `is_part_delivery` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否部分发货(0:否,1:是)', + `is_delivery_completed` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否发货完成(0:否,1:是)', + `is_complated` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否完成订单(0:否,1:是)', + `is_cancel` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否取消订单(0:否,1:是)', + `is_refunding` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否退款中(0:否,1:是)', + `is_refunded` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否退款完成(0:否,1:是)', + `is_deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除(0:否,1:是)', + `refund_reason_id` tinyint(4) DEFAULT NULL COMMENT '取消订单原因ID', + `refund_reason` varchar(255) DEFAULT NULL COMMENT '取消订单原因', + `ts_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `is_sure` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否确认订单 1确认0未确认', + `deliver_sn` varchar(50) NOT NULL DEFAULT '' COMMENT '发货单号', + `email_time` int(11) NOT NULL DEFAULT '0' COMMENT '邮件发送时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `sn` (`sn`) USING BTREE, + KEY `user_id` (`user_id`) USING BTREE, + KEY `address_id` (`address_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=691 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; \ No newline at end of file diff --git a/ddl/fs_order_detail.sql b/ddl/fs_order_detail.sql new file mode 100644 index 00000000..3c58221b --- /dev/null +++ b/ddl/fs_order_detail.sql @@ -0,0 +1,32 @@ +-- fusentest.fs_order_detail definition + +CREATE TABLE `fs_order_detail` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sn` char(32) NOT NULL COMMENT '唯一编码', + `order_id` int(11) NOT NULL COMMENT '订单ID', + `user_id` int(11) DEFAULT NULL COMMENT '用户ID', + `factory_id` smallint(6) DEFAULT '0' COMMENT '工厂ID', + `order_detail_template_id` int(11) NOT NULL COMMENT '详情templateID', + `product_id` int(11) NOT NULL COMMENT '产品ID', + `buy_num` int(11) NOT NULL COMMENT '购买数量', + `push_num` int(11) NOT NULL COMMENT '已发数量', + `amount` int(11) NOT NULL COMMENT '单价', + `cover` varchar(128) NOT NULL COMMENT '截图', + `ctime` int(11) NOT NULL COMMENT '添加时间', + `status` tinyint(4) NOT NULL COMMENT '状态位 是否推送到厂家 是否生产完成 是否发货完成', + `optional_id` int(11) NOT NULL DEFAULT '0' COMMENT '选项ID', + `optional_title` varchar(64) NOT NULL COMMENT '选项名称', + `option_price` int(11) NOT NULL DEFAULT '0' COMMENT '配件价格', + `is_tofactory` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否推送到工厂', + `is_product` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否生产中', + `is_product_completion` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否生产完成', + `is_cloud` tinyint(1) NOT NULL COMMENT '是否是云仓订单', + `is_tocloud` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否已发云仓(云仓单要发货到云仓,直接发到用户的不需要发到云仓)', + `is_deliver` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否已发货', + `is_end` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否完成订单(签收)', + `cart_id` int(10) NOT NULL DEFAULT '0' COMMENT '购物车编号', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `sn` (`sn`) USING BTREE, + KEY `order_id` (`order_id`) USING BTREE, + KEY `cart_id` (`cart_id`) +) ENGINE=InnoDB AUTO_INCREMENT=1049 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='订单详细表'; \ No newline at end of file diff --git a/ddl/fs_order_detail_template.sql b/ddl/fs_order_detail_template.sql new file mode 100644 index 00000000..37deae4e --- /dev/null +++ b/ddl/fs_order_detail_template.sql @@ -0,0 +1,22 @@ +-- fusentest.fs_order_detail_template definition + +CREATE TABLE `fs_order_detail_template` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sn` char(32) NOT NULL COMMENT '唯一编码', + `product_id` int(11) NOT NULL COMMENT '产品ID', + `model_id` int(11) NOT NULL DEFAULT '0' COMMENT '模型ID', + `template_id` int(11) NOT NULL COMMENT '模板ID', + `material_id` int(11) NOT NULL COMMENT '材质id', + `size_id` int(11) NOT NULL COMMENT '尺寸id', + `each_box_num` int(11) NOT NULL COMMENT '每一箱的个数', + `each_box_weight` decimal(10,2) DEFAULT '0.00' COMMENT '每一箱的重量 单位KG', + `design_id` int(11) NOT NULL COMMENT '设计ID', + `ctime` int(11) DEFAULT NULL COMMENT '添加时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `sn` (`sn`) USING BTREE, + KEY `product_id` (`product_id`) USING BTREE, + KEY `template_id` (`template_id`) USING BTREE, + KEY `material_id` (`material_id`) USING BTREE, + KEY `size_id` (`size_id`) USING BTREE, + KEY `design_id` (`design_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=934 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='订单模板详细表'; \ No newline at end of file diff --git a/model/fsorderdetailmodel.go b/model/fsorderdetailmodel.go new file mode 100755 index 00000000..4947ef9b --- /dev/null +++ b/model/fsorderdetailmodel.go @@ -0,0 +1,24 @@ +package model + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var _ FsOrderDetailModel = (*customFsOrderDetailModel)(nil) + +type ( + // FsOrderDetailModel is an interface to be customized, add more methods here, + // and implement the added methods in customFsOrderDetailModel. + FsOrderDetailModel interface { + fsOrderDetailModel + } + + customFsOrderDetailModel struct { + *defaultFsOrderDetailModel + } +) + +// NewFsOrderDetailModel returns a model for the database table. +func NewFsOrderDetailModel(conn sqlx.SqlConn) FsOrderDetailModel { + return &customFsOrderDetailModel{ + defaultFsOrderDetailModel: newFsOrderDetailModel(conn), + } +} diff --git a/model/fsorderdetailmodel_gen.go b/model/fsorderdetailmodel_gen.go new file mode 100755 index 00000000..6bca48b4 --- /dev/null +++ b/model/fsorderdetailmodel_gen.go @@ -0,0 +1,121 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + fsOrderDetailFieldNames = builder.RawFieldNames(&FsOrderDetail{}) + fsOrderDetailRows = strings.Join(fsOrderDetailFieldNames, ",") + fsOrderDetailRowsExpectAutoSet = strings.Join(stringx.Remove(fsOrderDetailFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") + fsOrderDetailRowsWithPlaceHolder = strings.Join(stringx.Remove(fsOrderDetailFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" +) + +type ( + fsOrderDetailModel interface { + Insert(ctx context.Context, data *FsOrderDetail) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*FsOrderDetail, error) + FindOneBySn(ctx context.Context, sn string) (*FsOrderDetail, error) + Update(ctx context.Context, data *FsOrderDetail) error + Delete(ctx context.Context, id int64) error + } + + defaultFsOrderDetailModel struct { + conn sqlx.SqlConn + table string + } + + FsOrderDetail struct { + Id int64 `db:"id"` + Sn string `db:"sn"` // 唯一编码 + OrderId int64 `db:"order_id"` // 订单ID + UserId sql.NullInt64 `db:"user_id"` // 用户ID + FactoryId int64 `db:"factory_id"` // 工厂ID + OrderDetailTemplateId int64 `db:"order_detail_template_id"` // 详情templateID + ProductId int64 `db:"product_id"` // 产品ID + BuyNum int64 `db:"buy_num"` // 购买数量 + PushNum int64 `db:"push_num"` // 已发数量 + Amount int64 `db:"amount"` // 单价 + Cover string `db:"cover"` // 截图 + Ctime int64 `db:"ctime"` // 添加时间 + Status int64 `db:"status"` // 状态位 是否推送到厂家 是否生产完成 是否发货完成 + OptionalId int64 `db:"optional_id"` // 选项ID + OptionalTitle string `db:"optional_title"` // 选项名称 + OptionPrice int64 `db:"option_price"` // 配件价格 + IsTofactory int64 `db:"is_tofactory"` // 是否推送到工厂 + IsProduct int64 `db:"is_product"` // 是否生产中 + IsProductCompletion int64 `db:"is_product_completion"` // 是否生产完成 + IsCloud int64 `db:"is_cloud"` // 是否是云仓订单 + IsTocloud int64 `db:"is_tocloud"` // 是否已发云仓(云仓单要发货到云仓,直接发到用户的不需要发到云仓) + IsDeliver int64 `db:"is_deliver"` // 是否已发货 + IsEnd int64 `db:"is_end"` // 是否完成订单(签收) + CartId int64 `db:"cart_id"` // 购物车编号 + } +) + +func newFsOrderDetailModel(conn sqlx.SqlConn) *defaultFsOrderDetailModel { + return &defaultFsOrderDetailModel{ + conn: conn, + table: "`fs_order_detail`", + } +} + +func (m *defaultFsOrderDetailModel) Delete(ctx context.Context, id int64) error { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + _, err := m.conn.ExecCtx(ctx, query, id) + return err +} + +func (m *defaultFsOrderDetailModel) FindOne(ctx context.Context, id int64) (*FsOrderDetail, error) { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", fsOrderDetailRows, m.table) + var resp FsOrderDetail + err := m.conn.QueryRowCtx(ctx, &resp, query, id) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderDetailModel) FindOneBySn(ctx context.Context, sn string) (*FsOrderDetail, error) { + var resp FsOrderDetail + query := fmt.Sprintf("select %s from %s where `sn` = ? limit 1", fsOrderDetailRows, m.table) + err := m.conn.QueryRowCtx(ctx, &resp, query, sn) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderDetailModel) Insert(ctx context.Context, data *FsOrderDetail) (sql.Result, error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, fsOrderDetailRowsExpectAutoSet) + ret, err := m.conn.ExecCtx(ctx, query, data.Sn, data.OrderId, data.UserId, data.FactoryId, data.OrderDetailTemplateId, data.ProductId, data.BuyNum, data.PushNum, data.Amount, data.Cover, data.Ctime, data.Status, data.OptionalId, data.OptionalTitle, data.OptionPrice, data.IsTofactory, data.IsProduct, data.IsProductCompletion, data.IsCloud, data.IsTocloud, data.IsDeliver, data.IsEnd, data.CartId) + return ret, err +} + +func (m *defaultFsOrderDetailModel) Update(ctx context.Context, newData *FsOrderDetail) error { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, fsOrderDetailRowsWithPlaceHolder) + _, err := m.conn.ExecCtx(ctx, query, newData.Sn, newData.OrderId, newData.UserId, newData.FactoryId, newData.OrderDetailTemplateId, newData.ProductId, newData.BuyNum, newData.PushNum, newData.Amount, newData.Cover, newData.Ctime, newData.Status, newData.OptionalId, newData.OptionalTitle, newData.OptionPrice, newData.IsTofactory, newData.IsProduct, newData.IsProductCompletion, newData.IsCloud, newData.IsTocloud, newData.IsDeliver, newData.IsEnd, newData.CartId, newData.Id) + return err +} + +func (m *defaultFsOrderDetailModel) tableName() string { + return m.table +} diff --git a/model/fsorderdetailtemplatemodel.go b/model/fsorderdetailtemplatemodel.go new file mode 100755 index 00000000..02fc08a6 --- /dev/null +++ b/model/fsorderdetailtemplatemodel.go @@ -0,0 +1,24 @@ +package model + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var _ FsOrderDetailTemplateModel = (*customFsOrderDetailTemplateModel)(nil) + +type ( + // FsOrderDetailTemplateModel is an interface to be customized, add more methods here, + // and implement the added methods in customFsOrderDetailTemplateModel. + FsOrderDetailTemplateModel interface { + fsOrderDetailTemplateModel + } + + customFsOrderDetailTemplateModel struct { + *defaultFsOrderDetailTemplateModel + } +) + +// NewFsOrderDetailTemplateModel returns a model for the database table. +func NewFsOrderDetailTemplateModel(conn sqlx.SqlConn) FsOrderDetailTemplateModel { + return &customFsOrderDetailTemplateModel{ + defaultFsOrderDetailTemplateModel: newFsOrderDetailTemplateModel(conn), + } +} diff --git a/model/fsorderdetailtemplatemodel_gen.go b/model/fsorderdetailtemplatemodel_gen.go new file mode 100755 index 00000000..10f4604e --- /dev/null +++ b/model/fsorderdetailtemplatemodel_gen.go @@ -0,0 +1,108 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + fsOrderDetailTemplateFieldNames = builder.RawFieldNames(&FsOrderDetailTemplate{}) + fsOrderDetailTemplateRows = strings.Join(fsOrderDetailTemplateFieldNames, ",") + fsOrderDetailTemplateRowsExpectAutoSet = strings.Join(stringx.Remove(fsOrderDetailTemplateFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") + fsOrderDetailTemplateRowsWithPlaceHolder = strings.Join(stringx.Remove(fsOrderDetailTemplateFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" +) + +type ( + fsOrderDetailTemplateModel interface { + Insert(ctx context.Context, data *FsOrderDetailTemplate) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*FsOrderDetailTemplate, error) + FindOneBySn(ctx context.Context, sn string) (*FsOrderDetailTemplate, error) + Update(ctx context.Context, data *FsOrderDetailTemplate) error + Delete(ctx context.Context, id int64) error + } + + defaultFsOrderDetailTemplateModel struct { + conn sqlx.SqlConn + table string + } + + FsOrderDetailTemplate struct { + Id int64 `db:"id"` + Sn string `db:"sn"` // 唯一编码 + ProductId int64 `db:"product_id"` // 产品ID + ModelId int64 `db:"model_id"` // 模型ID + TemplateId int64 `db:"template_id"` // 模板ID + MaterialId int64 `db:"material_id"` // 材质id + SizeId int64 `db:"size_id"` // 尺寸id + EachBoxNum int64 `db:"each_box_num"` // 每一箱的个数 + EachBoxWeight float64 `db:"each_box_weight"` // 每一箱的重量 单位KG + DesignId int64 `db:"design_id"` // 设计ID + Ctime sql.NullInt64 `db:"ctime"` // 添加时间 + } +) + +func newFsOrderDetailTemplateModel(conn sqlx.SqlConn) *defaultFsOrderDetailTemplateModel { + return &defaultFsOrderDetailTemplateModel{ + conn: conn, + table: "`fs_order_detail_template`", + } +} + +func (m *defaultFsOrderDetailTemplateModel) Delete(ctx context.Context, id int64) error { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + _, err := m.conn.ExecCtx(ctx, query, id) + return err +} + +func (m *defaultFsOrderDetailTemplateModel) FindOne(ctx context.Context, id int64) (*FsOrderDetailTemplate, error) { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", fsOrderDetailTemplateRows, m.table) + var resp FsOrderDetailTemplate + err := m.conn.QueryRowCtx(ctx, &resp, query, id) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderDetailTemplateModel) FindOneBySn(ctx context.Context, sn string) (*FsOrderDetailTemplate, error) { + var resp FsOrderDetailTemplate + query := fmt.Sprintf("select %s from %s where `sn` = ? limit 1", fsOrderDetailTemplateRows, m.table) + err := m.conn.QueryRowCtx(ctx, &resp, query, sn) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderDetailTemplateModel) Insert(ctx context.Context, data *FsOrderDetailTemplate) (sql.Result, error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, fsOrderDetailTemplateRowsExpectAutoSet) + ret, err := m.conn.ExecCtx(ctx, query, data.Sn, data.ProductId, data.ModelId, data.TemplateId, data.MaterialId, data.SizeId, data.EachBoxNum, data.EachBoxWeight, data.DesignId, data.Ctime) + return ret, err +} + +func (m *defaultFsOrderDetailTemplateModel) Update(ctx context.Context, newData *FsOrderDetailTemplate) error { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, fsOrderDetailTemplateRowsWithPlaceHolder) + _, err := m.conn.ExecCtx(ctx, query, newData.Sn, newData.ProductId, newData.ModelId, newData.TemplateId, newData.MaterialId, newData.SizeId, newData.EachBoxNum, newData.EachBoxWeight, newData.DesignId, newData.Ctime, newData.Id) + return err +} + +func (m *defaultFsOrderDetailTemplateModel) tableName() string { + return m.table +} diff --git a/model/fsordermodel.go b/model/fsordermodel.go new file mode 100755 index 00000000..e4e99c20 --- /dev/null +++ b/model/fsordermodel.go @@ -0,0 +1,24 @@ +package model + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var _ FsOrderModel = (*customFsOrderModel)(nil) + +type ( + // FsOrderModel is an interface to be customized, add more methods here, + // and implement the added methods in customFsOrderModel. + FsOrderModel interface { + fsOrderModel + } + + customFsOrderModel struct { + *defaultFsOrderModel + } +) + +// NewFsOrderModel returns a model for the database table. +func NewFsOrderModel(conn sqlx.SqlConn) FsOrderModel { + return &customFsOrderModel{ + defaultFsOrderModel: newFsOrderModel(conn), + } +} diff --git a/model/fsordermodel_gen.go b/model/fsordermodel_gen.go new file mode 100755 index 00000000..e892bd9f --- /dev/null +++ b/model/fsordermodel_gen.go @@ -0,0 +1,134 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + fsOrderFieldNames = builder.RawFieldNames(&FsOrder{}) + fsOrderRows = strings.Join(fsOrderFieldNames, ",") + fsOrderRowsExpectAutoSet = strings.Join(stringx.Remove(fsOrderFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") + fsOrderRowsWithPlaceHolder = strings.Join(stringx.Remove(fsOrderFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" +) + +type ( + fsOrderModel interface { + Insert(ctx context.Context, data *FsOrder) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*FsOrder, error) + FindOneBySn(ctx context.Context, sn string) (*FsOrder, error) + Update(ctx context.Context, data *FsOrder) error + Delete(ctx context.Context, id int64) error + } + + defaultFsOrderModel struct { + conn sqlx.SqlConn + table string + } + + FsOrder struct { + Id int64 `db:"id"` + Sn string `db:"sn"` // 订单编号 FS211224OL2XDKNP + UserId sql.NullInt64 `db:"user_id"` // 用户ID + SellerUserId sql.NullInt64 `db:"seller_user_id"` // 销售员ID 0:自主下单 + TotalAmount int64 `db:"total_amount"` // 总价 + PayedAmount int64 `db:"payed_amount"` // 已支付金额 + PayMethod int64 `db:"pay_method"` // 支付方式 1paypal 2strip + Ctime sql.NullInt64 `db:"ctime"` // 添加时间 + Utime sql.NullInt64 `db:"utime"` // 更新时间 + Ptime sql.NullInt64 `db:"ptime"` // 最后一次 支付时间(可能多次支付) + AddressId int64 `db:"address_id"` // 地址ID或者云仓ID + DeliveryMethod int64 `db:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 + CustomerMark sql.NullString `db:"customer_mark"` // 客户备注 + Mark sql.NullString `db:"mark"` // 后台订单备注 + AddressInfo sql.NullString `db:"address_info"` // 详细地址信息JSON + IsSup int64 `db:"is_sup"` // 0不是补货 1是补货 + Status int64 `db:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) + IsPartPay int64 `db:"is_part_pay"` // 是否部分支付(0:否,1:是) + IsPayCompleted int64 `db:"is_pay_completed"` // 是否支付完成(0:否,1:是) + IsPartProduct int64 `db:"is_part_product"` // 是否部分生产(0:否,1:是) + IsPartProductCompleted int64 `db:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) + IsAllProduct int64 `db:"is_all_product"` // 是否全部生产(0:否,1:是) + IsAllProductCompleted int64 `db:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) + IsPartDelivery int64 `db:"is_part_delivery"` // 是否部分发货(0:否,1:是) + IsDeliveryCompleted int64 `db:"is_delivery_completed"` // 是否发货完成(0:否,1:是) + IsComplated int64 `db:"is_complated"` // 是否完成订单(0:否,1:是) + IsCancel int64 `db:"is_cancel"` // 是否取消订单(0:否,1:是) + IsRefunding int64 `db:"is_refunding"` // 是否退款中(0:否,1:是) + IsRefunded int64 `db:"is_refunded"` // 是否退款完成(0:否,1:是) + IsDeleted int64 `db:"is_deleted"` // 是否删除(0:否,1:是) + RefundReasonId sql.NullInt64 `db:"refund_reason_id"` // 取消订单原因ID + RefundReason sql.NullString `db:"refund_reason"` // 取消订单原因 + TsTime time.Time `db:"ts_time"` + IsSure int64 `db:"is_sure"` // 是否确认订单 1确认0未确认 + DeliverSn string `db:"deliver_sn"` // 发货单号 + EmailTime int64 `db:"email_time"` // 邮件发送时间 + } +) + +func newFsOrderModel(conn sqlx.SqlConn) *defaultFsOrderModel { + return &defaultFsOrderModel{ + conn: conn, + table: "`fs_order`", + } +} + +func (m *defaultFsOrderModel) Delete(ctx context.Context, id int64) error { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + _, err := m.conn.ExecCtx(ctx, query, id) + return err +} + +func (m *defaultFsOrderModel) FindOne(ctx context.Context, id int64) (*FsOrder, error) { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", fsOrderRows, m.table) + var resp FsOrder + err := m.conn.QueryRowCtx(ctx, &resp, query, id) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderModel) FindOneBySn(ctx context.Context, sn string) (*FsOrder, error) { + var resp FsOrder + query := fmt.Sprintf("select %s from %s where `sn` = ? limit 1", fsOrderRows, m.table) + err := m.conn.QueryRowCtx(ctx, &resp, query, sn) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsOrderModel) Insert(ctx context.Context, data *FsOrder) (sql.Result, error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, fsOrderRowsExpectAutoSet) + ret, err := m.conn.ExecCtx(ctx, query, data.Sn, data.UserId, data.SellerUserId, data.TotalAmount, data.PayedAmount, data.PayMethod, data.Ctime, data.Utime, data.Ptime, data.AddressId, data.DeliveryMethod, data.CustomerMark, data.Mark, data.AddressInfo, data.IsSup, data.Status, data.IsPartPay, data.IsPayCompleted, data.IsPartProduct, data.IsPartProductCompleted, data.IsAllProduct, data.IsAllProductCompleted, data.IsPartDelivery, data.IsDeliveryCompleted, data.IsComplated, data.IsCancel, data.IsRefunding, data.IsRefunded, data.IsDeleted, data.RefundReasonId, data.RefundReason, data.TsTime, data.IsSure, data.DeliverSn, data.EmailTime) + return ret, err +} + +func (m *defaultFsOrderModel) Update(ctx context.Context, newData *FsOrder) error { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, fsOrderRowsWithPlaceHolder) + _, err := m.conn.ExecCtx(ctx, query, newData.Sn, newData.UserId, newData.SellerUserId, newData.TotalAmount, newData.PayedAmount, newData.PayMethod, newData.Ctime, newData.Utime, newData.Ptime, newData.AddressId, newData.DeliveryMethod, newData.CustomerMark, newData.Mark, newData.AddressInfo, newData.IsSup, newData.Status, newData.IsPartPay, newData.IsPayCompleted, newData.IsPartProduct, newData.IsPartProductCompleted, newData.IsAllProduct, newData.IsAllProductCompleted, newData.IsPartDelivery, newData.IsDeliveryCompleted, newData.IsComplated, newData.IsCancel, newData.IsRefunding, newData.IsRefunded, newData.IsDeleted, newData.RefundReasonId, newData.RefundReason, newData.TsTime, newData.IsSure, newData.DeliverSn, newData.EmailTime, newData.Id) + return err +} + +func (m *defaultFsOrderModel) tableName() string { + return m.table +} diff --git a/model/gmodel/fsaddressmodel.go b/model/gmodel/fsaddressmodel.go index 0c53c219..f6b14d0c 100755 --- a/model/gmodel/fsaddressmodel.go +++ b/model/gmodel/fsaddressmodel.go @@ -1,6 +1,9 @@ package gmodel -import "gorm.io/gorm" +import ( + "context" + "gorm.io/gorm" +) type FsAddress struct { Id int64 `gorm:"primary_key" json:"id"` @@ -26,3 +29,11 @@ type FsAddressModel struct { func NewFsAddressModel(db *gorm.DB) *FsAddressModel { return &FsAddressModel{db} } + +func (a *FsAddressModel) GetUserAllAddress(ctx context.Context, userId int64) (resp []FsAddress, err error) { + err = a.db.WithContext(ctx).Model(&FsAddress{}).Where("`user_id` = ? and `status` = ?", userId, 1).Order("`id` DESC").Find(&resp).Error + if err != nil { + return nil, err + } + return +} diff --git a/model/gmodel/fsorderdetailmodel.go b/model/gmodel/fsorderdetailmodel.go new file mode 100755 index 00000000..ad245e18 --- /dev/null +++ b/model/gmodel/fsorderdetailmodel.go @@ -0,0 +1,48 @@ +package gmodel + +import ( + "context" + "gorm.io/gorm" +) + +type FsOrderDetail struct { + Id int64 `gorm:"primary_key" json:"id"` + Sn *string `gorm:"default:''" json:"sn"` // 唯一编码 + OrderId *int64 `gorm:"default:0" json:"order_id"` // 订单ID + UserId *int64 `gorm:"default:0" json:"user_id"` // 用户ID + FactoryId *int64 `gorm:"default:0" json:"factory_id"` // 工厂ID + OrderDetailTemplateId *int64 `gorm:"default:0" json:"order_detail_template_id"` // 详情templateID + ProductId *int64 `gorm:"default:0" json:"product_id"` // 产品ID + BuyNum *int64 `gorm:"default:0" json:"buy_num"` // 购买数量 + PushNum *int64 `gorm:"default:0" json:"push_num"` // 已发数量 + Amount *int64 `gorm:"default:0" json:"amount"` // 单价 + Cover *string `gorm:"default:''" json:"cover"` // 截图 + Ctime *int64 `gorm:"default:0" json:"ctime"` // 添加时间 + Status *int64 `gorm:"default:0" json:"status"` // 状态位 是否推送到厂家 是否生产完成 是否发货完成 + OptionalId *int64 `gorm:"default:0" json:"optional_id"` // 选项ID + OptionalTitle *string `gorm:"default:''" json:"optional_title"` // 选项名称 + OptionPrice *int64 `gorm:"default:0" json:"option_price"` // 配件价格 + IsTofactory *int64 `gorm:"default:0" json:"is_tofactory"` // 是否推送到工厂 + IsProduct *int64 `gorm:"default:0" json:"is_product"` // 是否生产中 + IsProductCompletion *int64 `gorm:"default:0" json:"is_product_completion"` // 是否生产完成 + IsCloud *int64 `gorm:"default:0" json:"is_cloud"` // 是否是云仓订单 + IsTocloud *int64 `gorm:"default:0" json:"is_tocloud"` // 是否已发云仓(云仓单要发货到云仓,直接发到用户的不需要发到云仓) + IsDeliver *int64 `gorm:"default:0" json:"is_deliver"` // 是否已发货 + IsEnd *int64 `gorm:"default:0" json:"is_end"` // 是否完成订单(签收) + CartId *int64 `gorm:"default:0" json:"cart_id"` // 购物车编号 +} +type FsOrderDetailModel struct { + db *gorm.DB +} + +func NewFsOrderDetailModel(db *gorm.DB) *FsOrderDetailModel { + return &FsOrderDetailModel{db} +} + +func (od *FsOrderDetailModel) GetOrderDetailsByOrderId(ctx context.Context, orderId int64) (resp []FsOrderDetail, err error) { + err = od.db.WithContext(ctx).Model(&FsOrderDetail{}).Where("`order_id` = ?", orderId).Find(&resp).Error + if err != nil { + return nil, err + } + return +} diff --git a/model/gmodel/fsorderdetailtemplatemodel.go b/model/gmodel/fsorderdetailtemplatemodel.go new file mode 100755 index 00000000..02c72e23 --- /dev/null +++ b/model/gmodel/fsorderdetailtemplatemodel.go @@ -0,0 +1,38 @@ +package gmodel + +import ( + "context" + "gorm.io/gorm" +) + +type FsOrderDetailTemplate struct { + Id int64 `gorm:"primary_key" json:"id"` + Sn *string `gorm:"default:''" json:"sn"` // 唯一编码 + ProductId *int64 `gorm:"default:0" json:"product_id"` // 产品ID + ModelId *int64 `gorm:"default:0" json:"model_id"` // 模型ID + TemplateId *int64 `gorm:"default:0" json:"template_id"` // 模板ID + MaterialId *int64 `gorm:"default:0" json:"material_id"` // 材质id + SizeId *int64 `gorm:"default:0" json:"size_id"` // 尺寸id + EachBoxNum *int64 `gorm:"default:0" json:"each_box_num"` // 每一箱的个数 + EachBoxWeight *float64 `gorm:"default:0.00" json:"each_box_weight"` // 每一箱的重量 单位KG + DesignId *int64 `gorm:"default:0" json:"design_id"` // 设计ID + Ctime *int64 `gorm:"default:0" json:"ctime"` // 添加时间 +} +type FsOrderDetailTemplateModel struct { + db *gorm.DB +} + +func NewFsOrderDetailTemplateModel(db *gorm.DB) *FsOrderDetailTemplateModel { + return &FsOrderDetailTemplateModel{db} +} + +func (dt *FsOrderDetailTemplateModel) GetListByIds(ctx context.Context, ids []int64) (resp []FsOrderDetailTemplate, err error) { + if len(ids) == 0 { + return + } + err = dt.db.WithContext(ctx).Model(&FsOrderDetailTemplate{}).Where("`id` in (?)", ids).Find(&resp).Error + if err != nil { + return nil, err + } + return +} diff --git a/model/gmodel/fsordermodel.go b/model/gmodel/fsordermodel.go new file mode 100755 index 00000000..43f74cfd --- /dev/null +++ b/model/gmodel/fsordermodel.go @@ -0,0 +1,62 @@ +package gmodel + +import ( + "context" + "errors" + "gorm.io/gorm" + "time" +) + +type FsOrder struct { + Id int64 `gorm:"primary_key" json:"id"` + Sn *string `gorm:"default:''" json:"sn"` // 订单编号 FS211224OL2XDKNP + UserId *int64 `gorm:"default:0" json:"user_id"` // 用户ID + SellerUserId *int64 `gorm:"default:0" json:"seller_user_id"` // 销售员ID 0:自主下单 + TotalAmount *int64 `gorm:"default:0" json:"total_amount"` // 总价 + PayedAmount *int64 `gorm:"default:0" json:"payed_amount"` // 已支付金额 + PayMethod *int64 `gorm:"default:0" json:"pay_method"` // 支付方式 1paypal 2strip + Ctime *int64 `gorm:"default:0" json:"ctime"` // 添加时间 + Utime *int64 `gorm:"default:0" json:"utime"` // 更新时间 + Ptime *int64 `gorm:"default:0" json:"ptime"` // 最后一次 支付时间(可能多次支付) + AddressId *int64 `gorm:"default:0" json:"address_id"` // 地址ID或者云仓ID + DeliveryMethod *int64 `gorm:"default:0" json:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 + CustomerMark *string `gorm:"default:''" json:"customer_mark"` // 客户备注 + Mark *string `gorm:"default:''" json:"mark"` // 后台订单备注 + AddressInfo *string `gorm:"default:''" json:"address_info"` // 详细地址信息JSON + IsSup *int64 `gorm:"default:0" json:"is_sup"` // 0不是补货 1是补货 + Status *int64 `gorm:"default:0" json:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) + IsPartPay *int64 `gorm:"default:0" json:"is_part_pay"` // 是否部分支付(0:否,1:是) + IsPayCompleted *int64 `gorm:"default:0" json:"is_pay_completed"` // 是否支付完成(0:否,1:是) + IsPartProduct *int64 `gorm:"default:0" json:"is_part_product"` // 是否部分生产(0:否,1:是) + IsPartProductCompleted *int64 `gorm:"default:0" json:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) + IsAllProduct *int64 `gorm:"default:0" json:"is_all_product"` // 是否全部生产(0:否,1:是) + IsAllProductCompleted *int64 `gorm:"default:0" json:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) + IsPartDelivery *int64 `gorm:"default:0" json:"is_part_delivery"` // 是否部分发货(0:否,1:是) + IsDeliveryCompleted *int64 `gorm:"default:0" json:"is_delivery_completed"` // 是否发货完成(0:否,1:是) + IsComplated *int64 `gorm:"default:0" json:"is_complated"` // 是否完成订单(0:否,1:是) + IsCancel *int64 `gorm:"default:0" json:"is_cancel"` // 是否取消订单(0:否,1:是) + IsRefunding *int64 `gorm:"default:0" json:"is_refunding"` // 是否退款中(0:否,1:是) + IsRefunded *int64 `gorm:"default:0" json:"is_refunded"` // 是否退款完成(0:否,1:是) + IsDeleted *int64 `gorm:"default:0" json:"is_deleted"` // 是否删除(0:否,1:是) + RefundReasonId *int64 `gorm:"default:0" json:"refund_reason_id"` // 取消订单原因ID + RefundReason *string `gorm:"default:''" json:"refund_reason"` // 取消订单原因 + TsTime *time.Time `gorm:"" json:"ts_time"` + IsSure *int64 `gorm:"default:0" json:"is_sure"` // 是否确认订单 1确认0未确认 + DeliverSn *string `gorm:"default:''" json:"deliver_sn"` // 发货单号 + EmailTime *int64 `gorm:"default:0" json:"email_time"` // 邮件发送时间 +} +type FsOrderModel struct { + db *gorm.DB +} + +func NewFsOrderModel(db *gorm.DB) *FsOrderModel { + return &FsOrderModel{db} +} + +func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) (resp FsOrder, err error) { + err = o.db.WithContext(ctx).Model(&FsOrder{}).Where(" `user_id` = ? and `sn` = ? ", userId, sn).First(&resp).Error + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return FsOrder{}, err + } + return resp, nil +} diff --git a/server/canteen/internal/logic/savecanteentypeproductlogic.go b/server/canteen/internal/logic/savecanteentypeproductlogic.go index 7ef8e52d..69117664 100644 --- a/server/canteen/internal/logic/savecanteentypeproductlogic.go +++ b/server/canteen/internal/logic/savecanteentypeproductlogic.go @@ -31,7 +31,7 @@ func NewSaveCanteenTypeProductLogic(ctx context.Context, svcCtx *svc.ServiceCont // 保存餐厅类型的关联产品 func (l *SaveCanteenTypeProductLogic) SaveCanteenTypeProduct(req *types.SaveCanteenTypeProductReq, loginInfo *auth.UserInfo) (resp *basic.Response) { if len(req.ProductList) == 0 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "product list can`t be empty") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "product list can`t be empty") } canteenProductModel := gmodel.NewFsCanteenProductModel(l.svcCtx.MysqlConn) //获取原有餐厅类型的所有产品 diff --git a/server/shopping-cart-confirmation/internal/handler/cartorderdetailhandler.go b/server/shopping-cart-confirmation/internal/handler/cartorderdetailhandler.go new file mode 100644 index 00000000..f2f23523 --- /dev/null +++ b/server/shopping-cart-confirmation/internal/handler/cartorderdetailhandler.go @@ -0,0 +1,67 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart-confirmation/internal/logic" + "fusenapi/server/shopping-cart-confirmation/internal/svc" + "fusenapi/server/shopping-cart-confirmation/internal/types" +) + +func CartOrderDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // 解析jwtToken + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + // 从Token里获取对应的信息 + userinfo, err := auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + var req types.CartOrderDetailReq + // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + // 创建一个业务逻辑层实例 + l := logic.NewCartOrderDetailLogic(r.Context(), svcCtx) + resp := l.CartOrderDetail(&req, userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + // 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。 + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/shopping-cart-confirmation/internal/handler/routes.go b/server/shopping-cart-confirmation/internal/handler/routes.go index a3a88832..376133e9 100644 --- a/server/shopping-cart-confirmation/internal/handler/routes.go +++ b/server/shopping-cart-confirmation/internal/handler/routes.go @@ -32,6 +32,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/cart/list", Handler: CartListHandler(serverCtx), }, + { + Method: http.MethodGet, + Path: "/cart/order-detail", + Handler: CartOrderDetailHandler(serverCtx), + }, }, ) } diff --git a/server/shopping-cart-confirmation/internal/logic/cartaddlogic.go b/server/shopping-cart-confirmation/internal/logic/cartaddlogic.go index 1807f54a..b224a166 100644 --- a/server/shopping-cart-confirmation/internal/logic/cartaddlogic.go +++ b/server/shopping-cart-confirmation/internal/logic/cartaddlogic.go @@ -32,14 +32,14 @@ func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLo // 添加入购物车 func (l *CartAddLogic) CartAdd(req *types.CartAddReq, userinfo *auth.UserInfo) (resp *basic.Response) { if req.BuyNum == 0 { - return resp.SetStatusWithMessage(basic.CodeApiErr, "param buy_num can`t be 0") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param buy_num can`t be 0") } if req.IsCheck != 0 && req.IsCheck != 1 { - return resp.SetStatusWithMessage(basic.CodeApiErr, "param is_check should be 0 or 1") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param is_check should be 0 or 1") } req.DesignId = strings.Trim(req.DesignId, " ") if req.DesignId == "" { - return resp.SetStatusWithMessage(basic.CodeApiErr, "param design_id can`t be empty") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param design_id can`t be empty") } //查询是否有此设计 productDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) diff --git a/server/shopping-cart-confirmation/internal/logic/cartdeletelogic.go b/server/shopping-cart-confirmation/internal/logic/cartdeletelogic.go index 5c9edbcf..a58f7b63 100644 --- a/server/shopping-cart-confirmation/internal/logic/cartdeletelogic.go +++ b/server/shopping-cart-confirmation/internal/logic/cartdeletelogic.go @@ -29,7 +29,7 @@ func NewCartDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartDe func (l *CartDeleteLogic) CartDelete(req *types.CartDeleteReq, userinfo *auth.UserInfo) (resp *basic.Response) { if req.Id <= 0 { - return resp.SetStatusWithMessage(basic.CodeApiErr, "invalid param id") + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid param id") } cartModel := gmodel.NewFsCartModel(l.svcCtx.MysqlConn) status := int64(0) diff --git a/server/shopping-cart-confirmation/internal/logic/cartorderdetaillogic.go b/server/shopping-cart-confirmation/internal/logic/cartorderdetaillogic.go new file mode 100644 index 00000000..a699c2f1 --- /dev/null +++ b/server/shopping-cart-confirmation/internal/logic/cartorderdetaillogic.go @@ -0,0 +1,175 @@ +package logic + +import ( + "fmt" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "strings" + "time" + + "context" + + "fusenapi/server/shopping-cart-confirmation/internal/svc" + "fusenapi/server/shopping-cart-confirmation/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CartOrderDetailLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewCartOrderDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartOrderDetailLogic { + return &CartOrderDetailLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CartOrderDetailLogic) CartOrderDetail(req *types.CartOrderDetailReq, userinfo *auth.UserInfo) (resp *basic.Response) { + req.Sn = strings.Trim(req.Sn, " ") + if req.Sn == "" { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required") + } + //获取订单数据 + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + if orderInfo.Id == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the order is not exists") + } + //获取订单详细数据 + orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) + orderDetailList, err := orderDetailModel.GetOrderDetailsByOrderId(l.ctx, orderInfo.Id) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order details") + } + if len(orderDetailList) == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "order details is empty") + } + orderDetailTemplateIds := make([]int64, 0, len(orderDetailList)) + productIds := make([]int64, 0, len(orderDetailList)) + for _, v := range orderDetailList { + orderDetailTemplateIds = append(orderDetailTemplateIds, *v.OrderDetailTemplateId) + productIds = append(productIds, *v.ProductId) + } + //获取订单详情对应模板信息 + orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) + orderDetailTemplateList, err := orderDetailTemplateModel.GetListByIds(l.ctx, orderDetailTemplateIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order details templates") + } + sizeIds := make([]int64, 0, len(orderDetailTemplateList)) + mapDetailTemplate := make(map[int64]int) + for k, v := range orderDetailTemplateList { + sizeIds = append(sizeIds, *v.SizeId) + mapDetailTemplate[v.Id] = k + } + //获取尺寸信息 + productSizeModel := gmodel.NewFsProductSizeModel(l.svcCtx.MysqlConn) + productSizeList, err := productSizeModel.GetAllByIds(l.ctx, sizeIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product size list") + } + mapProductSize := make(map[int64]int) + for k, v := range productSizeList { + mapProductSize[v.Id] = k + } + //获取产品信息 + productModel := gmodel.NewFsProductModel(l.svcCtx.MysqlConn) + productList, err := productModel.GetProductListByIds(l.ctx, productIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order products") + } + mapProduct := make(map[int64]int) + for k, v := range productList { + mapProduct[v.Id] = k + } + //获取用户地址信息 + addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) + addressList, err := addressModel.GetUserAllAddress(l.ctx, userinfo.UserId) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address") + } + //处理订单数据 + addressItems := make([]types.CartAddr, 0, len(addressList)) + for _, v := range addressList { + addressItems = append(addressItems, types.CartAddr{ + Id: v.Id, + Name: *v.Name, + FirstName: *v.FirstName, + LastName: *v.LastName, + Mobile: *v.Mobile, + Street: *v.Street, + Suite: *v.Suite, + City: *v.City, + State: *v.State, + ZipCode: *v.ZipCode, + IsDefault: *v.IsDefault, + }) + } + items := make([]types.CartDetailItem, 0, len(orderDetailList)) + totalAmount := int64(0) //订单总金额 + for _, v := range orderDetailList { + thisTotal := (*v.BuyNum) * (*v.Amount) + size := "" + if detailTemplateIndex, ok := mapDetailTemplate[*v.OrderDetailTemplateId]; ok { + detailTemplate := orderDetailTemplateList[detailTemplateIndex] + if sizeIndex, ok := mapProductSize[*detailTemplate.SizeId]; ok { + size = *productSizeList[sizeIndex].Capacity + } + } + name := "" + if productIndex, ok := mapProduct[*v.ProductId]; ok { + name = *productList[productIndex].Title + } + items = append(items, types.CartDetailItem{ + Cover: *v.Cover, + Pcs: *v.BuyNum, + Amount: fmt.Sprintf("$ %.2f", float64(thisTotal)/100), + Option: *v.OptionalTitle, + Size: size, + Name: name, + }) + totalAmount += thisTotal + } + //首付50% + total := totalAmount / 2 + //尾款 + remaining := totalAmount - total + payStep := int64(0) //未支付 + if *orderInfo.PayedAmount == *orderInfo.TotalAmount/2 { + payStep = 1 //已支付首款 + } + if *orderInfo.PayedAmount == *orderInfo.TotalAmount { + payStep = 2 //已支付尾款 + } + payTime := "" + if *orderInfo.Ptime != 0 { + payTime = time.Unix(*orderInfo.Ptime, 0).Format("2006-01-02 15:04:05") + } + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CartOrderDetailRsp{ + DeliveryMethod: 1, + AddressId: 0, + PayTime: payTime, + PayMethod: 1, + PayStep: payStep, + Subtotal: fmt.Sprintf("$%.2f", float64(totalAmount)/100), + Total: fmt.Sprintf("$%.2f", float64(total)/100), + Remaining: fmt.Sprintf("$%.2f", float64(remaining)/100), + AddrList: addressItems, + Items: items, + }) +} diff --git a/server/shopping-cart-confirmation/internal/types/types.go b/server/shopping-cart-confirmation/internal/types/types.go index 98a5a2c9..f7594cc7 100644 --- a/server/shopping-cart-confirmation/internal/types/types.go +++ b/server/shopping-cart-confirmation/internal/types/types.go @@ -57,6 +57,46 @@ type CartSizeItem struct { Inch string `json:"inch"` } +type CartOrderDetailReq struct { + Sn string `form:"sn"` +} + +type CartOrderDetailRsp struct { + DeliveryMethod int64 `json:"delivery_method"` + AddressId int64 `json:"address_id"` + PayTime string `json:"pay_time"` + PayMethod int64 `json:"pay_method"` + PayStep int64 `json:"pay_step"` + Subtotal string `json:"subtotal"` + Total string `json:"total"` + Remaining string `json:"remaining"` + AddrList []CartAddr `json:"addr_list"` + Items []CartDetailItem `json:"items"` +} + +type CartDetailItem struct { + Cover string `json:"cover"` + Pcs int64 `json:"pcs"` + Amount string `json:"amount"` + Option string `json:"option"` + Size string `json:"size"` + Name string `json:"name"` +} + +type CartAddr struct { + Id int64 `json:"id"` + Name string `json:"name"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Mobile string `json:"mobile"` + Street string `json:"street"` + Suite string `json:"suite"` + City string `json:"city"` + State string `json:"state"` + ZipCode string `json:"zip_code"` + IsDefault int64 `json:"is_default"` +} + type Response struct { Code int `json:"code"` Message string `json:"msg"` diff --git a/server_api/shopping-cart-confirmation.api b/server_api/shopping-cart-confirmation.api index 1de7d33f..4aefe8a8 100644 --- a/server_api/shopping-cart-confirmation.api +++ b/server_api/shopping-cart-confirmation.api @@ -20,6 +20,9 @@ service shopping-cart-confirmation { //获取用户购物车列表 @handler CartListHandler get /cart/list (CartListReq) returns (response); + //获取用户购物车订单详情 + @handler CartOrderDetailHandler + get /cart/order-detail (CartOrderDetailReq) returns (response); } //添加入购物车 @@ -69,4 +72,41 @@ type PcsItem { type CartSizeItem { Cm string `json:"cm"` Inch string `json:"inch"` +} +//获取用户购物车订单详情 +type CartOrderDetailReq { + Sn string `form:"sn"` +} +type CartOrderDetailRsp { + DeliveryMethod int64 `json:"delivery_method"` + AddressId int64 `json:"address_id"` + PayTime string `json:"pay_time"` + PayMethod int64 `json:"pay_method"` + PayStep int64 `json:"pay_step"` + Subtotal string `json:"subtotal"` + Total string `json:"total"` + Remaining string `json:"remaining"` + AddrList []CartAddr `json:"addr_list"` + Items []CartDetailItem `json:"items"` +} +type CartDetailItem { + Cover string `json:"cover"` + Pcs int64 `json:"pcs"` + Amount string `json:"amount"` + Option string `json:"option"` + Size string `json:"size"` + Name string `json:"name"` +} +type CartAddr { + Id int64 `json:"id"` + Name string `json:"name"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Mobile string `json:"mobile"` + Street string `json:"street"` + Suite string `json:"suite"` + City string `json:"city"` + State string `json:"state"` + ZipCode string `json:"zip_code"` + IsDefault int64 `json:"is_default"` } \ No newline at end of file diff --git a/utils/basic/basic.go b/utils/basic/basic.go index c5bcc5b2..e9197a77 100644 --- a/utils/basic/basic.go +++ b/utils/basic/basic.go @@ -13,7 +13,8 @@ var ( CodeServiceErr = &StatusResponse{510, "server logic error"} // server logic 错误 CodeUnAuth = &StatusResponse{401, "unauthorized"} // 未授权 - CodeUpdateErr = &StatusResponse{5000, "update database error"} // update database logic 错误 + CodeUpdateErr = &StatusResponse{5000, "update database error"} // update database logic 错误 + CodeRequestParamsErr = &StatusResponse{5001, "invalid request param"} // api参数校验 错误 ) type Response struct { From 5b2eef4822bca557580d8ac1aa3fe96dbbf41bca Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 14:57:20 +0800 Subject: [PATCH 2/6] fix --- server/map_library/etc/map-library.yaml | 8 + server/map_library/internal/config/config.go | 12 ++ .../handler/getmaplibrarylisthandler.go | 55 +++++++ server/map_library/internal/handler/routes.go | 22 +++ .../internal/logic/getmaplibrarylistlogic.go | 29 ++++ .../internal/svc/servicecontext.go | 50 +++++++ server/map_library/internal/types/types.go | 138 ++++++++++++++++++ server/map_library/map-library.go | 49 +++++++ server_api/map_library.api | 82 +++++++++++ 9 files changed, 445 insertions(+) create mode 100644 server/map_library/etc/map-library.yaml create mode 100644 server/map_library/internal/config/config.go create mode 100644 server/map_library/internal/handler/getmaplibrarylisthandler.go create mode 100644 server/map_library/internal/handler/routes.go create mode 100644 server/map_library/internal/logic/getmaplibrarylistlogic.go create mode 100644 server/map_library/internal/svc/servicecontext.go create mode 100644 server/map_library/internal/types/types.go create mode 100644 server/map_library/map-library.go create mode 100644 server_api/map_library.api diff --git a/server/map_library/etc/map-library.yaml b/server/map_library/etc/map-library.yaml new file mode 100644 index 00000000..1d2ac64b --- /dev/null +++ b/server/map_library/etc/map-library.yaml @@ -0,0 +1,8 @@ +Name: map-library +Host: 0.0.0.0 +Port: 8893 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 60 + RefreshAfter: 60 \ No newline at end of file diff --git a/server/map_library/internal/config/config.go b/server/map_library/internal/config/config.go new file mode 100644 index 00000000..f9c9e9fd --- /dev/null +++ b/server/map_library/internal/config/config.go @@ -0,0 +1,12 @@ +package config + +import ( + "fusenapi/server/map_library/internal/types" + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth +} diff --git a/server/map_library/internal/handler/getmaplibrarylisthandler.go b/server/map_library/internal/handler/getmaplibrarylisthandler.go new file mode 100644 index 00000000..f81221e0 --- /dev/null +++ b/server/map_library/internal/handler/getmaplibrarylisthandler.go @@ -0,0 +1,55 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/map_library/internal/logic" + "fusenapi/server/map_library/internal/svc" +) + +func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // 解析jwtToken + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + // 从Token里获取对应的信息 + userinfo, err := auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + l := logic.NewGetMapLibraryListLogic(r.Context(), svcCtx) + resp := l.GetMapLibraryList(userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + // 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。 + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/map_library/internal/handler/routes.go b/server/map_library/internal/handler/routes.go new file mode 100644 index 00000000..2e9984d4 --- /dev/null +++ b/server/map_library/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/map_library/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodGet, + Path: "/map-library/list", + Handler: GetMapLibraryListHandler(serverCtx), + }, + }, + ) +} diff --git a/server/map_library/internal/logic/getmaplibrarylistlogic.go b/server/map_library/internal/logic/getmaplibrarylistlogic.go new file mode 100644 index 00000000..393f59b6 --- /dev/null +++ b/server/map_library/internal/logic/getmaplibrarylistlogic.go @@ -0,0 +1,29 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/map_library/internal/svc" + "github.com/zeromicro/go-zero/core/logx" +) + +type GetMapLibraryListLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMapLibraryListLogic { + return &GetMapLibraryListLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetMapLibraryListLogic) GetMapLibraryList(userinfo *auth.UserInfo) (resp *basic.Response) { + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/map_library/internal/svc/servicecontext.go b/server/map_library/internal/svc/servicecontext.go new file mode 100644 index 00000000..b02b6d54 --- /dev/null +++ b/server/map_library/internal/svc/servicecontext.go @@ -0,0 +1,50 @@ +package svc + +import ( + "errors" + "fusenapi/initalize" + "fusenapi/server/map_library/internal/config" + "github.com/golang-jwt/jwt" + "gorm.io/gorm" + "net/http" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.DataSource), + } +} + +func (svcCxt *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return svcCxt.Config.Auth.AccessSecret, nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/map_library/internal/types/types.go b/server/map_library/internal/types/types.go new file mode 100644 index 00000000..31ebf05e --- /dev/null +++ b/server/map_library/internal/types/types.go @@ -0,0 +1,138 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type GetMapLibraryListRsp struct { + Mid int64 `json:"mid"` + Ctime string `json:"ctime"` + Tag MapLibraryListTag `json:"tag"` + Info MapLibraryListInfo `json:"info"` +} + +type MapLibraryListInfo struct { + Id string `json:"id"` + Tag string `json:"tag"` + Title string `json:"title"` + Type string `json:"type"` + Text string `json:"text"` + Fill string `json:"fill"` + FontSize int64 `json:"fontSize"` + FontFamily string `json:"fontFamily"` + IfBr bool `json:"ifBr"` + IfShow bool `json:"ifShow"` + IfGroup bool `json:"ifGroup"` + MaxNum int64 `json:"maxNum"` + Rotation int64 `json:"rotation"` + Align string `json:"align"` + VerticalAlign string `json:"verticalAlign"` + Material string `json:"material"` + QRcodeType string `json:"QRcodeType"` + Width float64 `json:"width"` + Height float64 `json:"height"` + X float64 `json:"x"` + Y float64 `json:"y"` + Opacity int64 `json:"opacity"` + OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"` + ZIndex int64 `json:"zIndex"` + SvgPath string `json:"svgPath"` + Follow MapLibraryListFollow `json:"follow"` + Group []MapLibraryListGroup `json:"group"` + CameraStand MapLibraryListCameraStand `json:"cameraStand"` + MaterialTime string `json:"materialTime"` + MaterialName string `json:"materialName"` +} + +type MapLibraryListCameraStand struct { + X int64 `json:"x"` + Y int64 `json:"y"` + Z int64 `json:"z"` +} + +type MapLibraryListGroup struct { + Tag string `json:"tag"` + Text string `json:"text"` + Title string `json:"title"` + IfBr bool `json:"ifBr"` + IfShow bool `json:"ifShow"` + MaxNum int64 `json:"maxNum"` +} + +type MapLibraryListFollow struct { + Fill string `json:"fill"` + IfShow string `json:"ifShow"` + Content string `json:"content"` +} + +type MapLibraryListOptionalColorItem struct { + Color string `json:"color"` + Name string `json:"name"` + Default bool `json:"default"` +} + +type MapLibraryListTag struct { + Id int64 `json:"id"` + Title string `json:"title"` +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type ResponseJwt struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) *Response { + return &Response{ + Code: Code, + Message: Message, + } +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { + return &Response{ + Code: Code, + Message: Message, + Data: Data, + } +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response { + newResp := &Response{ + Code: sr.Code, + Message: msg, + } + if len(data) == 1 { + newResp.Data = data[0] + } + return newResp +} diff --git a/server/map_library/map-library.go b/server/map_library/map-library.go new file mode 100644 index 00000000..d0622347 --- /dev/null +++ b/server/map_library/map-library.go @@ -0,0 +1,49 @@ +package main + +import ( + "flag" + "fmt" + + "fusenapi/server/map_library/internal/config" + "fusenapi/server/map_library/internal/handler" + "fusenapi/server/map_library/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/map-library.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} + +// var testConfigFile = flag.String("f", "../etc/map-library.yaml", "the config file") +// var cnf config.Config + +// func GetTestServer() *rest.Server { +// flag.Parse() + +// conf.MustLoad(*testConfigFile, &cnf) + +// server := rest.MustNewServer(cnf.RestConf) +// defer server.Stop() + +// ctx := svc.NewServiceContext(cnf) +// handler.RegisterHandlers(server, ctx) + +// fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port) +// return server +// } diff --git a/server_api/map_library.api b/server_api/map_library.api new file mode 100644 index 00000000..d752b57c --- /dev/null +++ b/server_api/map_library.api @@ -0,0 +1,82 @@ +syntax = "v1" + +info ( + title: "贴图库服务"// TODO: add title + desc: // TODO: add description + author: "" + email: "" +) +import "basic.api" + +service map-library { + //获取贴图库列表 + @handler GetMapLibraryListHandler + get /map-library/list ( ) returns (response); +} + +//获取贴图库列表 +type GetMapLibraryListRsp { + Mid int64 `json:"mid"` + Ctime string `json:"ctime"` + Tag MapLibraryListTag `json:"tag"` + Info MapLibraryListInfo `json:"info"` +} +type MapLibraryListInfo { + Id string `json:"id"` + Tag string `json:"tag"` + Title string `json:"title"` + Type string `json:"type"` + Text string `json:"text"` + Fill string `json:"fill"` + FontSize int64 `json:"fontSize"` + FontFamily string `json:"fontFamily"` + IfBr bool `json:"ifBr"` + IfShow bool `json:"ifShow"` + IfGroup bool `json:"ifGroup"` + MaxNum int64 `json:"maxNum"` + Rotation int64 `json:"rotation"` + Align string `json:"align"` + VerticalAlign string `json:"verticalAlign"` + Material string `json:"material"` + QRcodeType string `json:"QRcodeType"` + Width float64 `json:"width"` + Height float64 `json:"height"` + X float64 `json:"x"` + Y float64 `json:"y"` + Opacity int64 `json:"opacity"` + OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"` + ZIndex int64 `json:"zIndex"` + SvgPath string `json:"svgPath"` + Follow MapLibraryListFollow `json:"follow"` + Group []MapLibraryListGroup `json:"group"` + CameraStand MapLibraryListCameraStand `json:"cameraStand"` + MaterialTime string `json:"materialTime"` + MaterialName string `json:"materialName"` +} +type MapLibraryListCameraStand { + X int64 `json:"x"` + Y int64 `json:"y"` + Z int64 `json:"z"` +} +type MapLibraryListGroup { + Tag string `json:"tag"` + Text string `json:"text"` + Title string `json:"title"` + IfBr bool `json:"ifBr"` + IfShow bool `json:"ifShow"` + MaxNum int64 `json:"maxNum"` +} +type MapLibraryListFollow { + Fill string `json:"fill"` + IfShow string `json:"ifShow"` + Content string `json:"content"` +} +type MapLibraryListOptionalColorItem { + Color string `json:"color"` + Name string `json:"name"` + Default bool `json:"default"` +} +type MapLibraryListTag { + Id int64 `json:"id"` + Title string `json:"title"` +} \ No newline at end of file From 83e45f26b2e1610ca99595444defcd0ddaab8618 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 15:45:56 +0800 Subject: [PATCH 3/6] fix --- ddl/fs_map_library.sql | 12 +++ goctl_template/api/context.tpl | 2 +- model/fsmaplibrarymodel.go | 24 +++++ model/fsmaplibrarymodel_gen.go | 89 +++++++++++++++++++ model/gmodel/fsmaplibrarymodel.go | 31 +++++++ model/gmodel/fsproducttemplatetagsmodel.go | 16 +++- .../handler/getmaplibrarylisthandler.go | 10 +-- .../internal/logic/getmaplibrarylistlogic.go | 50 +++++++++++ .../internal/svc/servicecontext.go | 3 +- 9 files changed, 228 insertions(+), 9 deletions(-) create mode 100644 ddl/fs_map_library.sql create mode 100755 model/fsmaplibrarymodel.go create mode 100755 model/fsmaplibrarymodel_gen.go create mode 100755 model/gmodel/fsmaplibrarymodel.go diff --git a/ddl/fs_map_library.sql b/ddl/fs_map_library.sql new file mode 100644 index 00000000..1d1a10a3 --- /dev/null +++ b/ddl/fs_map_library.sql @@ -0,0 +1,12 @@ +-- fusentest.fs_map_library definition + +CREATE TABLE `fs_map_library` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Id', + `title` varchar(255) NOT NULL DEFAULT '' COMMENT '名称', + `info` text NOT NULL COMMENT '贴图数据', + `sort` smallint(5) NOT NULL DEFAULT '0' COMMENT '排序', + `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态 1启用', + `ctime` int(10) NOT NULL DEFAULT '0' COMMENT '创建时间', + `tag_id` int(10) NOT NULL DEFAULT '0' COMMENT '模板标签id', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='贴图库'; \ No newline at end of file diff --git a/goctl_template/api/context.tpl b/goctl_template/api/context.tpl index 26bd8a5d..1bb0c6c5 100644 --- a/goctl_template/api/context.tpl +++ b/goctl_template/api/context.tpl @@ -19,7 +19,7 @@ func NewServiceContext(c {{.config}}) *ServiceContext { return &ServiceContext{ Config: c, - MysqlConn: initalize.InitMysql(c.DataSource), + MysqlConn: initalize.InitMysql(c.SourceMysql), {{.middlewareAssignment}} } } diff --git a/model/fsmaplibrarymodel.go b/model/fsmaplibrarymodel.go new file mode 100755 index 00000000..c3c7d0e7 --- /dev/null +++ b/model/fsmaplibrarymodel.go @@ -0,0 +1,24 @@ +package model + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var _ FsMapLibraryModel = (*customFsMapLibraryModel)(nil) + +type ( + // FsMapLibraryModel is an interface to be customized, add more methods here, + // and implement the added methods in customFsMapLibraryModel. + FsMapLibraryModel interface { + fsMapLibraryModel + } + + customFsMapLibraryModel struct { + *defaultFsMapLibraryModel + } +) + +// NewFsMapLibraryModel returns a model for the database table. +func NewFsMapLibraryModel(conn sqlx.SqlConn) FsMapLibraryModel { + return &customFsMapLibraryModel{ + defaultFsMapLibraryModel: newFsMapLibraryModel(conn), + } +} diff --git a/model/fsmaplibrarymodel_gen.go b/model/fsmaplibrarymodel_gen.go new file mode 100755 index 00000000..2b662b7f --- /dev/null +++ b/model/fsmaplibrarymodel_gen.go @@ -0,0 +1,89 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + fsMapLibraryFieldNames = builder.RawFieldNames(&FsMapLibrary{}) + fsMapLibraryRows = strings.Join(fsMapLibraryFieldNames, ",") + fsMapLibraryRowsExpectAutoSet = strings.Join(stringx.Remove(fsMapLibraryFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") + fsMapLibraryRowsWithPlaceHolder = strings.Join(stringx.Remove(fsMapLibraryFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), "=?,") + "=?" +) + +type ( + fsMapLibraryModel interface { + Insert(ctx context.Context, data *FsMapLibrary) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*FsMapLibrary, error) + Update(ctx context.Context, data *FsMapLibrary) error + Delete(ctx context.Context, id int64) error + } + + defaultFsMapLibraryModel struct { + conn sqlx.SqlConn + table string + } + + FsMapLibrary struct { + Id int64 `db:"id"` // Id + Title string `db:"title"` // 名称 + Info string `db:"info"` // 贴图数据 + Sort int64 `db:"sort"` // 排序 + Status int64 `db:"status"` // 状态 1启用 + Ctime int64 `db:"ctime"` // 创建时间 + TagId int64 `db:"tag_id"` // 模板标签id + } +) + +func newFsMapLibraryModel(conn sqlx.SqlConn) *defaultFsMapLibraryModel { + return &defaultFsMapLibraryModel{ + conn: conn, + table: "`fs_map_library`", + } +} + +func (m *defaultFsMapLibraryModel) Delete(ctx context.Context, id int64) error { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + _, err := m.conn.ExecCtx(ctx, query, id) + return err +} + +func (m *defaultFsMapLibraryModel) FindOne(ctx context.Context, id int64) (*FsMapLibrary, error) { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", fsMapLibraryRows, m.table) + var resp FsMapLibrary + err := m.conn.QueryRowCtx(ctx, &resp, query, id) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultFsMapLibraryModel) Insert(ctx context.Context, data *FsMapLibrary) (sql.Result, error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, fsMapLibraryRowsExpectAutoSet) + ret, err := m.conn.ExecCtx(ctx, query, data.Title, data.Info, data.Sort, data.Status, data.Ctime, data.TagId) + return ret, err +} + +func (m *defaultFsMapLibraryModel) Update(ctx context.Context, data *FsMapLibrary) error { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, fsMapLibraryRowsWithPlaceHolder) + _, err := m.conn.ExecCtx(ctx, query, data.Title, data.Info, data.Sort, data.Status, data.Ctime, data.TagId, data.Id) + return err +} + +func (m *defaultFsMapLibraryModel) tableName() string { + return m.table +} diff --git a/model/gmodel/fsmaplibrarymodel.go b/model/gmodel/fsmaplibrarymodel.go new file mode 100755 index 00000000..1084e333 --- /dev/null +++ b/model/gmodel/fsmaplibrarymodel.go @@ -0,0 +1,31 @@ +package gmodel + +import ( + "context" + "gorm.io/gorm" +) + +type FsMapLibrary struct { + Id int64 `gorm:"primary_key" json:"id"` // Id + Title *string `gorm:"default:''" json:"title"` // 名称 + Info *string `gorm:"default:''" json:"info"` // 贴图数据 + Sort *int64 `gorm:"default:0" json:"sort"` // 排序 + Status *int64 `gorm:"default:1" json:"status"` // 状态 1启用 0未启用 + Ctime *int64 `gorm:"default:0" json:"ctime"` // 创建时间 + TagId *int64 `gorm:"default:0" json:"tag_id"` // 模板标签id +} +type FsMapLibraryModel struct { + db *gorm.DB +} + +func NewFsMapLibraryModel(db *gorm.DB) *FsMapLibraryModel { + return &FsMapLibraryModel{db} +} + +func (ml *FsMapLibraryModel) GetAllEnabledList(ctx context.Context) (resp []FsMapLibrary, err error) { + err = ml.db.WithContext(ctx).Model(&FsMapLibrary{}).Where("`status` = ?", 1).Find(&resp).Error + if err != nil { + return nil, err + } + return +} diff --git a/model/gmodel/fsproducttemplatetagsmodel.go b/model/gmodel/fsproducttemplatetagsmodel.go index 22dc1ebd..81bc121e 100755 --- a/model/gmodel/fsproducttemplatetagsmodel.go +++ b/model/gmodel/fsproducttemplatetagsmodel.go @@ -1,6 +1,9 @@ package gmodel -import "gorm.io/gorm" +import ( + "context" + "gorm.io/gorm" +) type FsProductTemplateTags struct { Id int64 `gorm:"primary_key" json:"id"` // ID @@ -15,3 +18,14 @@ type FsProductTemplateTagsModel struct { func NewFsProductTemplateTagsModel(db *gorm.DB) *FsProductTemplateTagsModel { return &FsProductTemplateTagsModel{db} } + +func (pt *FsProductTemplateTagsModel) GetListByIds(ctx context.Context, ids []int64) (resp []FsProductTemplateTags, err error) { + if len(ids) == 0 { + return + } + err = pt.db.WithContext(ctx).Model(&FsProductTemplateTags{}).Where("`id` in (?)", ids).Find(&resp).Error + if err != nil { + return nil, err + } + return +} diff --git a/server/map_library/internal/handler/getmaplibrarylisthandler.go b/server/map_library/internal/handler/getmaplibrarylisthandler.go index f81221e0..bad5e65d 100644 --- a/server/map_library/internal/handler/getmaplibrarylisthandler.go +++ b/server/map_library/internal/handler/getmaplibrarylisthandler.go @@ -7,16 +7,14 @@ import ( "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" - "fusenapi/utils/auth" - "fusenapi/utils/basic" - "fusenapi/server/map_library/internal/logic" "fusenapi/server/map_library/internal/svc" + "fusenapi/utils/auth" ) func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - // 解析jwtToken + /*// 解析jwtToken claims, err := svcCtx.ParseJwtToken(r) // 如果解析出错,则返回未授权的JSON响应并记录错误消息 if err != nil { @@ -38,10 +36,10 @@ func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { }) logx.Info("unauthorized:", err.Error()) return - } + }*/ l := logic.NewGetMapLibraryListLogic(r.Context(), svcCtx) - resp := l.GetMapLibraryList(userinfo) + resp := l.GetMapLibraryList(&auth.UserInfo{86}) // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; // 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。 if resp != nil { diff --git a/server/map_library/internal/logic/getmaplibrarylistlogic.go b/server/map_library/internal/logic/getmaplibrarylistlogic.go index 393f59b6..fc393b47 100644 --- a/server/map_library/internal/logic/getmaplibrarylistlogic.go +++ b/server/map_library/internal/logic/getmaplibrarylistlogic.go @@ -1,8 +1,12 @@ package logic import ( + "encoding/json" + "fusenapi/model/gmodel" + "fusenapi/server/map_library/internal/types" "fusenapi/utils/auth" "fusenapi/utils/basic" + "time" "context" @@ -25,5 +29,51 @@ func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *GetMapLibraryListLogic) GetMapLibraryList(userinfo *auth.UserInfo) (resp *basic.Response) { + mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn) + mapLibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get map library list") + } + if len(mapLibraryList) == 0 { + return resp.SetStatus(basic.CodeOK) + } + productTemplateTagIds := make([]int64, 0, len(mapLibraryList)) + for _, v := range mapLibraryList { + productTemplateTagIds = append(productTemplateTagIds, *v.TagId) + } + //获取标签列表 + productTemplateTagsModel := gmodel.NewFsProductTemplateTagsModel(l.svcCtx.MysqlConn) + templateTagList, err := productTemplateTagsModel.GetListByIds(l.ctx, productTemplateTagIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product template tags") + } + mapTag := make(map[int64]int) + for k, v := range templateTagList { + mapTag[v.Id] = k + } + list := make([]types.GetMapLibraryListRsp, 0, len(mapLibraryList)) + for _, v := range mapLibraryList { + data := types.GetMapLibraryListRsp{ + Mid: v.Id, + Ctime: time.Unix(*v.Ctime, 0).Format("2006-01-02 15:04:05"), + } + //tag拼装 + if tagIndex, ok := mapTag[*v.TagId]; ok { + data.Tag = types.MapLibraryListTag{ + Id: templateTagList[tagIndex].Id, + Title: *templateTagList[tagIndex].Title, + } + } + //解析info + var info types.MapLibraryListInfo + if err = json.Unmarshal([]byte(*v.Info), &info); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "json parse info err") + } + data.Info = info + list = append(list, data) + } return resp.SetStatus(basic.CodeOK) } diff --git a/server/map_library/internal/svc/servicecontext.go b/server/map_library/internal/svc/servicecontext.go index b02b6d54..3d6acee1 100644 --- a/server/map_library/internal/svc/servicecontext.go +++ b/server/map_library/internal/svc/servicecontext.go @@ -2,6 +2,7 @@ package svc import ( "errors" + "fmt" "fusenapi/initalize" "fusenapi/server/map_library/internal/config" "github.com/golang-jwt/jwt" @@ -19,7 +20,7 @@ func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, - MysqlConn: initalize.InitMysql(c.DataSource), + MysqlConn: initalize.InitMysql(c.SourceMysql), } } From f7da17778edacadea1ef7c4c8880a963aebd0b83 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 16:04:43 +0800 Subject: [PATCH 4/6] fix --- model/gmodel/fsmaplibrarymodel.go | 2 +- .../internal/handler/getmaplibrarylisthandler.go | 10 ++++++---- .../internal/logic/getmaplibrarylistlogic.go | 2 +- server/map_library/internal/types/types.go | 4 ++-- server_api/map_library.api | 4 ++-- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/model/gmodel/fsmaplibrarymodel.go b/model/gmodel/fsmaplibrarymodel.go index 1084e333..58c02db6 100755 --- a/model/gmodel/fsmaplibrarymodel.go +++ b/model/gmodel/fsmaplibrarymodel.go @@ -23,7 +23,7 @@ func NewFsMapLibraryModel(db *gorm.DB) *FsMapLibraryModel { } func (ml *FsMapLibraryModel) GetAllEnabledList(ctx context.Context) (resp []FsMapLibrary, err error) { - err = ml.db.WithContext(ctx).Model(&FsMapLibrary{}).Where("`status` = ?", 1).Find(&resp).Error + err = ml.db.WithContext(ctx).Model(&FsMapLibrary{}).Where("`status` = ?", 0).Find(&resp).Error if err != nil { return nil, err } diff --git a/server/map_library/internal/handler/getmaplibrarylisthandler.go b/server/map_library/internal/handler/getmaplibrarylisthandler.go index bad5e65d..f81221e0 100644 --- a/server/map_library/internal/handler/getmaplibrarylisthandler.go +++ b/server/map_library/internal/handler/getmaplibrarylisthandler.go @@ -7,14 +7,16 @@ import ( "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "fusenapi/server/map_library/internal/logic" "fusenapi/server/map_library/internal/svc" - "fusenapi/utils/auth" ) func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - /*// 解析jwtToken + // 解析jwtToken claims, err := svcCtx.ParseJwtToken(r) // 如果解析出错,则返回未授权的JSON响应并记录错误消息 if err != nil { @@ -36,10 +38,10 @@ func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { }) logx.Info("unauthorized:", err.Error()) return - }*/ + } l := logic.NewGetMapLibraryListLogic(r.Context(), svcCtx) - resp := l.GetMapLibraryList(&auth.UserInfo{86}) + resp := l.GetMapLibraryList(userinfo) // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; // 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。 if resp != nil { diff --git a/server/map_library/internal/logic/getmaplibrarylistlogic.go b/server/map_library/internal/logic/getmaplibrarylistlogic.go index fc393b47..0cae21dc 100644 --- a/server/map_library/internal/logic/getmaplibrarylistlogic.go +++ b/server/map_library/internal/logic/getmaplibrarylistlogic.go @@ -75,5 +75,5 @@ func (l *GetMapLibraryListLogic) GetMapLibraryList(userinfo *auth.UserInfo) (res data.Info = info list = append(list, data) } - return resp.SetStatus(basic.CodeOK) + return resp.SetStatusWithMessage(basic.CodeOK, "success", list) } diff --git a/server/map_library/internal/types/types.go b/server/map_library/internal/types/types.go index 31ebf05e..75af6051 100644 --- a/server/map_library/internal/types/types.go +++ b/server/map_library/internal/types/types.go @@ -29,12 +29,12 @@ type MapLibraryListInfo struct { Align string `json:"align"` VerticalAlign string `json:"verticalAlign"` Material string `json:"material"` - QRcodeType string `json:"QRcodeType"` + QRcodeType int64 `json:"QRcodeType"` Width float64 `json:"width"` Height float64 `json:"height"` X float64 `json:"x"` Y float64 `json:"y"` - Opacity int64 `json:"opacity"` + Opacity float64 `json:"opacity"` OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"` ZIndex int64 `json:"zIndex"` SvgPath string `json:"svgPath"` diff --git a/server_api/map_library.api b/server_api/map_library.api index d752b57c..db3a3436 100644 --- a/server_api/map_library.api +++ b/server_api/map_library.api @@ -38,12 +38,12 @@ type MapLibraryListInfo { Align string `json:"align"` VerticalAlign string `json:"verticalAlign"` Material string `json:"material"` - QRcodeType string `json:"QRcodeType"` + QRcodeType int64 `json:"QRcodeType"` Width float64 `json:"width"` Height float64 `json:"height"` X float64 `json:"x"` Y float64 `json:"y"` - Opacity int64 `json:"opacity"` + Opacity float64 `json:"opacity"` OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"` ZIndex int64 `json:"zIndex"` SvgPath string `json:"svgPath"` From a5c3463fa9ed4d6058d832c540215f4f54cfd752 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 17:59:48 +0800 Subject: [PATCH 5/6] fix --- model/gmodel/fsaddressmodel.go | 9 ++- model/gmodel/fsordermodel.go | 3 + .../handler/changeordermethodhandler.go | 67 +++++++++++++++++ .../internal/handler/routes.go | 5 ++ .../internal/logic/changeordermethodlogic.go | 74 +++++++++++++++++++ .../internal/types/types.go | 7 ++ server_api/shopping-cart-confirmation.api | 11 +++ 7 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 server/shopping-cart-confirmation/internal/handler/changeordermethodhandler.go create mode 100644 server/shopping-cart-confirmation/internal/logic/changeordermethodlogic.go diff --git a/model/gmodel/fsaddressmodel.go b/model/gmodel/fsaddressmodel.go index f6b14d0c..08c51241 100755 --- a/model/gmodel/fsaddressmodel.go +++ b/model/gmodel/fsaddressmodel.go @@ -2,6 +2,7 @@ package gmodel import ( "context" + "errors" "gorm.io/gorm" ) @@ -29,7 +30,13 @@ type FsAddressModel struct { func NewFsAddressModel(db *gorm.DB) *FsAddressModel { return &FsAddressModel{db} } - +func (a *FsAddressModel) GetOne(ctx context.Context, id int64, userId int64) (resp FsAddress, err error) { + err = a.db.WithContext(ctx).Model(&FsAddress{}).Where("`id` = ? and `user_id` = ? and `status` = ? ", id, userId, 1).First(&resp).Error + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return FsAddress{}, err + } + return resp, nil +} func (a *FsAddressModel) GetUserAllAddress(ctx context.Context, userId int64) (resp []FsAddress, err error) { err = a.db.WithContext(ctx).Model(&FsAddress{}).Where("`user_id` = ? and `status` = ?", userId, 1).Order("`id` DESC").Find(&resp).Error if err != nil { diff --git a/model/gmodel/fsordermodel.go b/model/gmodel/fsordermodel.go index 43f74cfd..bfd17060 100755 --- a/model/gmodel/fsordermodel.go +++ b/model/gmodel/fsordermodel.go @@ -60,3 +60,6 @@ func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) } return resp, nil } +func (o *FsOrderModel) Update(ctx context.Context, id int64, data FsOrder) error { + return o.db.WithContext(ctx).Model(&FsOrder{}).Where("`id` = ?", id).Updates(data).Error +} diff --git a/server/shopping-cart-confirmation/internal/handler/changeordermethodhandler.go b/server/shopping-cart-confirmation/internal/handler/changeordermethodhandler.go new file mode 100644 index 00000000..0516e923 --- /dev/null +++ b/server/shopping-cart-confirmation/internal/handler/changeordermethodhandler.go @@ -0,0 +1,67 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart-confirmation/internal/logic" + "fusenapi/server/shopping-cart-confirmation/internal/svc" + "fusenapi/server/shopping-cart-confirmation/internal/types" +) + +func ChangeOrderMethodHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // 解析jwtToken + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + // 从Token里获取对应的信息 + userinfo, err := auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + + var req types.ChangeOrderMethodReq + // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + // 创建一个业务逻辑层实例 + l := logic.NewChangeOrderMethodLogic(r.Context(), svcCtx) + resp := l.ChangeOrderMethod(&req, userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + // 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。 + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/shopping-cart-confirmation/internal/handler/routes.go b/server/shopping-cart-confirmation/internal/handler/routes.go index 376133e9..c69baeaf 100644 --- a/server/shopping-cart-confirmation/internal/handler/routes.go +++ b/server/shopping-cart-confirmation/internal/handler/routes.go @@ -37,6 +37,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/cart/order-detail", Handler: CartOrderDetailHandler(serverCtx), }, + { + Method: http.MethodPost, + Path: "/cart/chang-order-method", + Handler: ChangeOrderMethodHandler(serverCtx), + }, }, ) } diff --git a/server/shopping-cart-confirmation/internal/logic/changeordermethodlogic.go b/server/shopping-cart-confirmation/internal/logic/changeordermethodlogic.go new file mode 100644 index 00000000..ddf9301f --- /dev/null +++ b/server/shopping-cart-confirmation/internal/logic/changeordermethodlogic.go @@ -0,0 +1,74 @@ +package logic + +import ( + "encoding/json" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "strings" + + "context" + + "fusenapi/server/shopping-cart-confirmation/internal/svc" + "fusenapi/server/shopping-cart-confirmation/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ChangeOrderMethodLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewChangeOrderMethodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangeOrderMethodLogic { + return &ChangeOrderMethodLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ChangeOrderMethodLogic) ChangeOrderMethod(req *types.ChangeOrderMethodReq, userinfo *auth.UserInfo) (resp *basic.Response) { + req.Sn = strings.Trim(req.Sn, " ") + if req.Sn == "" { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required") + } + //查询订单信息 + orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + } + if orderInfo.Id == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the order is not exists") + } + if *orderInfo.PayedAmount > 0 { + return resp.SetStatusWithMessage(basic.CodeApiErr, "the order`s address cannot be changed for it is paid") + } + updData := gmodel.FsOrder{} + //地址 + if req.AddressId > 0 { + addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) + addr, err := addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info") + } + if addr.Id == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "address is not exists") + } + infoJsonByte, _ := json.Marshal(addr) + strInfoJson := string(infoJsonByte) + updData.AddressInfo = &strInfoJson + } + updData.DeliveryMethod = &req.DeliveryMethod + updData.AddressId = &req.AddressId + updData.PayMethod = &req.PayMethod + if err = orderModel.Update(l.ctx, orderInfo.Id, updData); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to save data") + } + return resp.SetStatusWithMessage(basic.CodeOK, "success") +} diff --git a/server/shopping-cart-confirmation/internal/types/types.go b/server/shopping-cart-confirmation/internal/types/types.go index f7594cc7..84ad80b8 100644 --- a/server/shopping-cart-confirmation/internal/types/types.go +++ b/server/shopping-cart-confirmation/internal/types/types.go @@ -97,6 +97,13 @@ type CartAddr struct { IsDefault int64 `json:"is_default"` } +type ChangeOrderMethodReq struct { + Sn string `json:"sn"` + DeliveryMethod int64 `json:"delivery_method , options=1|2"` + AddressId int64 `json:"address_id"` + PayMethod int64 `json:"pay_method"` +} + type Response struct { Code int `json:"code"` Message string `json:"msg"` diff --git a/server_api/shopping-cart-confirmation.api b/server_api/shopping-cart-confirmation.api index 4aefe8a8..5dafc1d6 100644 --- a/server_api/shopping-cart-confirmation.api +++ b/server_api/shopping-cart-confirmation.api @@ -23,6 +23,9 @@ service shopping-cart-confirmation { //获取用户购物车订单详情 @handler CartOrderDetailHandler get /cart/order-detail (CartOrderDetailReq) returns (response); + //变更发货方式和地址 + @handler ChangeOrderMethodHandler + post /cart/chang-order-method (ChangeOrderMethodReq) returns (response); } //添加入购物车 @@ -109,4 +112,12 @@ type CartAddr { State string `json:"state"` ZipCode string `json:"zip_code"` IsDefault int64 `json:"is_default"` +} + +//变更发货方式和地址 +type ChangeOrderMethodReq { + Sn string `json:"sn"` + DeliveryMethod int64 `json:"delivery_method , options=1|2"` + AddressId int64 `json:"address_id"` + PayMethod int64 `json:"pay_method"` } \ No newline at end of file From f2893cc336f67a4dc76fcc3fce49d7ad31c253fe Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 14 Jun 2023 18:17:24 +0800 Subject: [PATCH 6/6] fix --- server_api/shopping-cart-confirmation.api | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/server_api/shopping-cart-confirmation.api b/server_api/shopping-cart-confirmation.api index 5dafc1d6..2156d17d 100644 --- a/server_api/shopping-cart-confirmation.api +++ b/server_api/shopping-cart-confirmation.api @@ -26,6 +26,9 @@ service shopping-cart-confirmation { //变更发货方式和地址 @handler ChangeOrderMethodHandler post /cart/chang-order-method (ChangeOrderMethodReq) returns (response); + //创建订单 + @handler CartCreateOrderHandler + post /cart/create-order (CartCreateOrderReq) returns (response); } //添加入购物车 @@ -120,4 +123,9 @@ type ChangeOrderMethodReq { DeliveryMethod int64 `json:"delivery_method , options=1|2"` AddressId int64 `json:"address_id"` PayMethod int64 `json:"pay_method"` +} + +//创建订单 +type CartCreateOrderReq{ + } \ No newline at end of file