diff --git a/docs/pb_tbl_cart.md b/docs/pb_tbl_cart.md new file mode 100644 index 0000000..5324b2a --- /dev/null +++ b/docs/pb_tbl_cart.md @@ -0,0 +1,52 @@ +# pb_tbl_cart + +> 来源:购物车表需求草图、`script/pocketbase.cart-order.js` +> 类型:`base` +> 读写规则:微信端原生访问建议仅允许记录所有者访问;当前脚本已按 `cart_owner = 当前 token 对应 openid` 配置原生 collection 规则,管理后台建议通过 hooks / API 聚合查询 + +## 表用途 + +用于存储购物车商品项明细。 + +当前结构按“一个购物车商品项一条记录”设计: + +- `cart_id` 是单条购物车项业务 ID +- `cart_number` 是购物车名称 / 分组号,同一购物车下的多条商品项可共用同一个 `cart_number` +- `cart_owner` 用于标识购物车所属用户 + +## 字段清单 + +| 字段名 | 类型 | 必填 | 说明 | +| :--- | :--- | :---: | :--- | +| `id` | `text` | 是 | PocketBase 记录主键 | +| `cart_id` | `text` | 是 | 购物车项业务 ID,唯一标识 | +| `cart_number` | `text` | 是 | 购物车名称 / 分组号,默认可按“用户名+年月日时分秒”生成 | +| `cart_create` | `autodate` | 否 | 购物车项创建时间,由数据库自动生成 | +| `cart_owner` | `text` | 是 | 生成者 openid,约定保存 `tbl_auth_users.openid` | +| `cart_product_id` | `text` | 是 | 产品 ID,建议保存 `tbl_product_list.prod_list_id` | +| `cart_product_quantity` | `number` | 是 | 产品数量,建议业务侧约束为正整数 | +| `cart_status` | `text` | 是 | 购物车状态,建议值:`有效` / `无效` | +| `cart_at_price` | `number` | 是 | 加入购物车时的价格,用于后续降价提醒或对比 | +| `cart_remark` | `text` | 否 | 备注 | + +## 索引 + +| 索引名 | 类型 | 说明 | +| :--- | :--- | :--- | +| `idx_tbl_cart_cart_id` | `UNIQUE INDEX` | 保证 `cart_id` 唯一 | +| `idx_tbl_cart_cart_number` | `INDEX` | 加速按购物车名称 / 分组号查询 | +| `idx_tbl_cart_cart_owner` | `INDEX` | 加速按所属用户查询 | +| `idx_tbl_cart_cart_product_id` | `INDEX` | 加速按产品查询 | +| `idx_tbl_cart_cart_status` | `INDEX` | 加速按购物车状态过滤 | +| `idx_tbl_cart_cart_create` | `INDEX` | 加速按购物车项创建时间倒序查询 | +| `idx_tbl_cart_owner_number` | `INDEX` | 加速同一用户下按购物车分组查询 | +| `idx_tbl_cart_owner_status` | `INDEX` | 加速查询某用户的有效购物车项 | + +## 补充约定 + +- `cart_owner`、`cart_product_id` 当前按文本字段保存业务 ID,不直接建立 relation,便于兼容现有 hooks 业务模型。 +- `cart_owner` 统一保存 `tbl_auth_users.openid`,便于直接使用微信登录返回 token 做原生访问控制。 +- `cart_product_quantity`、`cart_at_price` 使用 `number`,数量正整数与价格精度建议在 hooks / API 层统一校验。 +- 当购物车被清空时,建议业务侧将历史记录 `cart_status` 置为 `无效`,而不是直接覆盖有效记录。 +- `cart_create` 由数据库自动写入,接口层不需要也不应允许客户端自行填值。 +- PocketBase 系统字段 `created`、`updated` 仍然存在,只是不在 collection 字段清单里单独声明。 diff --git a/docs/pb_tbl_order.md b/docs/pb_tbl_order.md new file mode 100644 index 0000000..66706c8 --- /dev/null +++ b/docs/pb_tbl_order.md @@ -0,0 +1,54 @@ +# pb_tbl_order + +> 来源:订单表需求草图、`script/pocketbase.cart-order.js` +> 类型:`base` +> 读写规则:微信端原生访问建议仅允许记录所有者访问;当前脚本已按 `order_owner = 当前 token 对应 openid` 配置原生 collection 规则,管理后台建议通过 hooks / API 聚合查询 + +## 表用途 + +用于存储订单主记录与订单快照。 + +当前结构按“一个订单一条记录”设计: + +- `order_id` 是订单业务 ID +- `order_number` 是订单编号,建议按“用户名+年月日时分秒”或统一编号规则生成 +- `order_snap` 使用 JSON 完整保存下单时的商品、数量、价格、折扣等快照,避免后续商品数据变化影响历史订单 + +## 字段清单 + +| 字段名 | 类型 | 必填 | 说明 | +| :--- | :--- | :---: | :--- | +| `id` | `text` | 是 | PocketBase 记录主键 | +| `order_id` | `text` | 是 | 订单业务 ID,唯一标识 | +| `order_number` | `text` | 是 | 订单编号,建议业务侧自动生成并保证可追踪 | +| `order_create` | `autodate` | 否 | 订单创建时间,由数据库自动生成 | +| `order_owner` | `text` | 是 | 生成者 openid,约定保存 `tbl_auth_users.openid` | +| `order_source` | `text` | 是 | 订单来源,建议值:`购物车` / `方案清单` | +| `order_status` | `text` | 是 | 订单状态,建议值:`订单已生成` / `订单已确定` / `订单已交付` / `订单已验收` / `订单已结束` | +| `order_source_id` | `text` | 是 | 订单来源关联 ID,如购物车 ID 或方案清单 ID | +| `order_snap` | `json` | 是 | 订单快照,完整保存订单明细信息 | +| `order_amount` | `number` | 是 | 订单总金额 | +| `order_remark` | `text` | 否 | 订单备注 | + +## 索引 + +| 索引名 | 类型 | 说明 | +| :--- | :--- | :--- | +| `idx_tbl_order_order_id` | `UNIQUE INDEX` | 保证 `order_id` 唯一 | +| `idx_tbl_order_order_number` | `UNIQUE INDEX` | 保证 `order_number` 唯一 | +| `idx_tbl_order_order_owner` | `INDEX` | 加速按下单用户查询 | +| `idx_tbl_order_order_source` | `INDEX` | 加速按订单来源过滤 | +| `idx_tbl_order_order_status` | `INDEX` | 加速按订单状态过滤 | +| `idx_tbl_order_order_source_id` | `INDEX` | 加速按来源关联 ID 查询 | +| `idx_tbl_order_order_create` | `INDEX` | 加速按订单创建时间倒序查询 | +| `idx_tbl_order_owner_status` | `INDEX` | 加速查询某用户在不同状态下的订单 | + +## 补充约定 + +- `order_snap` 建议至少包含商品信息、数量、下单时价格、折扣、优惠、实际成交金额等字段。 +- 当订单进入 `订单已确定` 及之后状态时,建议业务侧锁定关键字段,不再允许修改订单核心数据。 +- `order_owner`、`order_source_id` 当前按文本字段保存业务 ID,不直接建立 relation,便于兼容现有 hooks 业务模型。 +- `order_owner` 统一保存 `tbl_auth_users.openid`,便于直接使用微信登录返回 token 做原生访问控制。 +- `order_amount` 使用 `number`,货币精度策略建议后续统一为“分”或固定小数位。 +- `order_create` 由数据库自动写入,接口层不需要也不应允许客户端自行填值。 +- PocketBase 系统字段 `created`、`updated` 仍然存在,只是不在 collection 字段清单里单独声明。 diff --git a/docs/pb_tbl_product_list.md b/docs/pb_tbl_product_list.md index e542694..946d636 100644 --- a/docs/pb_tbl_product_list.md +++ b/docs/pb_tbl_product_list.md @@ -16,10 +16,10 @@ | `prod_list_id` | `text` | 是 | 产品列表业务 ID,唯一标识 | | `prod_list_name` | `text` | 是 | 产品名称 | | `prod_list_modelnumber` | `text` | 否 | 产品型号 | -| `prod_list_icon` | `text` | 否 | 产品图标,保存 `tbl_attachments.attachments_id` | +| `prod_list_icon` | `text` | 否 | 产品图标,保存 `tbl_attachments.attachments_id`,多图时以 `|` 分隔 | | `prod_list_description` | `text` | 否 | 产品说明(editor 内容,建议保存 Markdown 或已净化 HTML) | | `prod_list_feature` | `text` | 否 | 产品特色 | -| `prod_list_parameters` | `json` | 否 | 产品参数(JSON 数组,格式为 `[ { "name": "属性名", "value": "属性值" } ]`) | +| `prod_list_parameters` | `json` | 否 | 产品参数(JSON 数组,格式为 `[ { "sort": 1, "name": "属性名", "value": "属性值" } ]`) | | `prod_list_plantype` | `text` | 否 | 产品方案 | | `prod_list_category` | `text` | 是 | 产品分类(必填,单选) | | `prod_list_sort` | `number` | 否 | 排序值(同分类内按升序) | @@ -47,9 +47,10 @@ ## 补充约定 -- `prod_list_icon` 仅保存附件业务 ID,真实文件统一在 `tbl_attachments`。 +- `prod_list_icon` 仅保存附件业务 ID,真实文件统一在 `tbl_attachments`;多图时按上传顺序使用 `|` 聚合。 - 当前预构建脚本中已将 `listRule` 与 `viewRule` 设置为空字符串(`""`),对应 PocketBase 的“任何人可查看”。 -- `prod_list_parameters` 使用 PocketBase `json` 字段,写入时应直接提交数组结构:`[{"name":"属性名","value":"属性值"}]`。 +- `prod_list_parameters` 使用 PocketBase `json` 字段,写入时应直接提交数组结构:`[{"sort":1,"name":"属性名","value":"属性值"}]`。 +- `prod_list_parameters.sort` 用于稳定参数展示顺序,约定为正整数;前端未填写时可按当前录入/导入顺序自动补齐。 - `prod_list_description` 作为 editor 内容字段,建议统一为 Markdown 或净化后的 HTML;若允许 HTML,需在写入前做 XSS 白名单过滤。 - 前端渲染 `prod_list_description` 时应保持和存储格式一致(Markdown 渲染器或受控 HTML 渲染),避免直接注入未净化内容。 - `prod_list_basic_price` 使用 `number`,如需货币精度策略建议后续统一为“分”或固定小数位。 diff --git a/pocket-base/bai-api-main.pb.js b/pocket-base/bai-api-main.pb.js index b61c1b7..051c734 100644 --- a/pocket-base/bai-api-main.pb.js +++ b/pocket-base/bai-api-main.pb.js @@ -41,6 +41,17 @@ require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/product/detail.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/product/create.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/product/update.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/product/delete.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart/list.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart/detail.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart/create.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart/update.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart/delete.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/order/list.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/order/detail.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/order/create.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/order/update.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/order/delete.js`) +require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/cart-order/manage-users.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/document-history/list.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/sdk-permission/context.js`) require(`${__hooks}/bai_api_pb_hooks/bai_api_routes/sdk-permission/role-save.js`) diff --git a/pocket-base/bai-web-main.pb.js b/pocket-base/bai-web-main.pb.js index 699a94a..ab0fad4 100644 --- a/pocket-base/bai-web-main.pb.js +++ b/pocket-base/bai-web-main.pb.js @@ -4,6 +4,7 @@ require(`${__hooks}/bai_web_pb_hooks/pages/document-manage.js`) require(`${__hooks}/bai_web_pb_hooks/pages/product-manage.js`) require(`${__hooks}/bai_web_pb_hooks/pages/dictionary-manage.js`) require(`${__hooks}/bai_web_pb_hooks/pages/sdk-permission-manage.js`) +require(`${__hooks}/bai_web_pb_hooks/pages/cart-order-manage.js`) require(`${__hooks}/bai_chat_alm_hooks/bai-ai-manage-main.pb.js`) require(`${__hooks}/bai_chat_alm_hooks/bai-chat.pb.js`) require(`${__hooks}/bai_chat_alm_hooks/bai-sql-lab.pb.js`) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart-order/manage-users.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart-order/manage-users.js new file mode 100644 index 0000000..db77bf0 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart-order/manage-users.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/cart-order/manage-users', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + guards.requireManagePlatformUser(e) + const payload = guards.validateCartOrderManageListBody(e) + const data = cartOrderService.listManageUsersCartOrders(payload) + + return success(e, '查询用户购物车与订单成功', { + items: data, + }) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('查询用户购物车与订单失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/create.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/create.js new file mode 100644 index 0000000..39cf94d --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/create.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/cart/create', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateCartMutationBody(e, false) + const data = cartOrderService.createCart(authState, payload) + + return success(e, '创建购物车记录成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('创建购物车记录失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/delete.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/delete.js new file mode 100644 index 0000000..715a352 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/delete.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/cart/delete', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateCartDeleteBody(e) + const data = cartOrderService.deleteCart(authState.openid, payload.cart_id) + + return success(e, '删除购物车记录成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('删除购物车记录失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/detail.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/detail.js new file mode 100644 index 0000000..960d74d --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/detail.js @@ -0,0 +1,23 @@ +routerAdd('POST', '/api/cart/detail', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + const payload = guards.validateCartDetailBody(e) + const data = cartOrderService.getCartDetail(authState.openid, payload.cart_id) + + return success(e, '查询购物车详情成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('查询购物车详情失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/list.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/list.js new file mode 100644 index 0000000..70375d7 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/list.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/cart/list', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + const payload = guards.validateCartListBody(e) + const data = cartOrderService.listCarts(authState.openid, payload) + + return success(e, '查询购物车列表成功', { + items: data, + }) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('查询购物车列表失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/update.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/update.js new file mode 100644 index 0000000..02be668 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/cart/update.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/cart/update', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateCartMutationBody(e, true) + const data = cartOrderService.updateCart(authState.openid, payload) + + return success(e, '更新购物车记录成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('更新购物车记录失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/order/create.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/create.js new file mode 100644 index 0000000..5750c50 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/create.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/order/create', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateOrderMutationBody(e, false) + const data = cartOrderService.createOrder(authState, payload) + + return success(e, '创建订单成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('创建订单失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/order/delete.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/delete.js new file mode 100644 index 0000000..5b0a578 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/delete.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/order/delete', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateOrderDeleteBody(e) + const data = cartOrderService.deleteOrder(authState.openid, payload.order_id) + + return success(e, '删除订单成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('删除订单失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/order/detail.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/detail.js new file mode 100644 index 0000000..d960b4f --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/detail.js @@ -0,0 +1,23 @@ +routerAdd('POST', '/api/order/detail', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + const payload = guards.validateOrderDetailBody(e) + const data = cartOrderService.getOrderDetail(authState.openid, payload.order_id) + + return success(e, '查询订单详情成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('查询订单详情失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/order/list.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/list.js new file mode 100644 index 0000000..d38f984 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/list.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/order/list', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + const payload = guards.validateOrderListBody(e) + const data = cartOrderService.listOrders(authState.openid, payload) + + return success(e, '查询订单列表成功', { + items: data, + }) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('查询订单列表失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_routes/order/update.js b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/update.js new file mode 100644 index 0000000..3959ba4 --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_routes/order/update.js @@ -0,0 +1,25 @@ +routerAdd('POST', '/api/order/update', function (e) { + const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`) + const cartOrderService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js`) + const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) + const { success, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`) + + try { + guards.requireJson(e) + const authState = guards.requireAuthUser(e) + guards.duplicateGuard(e) + + const payload = guards.validateOrderMutationBody(e, true) + const data = cartOrderService.updateOrder(authState.openid, payload) + + return success(e, '更新订单成功', data) + } catch (err) { + const status = (err && err.statusCode) || (err && err.status) || 400 + logger.error('更新订单失败', { + status: status, + errMsg: (err && err.message) || '未知错误', + data: (err && err.data) || {}, + }) + return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status) + } +}) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js b/pocket-base/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js index d9ba824..a82b8a9 100644 --- a/pocket-base/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js +++ b/pocket-base/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js @@ -355,16 +355,31 @@ function normalizeProductParameters(value) { const result = [] const indexByName = {} - function upsert(nameValue, rawValue) { + function normalizeParameterSort(rawSort, fallbackSort) { + if (rawSort === '' || rawSort === null || typeof rawSort === 'undefined') { + return fallbackSort + } + + const num = Number(rawSort) + if (!Number.isFinite(num) || num <= 0 || Math.floor(num) !== num) { + throw createAppError(400, 'prod_list_parameters.sort 必须为正整数') + } + + return num + } + + function upsert(nameValue, rawValue, rawSort, fallbackSort) { const name = String(nameValue || '').trim() if (!name) { return } const normalizedValue = rawValue === null || typeof rawValue === 'undefined' ? '' : String(rawValue) + const normalizedSort = normalizeParameterSort(rawSort, fallbackSort) const existingIndex = indexByName[name] if (typeof existingIndex === 'number') { result[existingIndex].value = normalizedValue + result[existingIndex].sort = normalizedSort return } @@ -372,6 +387,7 @@ function normalizeProductParameters(value) { result.push({ name: name, value: normalizedValue, + sort: normalizedSort, }) } @@ -381,7 +397,7 @@ function normalizeProductParameters(value) { if (!item) { continue } - upsert(item.name || item.key, item.value) + upsert(item.name || item.key, item.value, item.sort, result.length + 1) } return result } @@ -393,7 +409,7 @@ function normalizeProductParameters(value) { const keys = Object.keys(value) for (let i = 0; i < keys.length; i += 1) { - upsert(keys[i], value[keys[i]]) + upsert(keys[i], value[keys[i]], '', result.length + 1) } return result @@ -439,7 +455,7 @@ function validateProductMutationBody(e, isUpdate) { prod_list_id: payload.prod_list_id || '', prod_list_name: payload.prod_list_name || '', prod_list_modelnumber: payload.prod_list_modelnumber || '', - prod_list_icon: payload.prod_list_icon || '', + prod_list_icon: normalizeAttachmentIdList(payload.prod_list_icon, 'prod_list_icon').join('|'), prod_list_description: payload.prod_list_description || '', prod_list_feature: payload.prod_list_feature || '', prod_list_parameters: normalizeProductParameters(payload.prod_list_parameters), @@ -460,6 +476,129 @@ function validateProductDeleteBody(e) { return validateProductDetailBody(e) } +function validateCartListBody(e) { + const payload = parseBody(e) + + return { + keyword: payload.keyword || '', + cart_status: payload.cart_status || '', + cart_number: payload.cart_number || '', + } +} + +function validateCartDetailBody(e) { + const payload = parseBody(e) + if (!payload.cart_id) { + throw createAppError(400, 'cart_id 为必填项') + } + + return { + cart_id: String(payload.cart_id || '').trim(), + } +} + +function validateCartMutationBody(e, isUpdate) { + const payload = parseBody(e) + + if (isUpdate && !payload.cart_id) { + throw createAppError(400, 'cart_id 为必填项') + } + + if (!isUpdate) { + if (!payload.cart_product_id) { + throw createAppError(400, 'cart_product_id 为必填项') + } + if (typeof payload.cart_product_quantity === 'undefined') { + throw createAppError(400, 'cart_product_quantity 为必填项') + } + if (typeof payload.cart_at_price === 'undefined') { + throw createAppError(400, 'cart_at_price 为必填项') + } + } + + return { + cart_id: payload.cart_id || '', + cart_number: Object.prototype.hasOwnProperty.call(payload, 'cart_number') ? payload.cart_number : undefined, + cart_owner: Object.prototype.hasOwnProperty.call(payload, 'cart_owner') ? payload.cart_owner : undefined, + cart_product_id: Object.prototype.hasOwnProperty.call(payload, 'cart_product_id') ? payload.cart_product_id : undefined, + cart_product_quantity: Object.prototype.hasOwnProperty.call(payload, 'cart_product_quantity') ? payload.cart_product_quantity : undefined, + cart_status: Object.prototype.hasOwnProperty.call(payload, 'cart_status') ? payload.cart_status : undefined, + cart_at_price: Object.prototype.hasOwnProperty.call(payload, 'cart_at_price') ? payload.cart_at_price : undefined, + cart_remark: Object.prototype.hasOwnProperty.call(payload, 'cart_remark') ? payload.cart_remark : undefined, + } +} + +function validateCartDeleteBody(e) { + return validateCartDetailBody(e) +} + +function validateOrderListBody(e) { + const payload = parseBody(e) + + return { + keyword: payload.keyword || '', + order_status: payload.order_status || '', + order_source: payload.order_source || '', + } +} + +function validateOrderDetailBody(e) { + const payload = parseBody(e) + if (!payload.order_id) { + throw createAppError(400, 'order_id 为必填项') + } + + return { + order_id: String(payload.order_id || '').trim(), + } +} + +function validateOrderMutationBody(e, isUpdate) { + const payload = parseBody(e) + + if (isUpdate && !payload.order_id) { + throw createAppError(400, 'order_id 为必填项') + } + + if (!isUpdate) { + if (!payload.order_source) { + throw createAppError(400, 'order_source 为必填项') + } + if (!payload.order_source_id) { + throw createAppError(400, 'order_source_id 为必填项') + } + if (typeof payload.order_snap === 'undefined') { + throw createAppError(400, 'order_snap 为必填项') + } + if (typeof payload.order_amount === 'undefined') { + throw createAppError(400, 'order_amount 为必填项') + } + } + + return { + order_id: payload.order_id || '', + order_number: Object.prototype.hasOwnProperty.call(payload, 'order_number') ? payload.order_number : undefined, + order_owner: Object.prototype.hasOwnProperty.call(payload, 'order_owner') ? payload.order_owner : undefined, + order_source: Object.prototype.hasOwnProperty.call(payload, 'order_source') ? payload.order_source : undefined, + order_status: Object.prototype.hasOwnProperty.call(payload, 'order_status') ? payload.order_status : undefined, + order_source_id: Object.prototype.hasOwnProperty.call(payload, 'order_source_id') ? payload.order_source_id : undefined, + order_snap: Object.prototype.hasOwnProperty.call(payload, 'order_snap') ? payload.order_snap : undefined, + order_amount: Object.prototype.hasOwnProperty.call(payload, 'order_amount') ? payload.order_amount : undefined, + order_remark: Object.prototype.hasOwnProperty.call(payload, 'order_remark') ? payload.order_remark : undefined, + } +} + +function validateOrderDeleteBody(e) { + return validateOrderDetailBody(e) +} + +function validateCartOrderManageListBody(e) { + const payload = parseBody(e) + return { + keyword: payload.keyword || '', + } +} + function validateDocumentHistoryListBody(e) { const payload = parseBody(e) @@ -635,6 +774,15 @@ module.exports = { validateProductDetailBody, validateProductMutationBody, validateProductDeleteBody, + validateCartListBody, + validateCartDetailBody, + validateCartMutationBody, + validateCartDeleteBody, + validateOrderListBody, + validateOrderDetailBody, + validateOrderMutationBody, + validateOrderDeleteBody, + validateCartOrderManageListBody, validateDocumentHistoryListBody, validateSdkPermissionContextBody, validateSdkPermissionRoleBody, diff --git a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js new file mode 100644 index 0000000..88c1a6b --- /dev/null +++ b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/cartOrderService.js @@ -0,0 +1,614 @@ +const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`) +const { createAppError } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/appError.js`) + +function buildBusinessId(prefix) { + return prefix + '-' + new Date().getTime() + '-' + $security.randomString(6) +} + +function normalizeText(value) { + return String(value || '').replace(/^\s+|\s+$/g, '') +} + +function formatDateNumberSegment(date) { + const current = date || new Date() + const yyyy = String(current.getFullYear()) + const mm = String(current.getMonth() + 1).padStart(2, '0') + const dd = String(current.getDate()).padStart(2, '0') + const hh = String(current.getHours()).padStart(2, '0') + const mi = String(current.getMinutes()).padStart(2, '0') + const ss = String(current.getSeconds()).padStart(2, '0') + return yyyy + mm + dd + hh + mi + ss +} + +function buildDisplayNumber(prefix, authRecord, openid) { + const baseName = normalizeText(authRecord && typeof authRecord.getString === 'function' ? authRecord.getString('users_name') : '') || normalizeText(openid) || prefix + return baseName + '-' + formatDateNumberSegment(new Date()) +} + +function normalizeNumberValue(value, fieldName) { + if (value === '' || value === null || typeof value === 'undefined') { + throw createAppError(400, fieldName + ' 为必填项') + } + + const num = Number(value) + if (!Number.isFinite(num)) { + throw createAppError(400, fieldName + ' 必须为数字') + } + + return num +} + +function normalizePositiveIntegerValue(value, fieldName) { + const num = normalizeNumberValue(value, fieldName) + if (num <= 0 || Math.floor(num) !== num) { + throw createAppError(400, fieldName + ' 必须为正整数') + } + return num +} + +function normalizeOptionalNumberValue(value, fieldName) { + if (value === '' || value === null || typeof value === 'undefined') { + return undefined + } + + const num = Number(value) + if (!Number.isFinite(num)) { + throw createAppError(400, fieldName + ' 必须为数字') + } + + return num +} + +function normalizeCartStatus(value) { + return normalizeText(value) || '有效' +} + +function normalizeOrderStatus(value) { + return normalizeText(value) || '订单已生成' +} + +function normalizeOrderSource(value) { + return normalizeText(value) +} + +function normalizeJsonField(value, fieldName) { + if (value === null || typeof value === 'undefined' || value === '') { + throw createAppError(400, fieldName + ' 为必填项') + } + + if (Array.isArray(value)) { + try { + return JSON.parse(JSON.stringify(value)) + } catch (_err) { + throw createAppError(400, fieldName + ' 必须可序列化为 JSON') + } + } + + if (typeof value === 'object') { + try { + return JSON.parse(JSON.stringify(value)) + } catch (_err) { + throw createAppError(400, fieldName + ' 必须可序列化为 JSON') + } + } + + if (typeof value === 'string') { + try { + return JSON.parse(value) + } catch (_err) { + throw createAppError(400, fieldName + ' 必须是 JSON 对象、数组或合法 JSON 字符串') + } + } + + throw createAppError(400, fieldName + ' 必须是 JSON 对象、数组或合法 JSON 字符串') +} + +function parseJsonFieldForOutput(value) { + if (value === null || typeof value === 'undefined' || value === '') { + return {} + } + + if (Array.isArray(value)) { + return value + } + + if (typeof value === 'object') { + try { + return JSON.parse(JSON.stringify(value)) + } catch (_err) { + return {} + } + } + + if (typeof value === 'string') { + try { + return JSON.parse(value) + } catch (_err) { + return {} + } + } + + return {} +} + +function findProductRecordByBusinessId(productId) { + const records = $app.findRecordsByFilter('tbl_product_list', 'prod_list_id = {:productId}', '', 1, 0, { + productId: productId, + }) + + return records.length ? records[0] : null +} + +function buildProductInfo(record) { + if (!record) { + return { + prod_list_id: '', + prod_list_name: '', + prod_list_modelnumber: '', + prod_list_basic_price: null, + } + } + + return { + prod_list_id: record.getString('prod_list_id'), + prod_list_name: record.getString('prod_list_name'), + prod_list_modelnumber: record.getString('prod_list_modelnumber'), + prod_list_basic_price: record.get('prod_list_basic_price'), + } +} + +function ensureProductExists(productId) { + const targetId = normalizeText(productId) + if (!targetId) { + throw createAppError(400, 'cart_product_id 为必填项') + } + + const record = findProductRecordByBusinessId(targetId) + if (!record) { + throw createAppError(400, 'cart_product_id 对应产品不存在:' + targetId) + } + + return record +} + +function findCartRecordByBusinessId(cartId) { + const records = $app.findRecordsByFilter('tbl_cart', 'cart_id = {:cartId}', '', 1, 0, { + cartId: cartId, + }) + + return records.length ? records[0] : null +} + +function findOrderRecordByBusinessId(orderId) { + const records = $app.findRecordsByFilter('tbl_order', 'order_id = {:orderId}', '', 1, 0, { + orderId: orderId, + }) + + return records.length ? records[0] : null +} + +function ensureRecordOwner(record, fieldName, authOpenid, resourceLabel) { + const owner = normalizeText(record && typeof record.getString === 'function' ? record.getString(fieldName) : '') + if (!owner || owner !== normalizeText(authOpenid)) { + throw createAppError(403, '无权访问该' + resourceLabel) + } +} + +function exportCartRecord(record, productRecord) { + const productInfo = buildProductInfo(productRecord || findProductRecordByBusinessId(record.getString('cart_product_id'))) + + return { + pb_id: record.id, + cart_id: record.getString('cart_id'), + cart_number: record.getString('cart_number'), + cart_create: String(record.get('cart_create') || ''), + cart_owner: record.getString('cart_owner'), + cart_product_id: record.getString('cart_product_id'), + cart_product_quantity: Number(record.get('cart_product_quantity') || 0), + cart_status: record.getString('cart_status'), + cart_at_price: Number(record.get('cart_at_price') || 0), + cart_remark: record.getString('cart_remark'), + product_name: productInfo.prod_list_name, + product_modelnumber: productInfo.prod_list_modelnumber, + product_basic_price: productInfo.prod_list_basic_price, + created: String(record.created || ''), + updated: String(record.updated || ''), + } +} + +function exportOrderRecord(record) { + return { + pb_id: record.id, + order_id: record.getString('order_id'), + order_number: record.getString('order_number'), + order_create: String(record.get('order_create') || ''), + order_owner: record.getString('order_owner'), + order_source: record.getString('order_source'), + order_status: record.getString('order_status'), + order_source_id: record.getString('order_source_id'), + order_snap: parseJsonFieldForOutput(record.get('order_snap')), + order_amount: Number(record.get('order_amount') || 0), + order_remark: record.getString('order_remark'), + created: String(record.created || ''), + updated: String(record.updated || ''), + } +} + +function listCarts(authOpenid, payload) { + const records = $app.findRecordsByFilter('tbl_cart', 'cart_owner = {:owner}', '-cart_create', 500, 0, { + owner: authOpenid, + }) + const keyword = normalizeText(payload.keyword).toLowerCase() + const cartStatus = normalizeText(payload.cart_status) + const cartNumber = normalizeText(payload.cart_number) + const result = [] + + for (let i = 0; i < records.length; i += 1) { + const item = exportCartRecord(records[i]) + const matchedKeyword = !keyword + || item.cart_id.toLowerCase().indexOf(keyword) !== -1 + || item.cart_number.toLowerCase().indexOf(keyword) !== -1 + || item.cart_product_id.toLowerCase().indexOf(keyword) !== -1 + || normalizeText(item.product_name).toLowerCase().indexOf(keyword) !== -1 + const matchedStatus = !cartStatus || item.cart_status === cartStatus + const matchedNumber = !cartNumber || item.cart_number === cartNumber + + if (matchedKeyword && matchedStatus && matchedNumber) { + result.push(item) + } + } + + return result +} + +function getCartDetail(authOpenid, cartId) { + const record = findCartRecordByBusinessId(normalizeText(cartId)) + if (!record) { + throw createAppError(404, '未找到对应购物车记录') + } + + ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录') + return exportCartRecord(record) +} + +function createCart(authState, payload) { + const productRecord = ensureProductExists(payload.cart_product_id) + const collection = $app.findCollectionByNameOrId('tbl_cart') + const record = new Record(collection) + + record.set('cart_id', buildBusinessId('CART')) + record.set('cart_number', normalizeText(payload.cart_number) || buildDisplayNumber('CART', authState.authRecord, authState.openid)) + record.set('cart_owner', authState.openid) + record.set('cart_product_id', productRecord.getString('prod_list_id')) + record.set('cart_product_quantity', normalizePositiveIntegerValue(payload.cart_product_quantity, 'cart_product_quantity')) + record.set('cart_status', normalizeCartStatus(payload.cart_status)) + record.set('cart_at_price', normalizeNumberValue(payload.cart_at_price, 'cart_at_price')) + record.set('cart_remark', normalizeText(payload.cart_remark)) + + try { + $app.save(record) + } catch (err) { + throw createAppError(400, '创建购物车记录失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('购物车记录创建成功', { + cart_id: record.getString('cart_id'), + cart_owner: authState.openid, + }) + + return exportCartRecord(record, productRecord) +} + +function updateCart(authOpenid, payload) { + const record = findCartRecordByBusinessId(normalizeText(payload.cart_id)) + if (!record) { + throw createAppError(404, '未找到待修改的购物车记录') + } + + ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录') + + let productRecord = null + if (typeof payload.cart_number !== 'undefined') { + record.set('cart_number', normalizeText(payload.cart_number) || record.getString('cart_number')) + } + if (typeof payload.cart_product_id !== 'undefined') { + productRecord = ensureProductExists(payload.cart_product_id) + record.set('cart_product_id', productRecord.getString('prod_list_id')) + } + if (typeof payload.cart_product_quantity !== 'undefined') { + record.set('cart_product_quantity', normalizePositiveIntegerValue(payload.cart_product_quantity, 'cart_product_quantity')) + } + if (typeof payload.cart_status !== 'undefined') { + record.set('cart_status', normalizeCartStatus(payload.cart_status)) + } + if (typeof payload.cart_at_price !== 'undefined') { + record.set('cart_at_price', normalizeNumberValue(payload.cart_at_price, 'cart_at_price')) + } + if (typeof payload.cart_remark !== 'undefined') { + record.set('cart_remark', normalizeText(payload.cart_remark)) + } + + try { + $app.save(record) + } catch (err) { + throw createAppError(400, '更新购物车记录失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('购物车记录更新成功', { + cart_id: record.getString('cart_id'), + cart_owner: authOpenid, + }) + + return exportCartRecord(record, productRecord) +} + +function deleteCart(authOpenid, cartId) { + const record = findCartRecordByBusinessId(normalizeText(cartId)) + if (!record) { + throw createAppError(404, '未找到待删除的购物车记录') + } + + ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录') + + try { + $app.delete(record) + } catch (err) { + throw createAppError(400, '删除购物车记录失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('购物车记录删除成功', { + cart_id: record.getString('cart_id'), + cart_owner: authOpenid, + }) + + return { + cart_id: normalizeText(cartId), + } +} + +function listOrders(authOpenid, payload) { + const records = $app.findRecordsByFilter('tbl_order', 'order_owner = {:owner}', '-order_create', 500, 0, { + owner: authOpenid, + }) + const keyword = normalizeText(payload.keyword).toLowerCase() + const orderStatus = normalizeText(payload.order_status) + const orderSource = normalizeText(payload.order_source) + const result = [] + + for (let i = 0; i < records.length; i += 1) { + const item = exportOrderRecord(records[i]) + const matchedKeyword = !keyword + || item.order_id.toLowerCase().indexOf(keyword) !== -1 + || item.order_number.toLowerCase().indexOf(keyword) !== -1 + || item.order_source_id.toLowerCase().indexOf(keyword) !== -1 + const matchedStatus = !orderStatus || item.order_status === orderStatus + const matchedSource = !orderSource || item.order_source === orderSource + + if (matchedKeyword && matchedStatus && matchedSource) { + result.push(item) + } + } + + return result +} + +function getOrderDetail(authOpenid, orderId) { + const record = findOrderRecordByBusinessId(normalizeText(orderId)) + if (!record) { + throw createAppError(404, '未找到对应订单记录') + } + + ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录') + return exportOrderRecord(record) +} + +function createOrder(authState, payload) { + const collection = $app.findCollectionByNameOrId('tbl_order') + const record = new Record(collection) + + record.set('order_id', buildBusinessId('ORDER')) + record.set('order_number', normalizeText(payload.order_number) || buildDisplayNumber('ORDER', authState.authRecord, authState.openid)) + record.set('order_owner', authState.openid) + record.set('order_source', normalizeOrderSource(payload.order_source)) + record.set('order_status', normalizeOrderStatus(payload.order_status)) + record.set('order_source_id', normalizeText(payload.order_source_id)) + record.set('order_snap', normalizeJsonField(payload.order_snap, 'order_snap')) + record.set('order_amount', normalizeNumberValue(payload.order_amount, 'order_amount')) + record.set('order_remark', normalizeText(payload.order_remark)) + + try { + $app.save(record) + } catch (err) { + throw createAppError(400, '创建订单失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('订单创建成功', { + order_id: record.getString('order_id'), + order_owner: authState.openid, + }) + + return exportOrderRecord(record) +} + +function updateOrder(authOpenid, payload) { + const record = findOrderRecordByBusinessId(normalizeText(payload.order_id)) + if (!record) { + throw createAppError(404, '未找到待修改的订单') + } + + ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录') + + if (typeof payload.order_number !== 'undefined') { + record.set('order_number', normalizeText(payload.order_number) || record.getString('order_number')) + } + if (typeof payload.order_source !== 'undefined') { + const nextSource = normalizeOrderSource(payload.order_source) + if (!nextSource) { + throw createAppError(400, 'order_source 为必填项') + } + record.set('order_source', nextSource) + } + if (typeof payload.order_status !== 'undefined') { + record.set('order_status', normalizeOrderStatus(payload.order_status)) + } + if (typeof payload.order_source_id !== 'undefined') { + const nextSourceId = normalizeText(payload.order_source_id) + if (!nextSourceId) { + throw createAppError(400, 'order_source_id 为必填项') + } + record.set('order_source_id', nextSourceId) + } + if (typeof payload.order_snap !== 'undefined') { + record.set('order_snap', normalizeJsonField(payload.order_snap, 'order_snap')) + } + if (typeof payload.order_amount !== 'undefined') { + record.set('order_amount', normalizeNumberValue(payload.order_amount, 'order_amount')) + } + if (typeof payload.order_remark !== 'undefined') { + record.set('order_remark', normalizeText(payload.order_remark)) + } + + try { + $app.save(record) + } catch (err) { + throw createAppError(400, '更新订单失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('订单更新成功', { + order_id: record.getString('order_id'), + order_owner: authOpenid, + }) + + return exportOrderRecord(record) +} + +function deleteOrder(authOpenid, orderId) { + const record = findOrderRecordByBusinessId(normalizeText(orderId)) + if (!record) { + throw createAppError(404, '未找到待删除的订单') + } + + ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录') + + try { + $app.delete(record) + } catch (err) { + throw createAppError(400, '删除订单失败', { + originalMessage: (err && err.message) || '未知错误', + originalData: (err && err.data) || {}, + }) + } + + logger.info('订单删除成功', { + order_id: record.getString('order_id'), + order_owner: authOpenid, + }) + + return { + order_id: normalizeText(orderId), + } +} + +function exportManageUser(userRecord, groupedCarts, groupedOrders) { + const openid = userRecord.getString('openid') + const carts = groupedCarts[openid] || [] + const orders = groupedOrders[openid] || [] + let cartTotalQuantity = 0 + let orderTotalAmount = 0 + + for (let i = 0; i < carts.length; i += 1) { + cartTotalQuantity += Number(carts[i].cart_product_quantity || 0) + } + for (let i = 0; i < orders.length; i += 1) { + orderTotalAmount += Number(orders[i].order_amount || 0) + } + + return { + pb_id: userRecord.id, + openid: openid, + users_id: userRecord.getString('users_id'), + users_name: userRecord.getString('users_name'), + users_phone: userRecord.getString('users_phone'), + users_type: userRecord.getString('users_type'), + users_idtype: userRecord.getString('users_idtype'), + company_id: userRecord.getString('company_id'), + cart_count: carts.length, + cart_total_quantity: cartTotalQuantity, + order_count: orders.length, + order_total_amount: orderTotalAmount, + carts: carts, + orders: orders, + created: String(userRecord.created || ''), + updated: String(userRecord.updated || ''), + } +} + +function listManageUsersCartOrders(payload) { + const keyword = normalizeText(payload.keyword).toLowerCase() + const userRecords = $app.findRecordsByFilter('tbl_auth_users', '', '-created', 500, 0) + const cartRecords = $app.findRecordsByFilter('tbl_cart', '', '-cart_create', 1000, 0) + const orderRecords = $app.findRecordsByFilter('tbl_order', '', '-order_create', 1000, 0) + const groupedCarts = {} + const groupedOrders = {} + + for (let i = 0; i < cartRecords.length; i += 1) { + const owner = cartRecords[i].getString('cart_owner') + if (!groupedCarts[owner]) { + groupedCarts[owner] = [] + } + groupedCarts[owner].push(exportCartRecord(cartRecords[i])) + } + + for (let i = 0; i < orderRecords.length; i += 1) { + const owner = orderRecords[i].getString('order_owner') + if (!groupedOrders[owner]) { + groupedOrders[owner] = [] + } + groupedOrders[owner].push(exportOrderRecord(orderRecords[i])) + } + + const result = [] + for (let i = 0; i < userRecords.length; i += 1) { + const item = exportManageUser(userRecords[i], groupedCarts, groupedOrders) + const matchedKeyword = !keyword + || normalizeText(item.openid).toLowerCase().indexOf(keyword) !== -1 + || normalizeText(item.users_id).toLowerCase().indexOf(keyword) !== -1 + || normalizeText(item.users_name).toLowerCase().indexOf(keyword) !== -1 + || normalizeText(item.users_phone).toLowerCase().indexOf(keyword) !== -1 + + if (matchedKeyword) { + result.push(item) + } + } + + return result +} + +module.exports = { + listCarts, + getCartDetail, + createCart, + updateCart, + deleteCart, + listOrders, + getOrderDetail, + createOrder, + updateOrder, + deleteOrder, + listManageUsersCartOrders, +} diff --git a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/dictionaryService.js b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/dictionaryService.js index 747689c..ff29b36 100644 --- a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/dictionaryService.js +++ b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/dictionaryService.js @@ -192,9 +192,9 @@ function updateDictionary(payload) { throw createAppError(404, '未找到待修改的字典') } - ensureDictionaryNameUnique(payload.dict_name, record.id) + const immutableName = record.getString('dict_name') - record.set('dict_name', payload.dict_name) + record.set('dict_name', immutableName) record.set('dict_word_is_enabled', payload.dict_word_is_enabled) record.set('dict_word_parent_id', payload.dict_word_parent_id) record.set('dict_word_remark', payload.dict_word_remark) @@ -210,7 +210,7 @@ function updateDictionary(payload) { } logger.info('字典修改成功', { - dict_name: payload.dict_name, + dict_name: immutableName, original_dict_name: payload.original_dict_name, }) diff --git a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/documentService.js b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/documentService.js index 4202646..0df1726 100644 --- a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/documentService.js +++ b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/documentService.js @@ -436,6 +436,7 @@ function deleteAttachment(attachmentId) { function listDocuments(payload) { const allRecords = $app.findRecordsByFilter('tbl_document', '', '', 500, 0) const keyword = String(payload.keyword || '').toLowerCase() + const titleKeyword = String(payload.title_keyword || '').toLowerCase().trim() const status = String(payload.status || '') const type = String(payload.document_type || '') const result = [] @@ -448,10 +449,23 @@ function listDocuments(payload) { || item.document_subtitle.toLowerCase().indexOf(keyword) !== -1 || item.document_summary.toLowerCase().indexOf(keyword) !== -1 || item.document_keywords.toLowerCase().indexOf(keyword) !== -1 + const matchedTitleKeyword = !titleKeyword + || item.document_title.toLowerCase().indexOf(titleKeyword) !== -1 const matchedStatus = !status || item.document_status === status - const matchedType = !type || item.document_type === type + const matchedType = !type || String(item.document_type || '') + .split('|') + .map(function (token) { return String(token || '').trim() }) + .some(function (token) { + if (!token) { + return false + } + if (token === type) { + return true + } + return token.indexOf(type + '@') === 0 + }) - if (matchedKeyword && matchedStatus && matchedType) { + if (matchedKeyword && matchedTitleKeyword && matchedStatus && matchedType) { result.push(item) } } diff --git a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/productService.js b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/productService.js index 1544735..f5b71d7 100644 --- a/pocket-base/bai_api_pb_hooks/bai_api_shared/services/productService.js +++ b/pocket-base/bai_api_pb_hooks/bai_api_shared/services/productService.js @@ -37,6 +37,16 @@ function normalizeSortValue(value) { } function normalizePipeValues(value) { + if (Array.isArray(value)) { + return value + .map(function (item) { + return normalizeText(item) + }) + .filter(function (item) { + return !!item + }) + } + return String(value || '') .split('|') .map(function (item) { @@ -70,6 +80,52 @@ function normalizeRequiredCategory(value) { return values[0] } +function normalizePositiveSort(rawSort, fieldName, fallbackSort) { + if (rawSort === '' || rawSort === null || typeof rawSort === 'undefined') { + return fallbackSort + } + + const num = Number(rawSort) + if (!Number.isFinite(num) || num <= 0 || Math.floor(num) !== num) { + throw createAppError(400, fieldName + ' 必须为正整数') + } + + return num +} + +function normalizePositiveSortForOutput(rawSort, fallbackSort) { + if (rawSort === '' || rawSort === null || typeof rawSort === 'undefined') { + return fallbackSort + } + + const num = Number(rawSort) + if (!Number.isFinite(num) || num <= 0 || Math.floor(num) !== num) { + return fallbackSort + } + + return num +} + +function sortParameterRows(rows) { + return rows + .slice() + .sort(function (a, b) { + const sortDiff = Number(a.sort || 0) - Number(b.sort || 0) + if (sortDiff !== 0) { + return sortDiff + } + + return Number(a.__inputIndex || 0) - Number(b.__inputIndex || 0) + }) + .map(function (item) { + return { + name: item.name, + value: item.value, + sort: Number(item.sort || 0), + } + }) +} + function buildCategoryRankMap(records) { const grouped = {} for (let i = 0; i < records.length; i += 1) { @@ -118,16 +174,18 @@ function normalizeParameters(value) { const result = [] const indexByName = {} - function upsert(nameValue, rawValue) { + function upsert(nameValue, rawValue, rawSort, fallbackSort, inputIndex) { const name = normalizeText(nameValue) if (!name) { return } const normalizedValue = rawValue === null || typeof rawValue === 'undefined' ? '' : String(rawValue) + const normalizedSort = normalizePositiveSort(rawSort, 'prod_list_parameters.sort', fallbackSort) const existingIndex = indexByName[name] if (typeof existingIndex === 'number') { result[existingIndex].value = normalizedValue + result[existingIndex].sort = normalizedSort return } @@ -135,6 +193,8 @@ function normalizeParameters(value) { result.push({ name: name, value: normalizedValue, + sort: normalizedSort, + __inputIndex: inputIndex, }) } @@ -144,9 +204,9 @@ function normalizeParameters(value) { if (!item) { continue } - upsert(item.name || item.key, item.value) + upsert(item.name || item.key, item.value, item.sort, i + 1, i + 1) } - return result + return sortParameterRows(result) } if (typeof value !== 'object') { @@ -155,10 +215,10 @@ function normalizeParameters(value) { const keys = Object.keys(value) for (let i = 0; i < keys.length; i += 1) { - upsert(keys[i], value[keys[i]]) + upsert(keys[i], value[keys[i]], '', i + 1, i + 1) } - return result + return sortParameterRows(result) } function normalizeParametersForOutput(value) { @@ -166,6 +226,30 @@ function normalizeParametersForOutput(value) { return [] } + function pushOrUpdate(targetRows, indexByName, nameValue, rawValue, rawSort, fallbackSort, inputIndex) { + const name = normalizeText(nameValue) + if (!name) { + return + } + + const normalizedValue = rawValue === null || typeof rawValue === 'undefined' ? '' : String(rawValue) + const normalizedSort = normalizePositiveSortForOutput(rawSort, fallbackSort) + const existingIndex = indexByName[name] + if (typeof existingIndex === 'number') { + targetRows[existingIndex].value = normalizedValue + targetRows[existingIndex].sort = normalizedSort + return + } + + indexByName[name] = targetRows.length + targetRows.push({ + name: name, + value: normalizedValue, + sort: normalizedSort, + __inputIndex: inputIndex, + }) + } + let source = value if (typeof source === 'string') { try { @@ -191,16 +275,9 @@ function normalizeParametersForOutput(value) { continue } const val = pair.slice(separatorIndex + 1) - const normalizedValue = val === null || typeof val === 'undefined' ? '' : String(val) - const existingIndex = indexByName[key] - if (typeof existingIndex === 'number') { - result[existingIndex].value = normalizedValue - } else { - indexByName[key] = result.length - result.push({ name: key, value: normalizedValue }) - } + pushOrUpdate(result, indexByName, key, val, '', i + 1, i + 1) } - return result + return sortParameterRows(result) } return [] } @@ -214,20 +291,9 @@ function normalizeParametersForOutput(value) { if (!item) { continue } - const name = normalizeText(item.name || item.key) - if (!name) { - continue - } - const normalizedValue = item.value === null || typeof item.value === 'undefined' ? '' : String(item.value) - const existingIndex = indexByName[name] - if (typeof existingIndex === 'number') { - mapped[existingIndex].value = normalizedValue - } else { - indexByName[name] = mapped.length - mapped.push({ name: name, value: normalizedValue }) - } + pushOrUpdate(mapped, indexByName, item.name || item.key, item.value, item.sort, i + 1, i + 1) } - return mapped + return sortParameterRows(mapped) } if (typeof source !== 'object') { @@ -243,18 +309,19 @@ function normalizeParametersForOutput(value) { const indexByName = {} const keys = Object.keys(source) for (let i = 0; i < keys.length; i += 1) { - const name = normalizeText(keys[i]) - if (!name) { - continue - } - const current = source[keys[i]] - const normalizedValue = current === null || typeof current === 'undefined' ? '' : String(current) - const existingIndex = indexByName[name] - if (typeof existingIndex === 'number') { - result[existingIndex].value = normalizedValue - } else { - indexByName[name] = result.length - result.push({ name: name, value: normalizedValue }) + pushOrUpdate(result, indexByName, keys[i], source[keys[i]], '', i + 1, i + 1) + } + + return sortParameterRows(result) +} + +function normalizeAttachmentIdList(value) { + const result = [] + const items = normalizePipeValues(value) + + for (let i = 0; i < items.length; i += 1) { + if (result.indexOf(items[i]) === -1) { + result.push(items[i]) } } @@ -262,15 +329,17 @@ function normalizeParametersForOutput(value) { } function ensureAttachmentExists(attachmentId, fieldName) { - const value = normalizeText(attachmentId) - if (!value) { + const values = normalizeAttachmentIdList(attachmentId) + if (!values.length) { return } - try { - documentService.getAttachmentDetail(value) - } catch (_err) { - throw createAppError(400, fieldName + ' 对应附件不存在:' + value) + for (let i = 0; i < values.length; i += 1) { + try { + documentService.getAttachmentDetail(values[i]) + } catch (_err) { + throw createAppError(400, fieldName + ' 对应附件不存在:' + values[i]) + } } } @@ -283,16 +352,20 @@ function findProductRecordByBusinessId(productId) { } function exportProductRecord(record, extra) { - const iconId = record.getString('prod_list_icon') - let iconAttachment = null + const iconIds = normalizeAttachmentIdList(record.getString('prod_list_icon')) + const iconAttachments = [] + const iconUrls = [] - if (iconId) { + for (let i = 0; i < iconIds.length; i += 1) { try { - iconAttachment = documentService.getAttachmentDetail(iconId) + const attachment = documentService.getAttachmentDetail(iconIds[i]) + iconAttachments.push(attachment) + iconUrls.push(attachment.attachments_url || '') } catch (_error) { - iconAttachment = null + continue } } + const firstIconAttachment = iconAttachments.length ? iconAttachments[0] : null const parametersText = normalizeText(record.getString('prod_list_parameters')) const parametersFromText = parametersText ? normalizeParametersForOutput(parametersText) : {} @@ -305,9 +378,12 @@ function exportProductRecord(record, extra) { prod_list_id: record.getString('prod_list_id'), prod_list_name: record.getString('prod_list_name'), prod_list_modelnumber: record.getString('prod_list_modelnumber'), - prod_list_icon: iconId, - prod_list_icon_attachment: iconAttachment, - prod_list_icon_url: iconAttachment ? iconAttachment.attachments_url : '', + prod_list_icon: iconIds.join('|'), + prod_list_icon_ids: iconIds, + prod_list_icon_attachments: iconAttachments, + prod_list_icon_urls: iconUrls, + prod_list_icon_attachment: firstIconAttachment, + prod_list_icon_url: firstIconAttachment ? firstIconAttachment.attachments_url : '', prod_list_description: record.getString('prod_list_description'), prod_list_feature: record.getString('prod_list_feature'), prod_list_parameters: parameters, @@ -399,7 +475,7 @@ function createProduct(_userOpenid, payload) { record.set('prod_list_id', targetProductId) record.set('prod_list_name', normalizeText(payload.prod_list_name)) record.set('prod_list_modelnumber', normalizeText(payload.prod_list_modelnumber)) - record.set('prod_list_icon', normalizeText(payload.prod_list_icon)) + record.set('prod_list_icon', joinUniquePipeValues(payload.prod_list_icon)) record.set('prod_list_description', normalizeText(payload.prod_list_description)) record.set('prod_list_feature', normalizeText(payload.prod_list_feature)) record.set('prod_list_parameters', normalizeParameters(payload.prod_list_parameters)) @@ -448,7 +524,7 @@ function updateProduct(_userOpenid, payload) { record.set('prod_list_name', normalizeText(payload.prod_list_name)) record.set('prod_list_modelnumber', normalizeText(payload.prod_list_modelnumber)) - record.set('prod_list_icon', normalizeText(payload.prod_list_icon)) + record.set('prod_list_icon', joinUniquePipeValues(payload.prod_list_icon)) record.set('prod_list_description', normalizeText(payload.prod_list_description)) record.set('prod_list_feature', normalizeText(payload.prod_list_feature)) record.set('prod_list_parameters', normalizeParameters(payload.prod_list_parameters)) diff --git a/pocket-base/bai_web_pb_hooks/pages/cart-order-manage.js b/pocket-base/bai_web_pb_hooks/pages/cart-order-manage.js new file mode 100644 index 0000000..ad1e7ab --- /dev/null +++ b/pocket-base/bai_web_pb_hooks/pages/cart-order-manage.js @@ -0,0 +1,312 @@ +routerAdd('GET', '/manage/cart-order-manage', function (e) { + const html = ` + +
+ + +| 属性名 | 属性值 | -操作 | +操作 / 排序 |
|---|---|---|---|
| ' + ' | ' - + ' | ' + + ' | '
+ + ''
+ + ''
+ + ' | '
+ '