Commit 4cb354d4225751a7e513e86d480444cefc8ca503

Authored by 杨鑫
1 parent df63f7c6

提交

Showing 43 changed files with 2465 additions and 1256 deletions
6-18代码优化.md 0 → 100644
  1 +# 6-18 代码优化
  2 +
  3 +本文档说明 **2026-06-18** 对 **`GET /api/app/label-template`** 列表接口的第二轮修复。
  4 +
  5 +6-17 已完成 scope 库结构兼容(未迁移 `fl_label_template_partner` / `fl_label_template_region` 时仍可查询),但测试环境 Web **Label Templates** 页仍返回 **500**,Network 中:
  6 +
  7 +`GET /api/app/label-template?SkipCount=1&MaxResultCount=10`
  8 +
  9 +测试环境:`http://flus-test.3ffoodsafety.com`
  10 +
  11 +---
  12 +
  13 +## 一、现象
  14 +
  15 +- 页面提示:**Failed to load label templates. Request failed.**
  16 +- 接口 HTTP **500**,响应体 `errors` 为空,无具体异常文案。
  17 +- 同页 `partner` / `group` / `location` 下拉接口可正常加载。
  18 +
  19 +> `SkipCount=1` 表示**第 1 页**(页码从 1 起),不是报错原因。详见 `Helpers/PagedQueryConvention.cs`。
  20 +
  21 +---
  22 +
  23 +## 二、根因
  24 +
  25 +服务端日志已明确报错:
  26 +
  27 +```text
  28 +Unknown column 'AppliedPartnerType' in 'field list'
  29 +```
  30 +
  31 +对应 SQL:
  32 +
  33 +```sql
  34 +SELECT ... `AppliedLocationType`,`AppliedPartnerType`,`AppliedRegionType`, ...
  35 +FROM `fl_label_template`
  36 +WHERE NOT ( `IsDeleted`=1 )
  37 +ORDER BY IFNULL(`LastModificationTime`,`CreationTime`) DESC
  38 +LIMIT 0,10
  39 +```
  40 +
  41 +### 2.1 主因:ORM 实体仍映射不存在列
  42 +
  43 +6-17 曾在 `FlLabelTemplateDbEntity` 上对 `AppliedPartnerType` / `AppliedRegionType` 标记 `[SugarColumn(IsIgnore = true)]`,但当前 SqlSugar 运行时**仍会**把这两列拼进 `SELECT`(与 `fl_label.AppliedRegionType` 的 `IsIgnore` 行为不一致),导致未执行 `fl_label_template_scope.sql` 的库直接 500。
  44 +
  45 +**MCP 查库(测试库)**:
  46 +
  47 +- `fl_label_template` **无** `AppliedPartnerType` / `AppliedRegionType` 列
  48 +- **无** `fl_label_template_partner` / `fl_label_template_region` 表
  49 +- **有** `AppliedLocationType` 与 `fl_label_template_location`
  50 +
  51 +### 2.2 次因:列表 SQL 其它隐患(一并修复)
  52 +
  53 +| # | 问题 | 后果 |
  54 +|---|------|------|
  55 +| 1 | 默认排序曾用 `LastModificationTime ?? CreationTime` | SqlSugar 翻译失败 → 500 |
  56 +| 2 | `Sorting` 直接 `OrderBy(input.Sorting)` 拼 SQL | 非法字段 / 注入风险 |
  57 +| 3 | 空 `templateIds` 仍 `Contains` 查询 | 可能生成 `IN ()` |
  58 +| 4 | 无效 partner/group 筛选未安全降级 | 未捕获异常 |
  59 +
  60 +---
  61 +
  62 +## 三、修复说明
  63 +
  64 +### 1. 从 ORM 实体移除不存在列 + 强制列投影(核心)
  65 +
  66 +| 改动 | 说明 |
  67 +|------|------|
  68 +| `FlLabelTemplateDbEntity` | **删除** `AppliedPartnerType` / `AppliedRegionType` 属性 |
  69 +| **`LabelTemplateQueryHelper.ProjectListColumns`** | 列表/详情/重复校验等只读查询 **显式 Select** 真实列,SQL 不再出现 scope 列 |
  70 +| `LabelTemplateScopeSchemaHelper` | 探测列/表;已迁移时用 raw SQL 写入 scope 列 |
  71 +| `LabelTemplateAppService` | `GetListAsync` 在排序后调用 `ProjectListColumns` |
  72 +
  73 +> **重要**:若 Yi-SQL 日志仍出现 `AppliedPartnerType`,说明进程加载的是**旧 DLL**(`FoodLabeling.Application` 未重新编译或未重启)。请先 `dotnet build` 通过后再**完全停止并重启** `Yi.Abp.Web`。
  74 +
  75 +### 2. 安全排序
  76 +
  77 +新增 `ApplyLabelTemplateListSorting`:
  78 +
  79 +- 默认:`ORDER BY IFNULL(LastModificationTime, CreationTime) DESC, TemplateCode ASC`
  80 +- `Sorting` 白名单字段 + asc/desc
  81 +
  82 +### 3. 列表查询健壮性
  83 +
  84 +| 改动 | 说明 |
  85 +|------|------|
  86 +| `input ??= new()`、`pageSize` 默认 10 | 入参/分页兜底 |
  87 +| `templateIds.Count > 0` 再查 elements/items | 避免空 `IN ()` |
  88 +| `ResolveFilteredLocationIdsForListAsync` | 无效 partner/group 返回空列表 |
  89 +| `DeleteAsync` | 仅当 scope 关联表存在时才删除 partner/region 行 |
  90 +
  91 +### 4. 与 6-17 的关系
  92 +
  93 +6-17 用 `IsIgnore` 试图跳过列映射,**实测无效**;6-18 改为**实体不含列 + raw SQL 按需写入**,与 `fl_label.AppliedRegionType` 处理方式一致。
  94 +
  95 +---
  96 +
  97 +## 四、接口说明
  98 +
  99 +| 项目 | 内容 |
  100 +|------|------|
  101 +| 方法 | `GET` |
  102 +| 路径 | `/api/app/label-template` |
  103 +| 鉴权 | Bearer Token(`Authorization: {data.token}`,`data.token` 已含 `Bearer ` 前缀) |
  104 +
  105 +### 入参(Query)
  106 +
  107 +| 参数 | 类型 | 必填 | 说明 |
  108 +|------|------|------|------|
  109 +| `SkipCount` | int | 否 | **页码,从 1 起**;第一页传 `1` |
  110 +| `MaxResultCount` | int | 否 | 每页条数;`<=0` 时后端按 **10** 处理 |
  111 +| `Keyword` | string | 否 | 模板名称 / 编码模糊搜索 |
  112 +| `PartnerId` | string | 否 | 按 Company(`fl_partner.Id`)筛选 |
  113 +| `GroupId` | string | 否 | 按 Region(`fl_group.Id`)筛选 |
  114 +| `LocationId` | string | 否 | 按门店(`location.Id`)筛选;**优先于** Partner/Region |
  115 +| `LabelType` | string | 否 | 如 `PRICE` / `NUTRITION` |
  116 +| `State` | bool | 否 | 启用状态 |
  117 +| `Sorting` | string | 否 | 白名单:`TemplateName asc/desc`、`TemplateCode asc/desc`、`CreationTime asc/desc`、`LastModificationTime asc/desc`;其它值忽略并走默认排序 |
  118 +
  119 +筛选解析顺序:**LocationId → GroupId → PartnerId**;均未传则不按门店范围收窄(仍返回全部未删除模板,除非前端传了无效 Id 则返回空列表)。
  120 +
  121 +### 出参(`PagedResultWithPageDto<LabelTemplateGetListOutputDto>`)
  122 +
  123 +| 字段 | 说明 |
  124 +|------|------|
  125 +| `pageIndex` | 当前页码 |
  126 +| `pageSize` | 每页条数 |
  127 +| `totalCount` | 总条数 |
  128 +| `totalPages` | 总页数 |
  129 +| `items[]` | 模板列表 |
  130 +
  131 +**`items[]` 主要字段**
  132 +
  133 +| 字段 | 说明 |
  134 +|------|------|
  135 +| `id` / `templateCode` | 模板编码(前端主键) |
  136 +| `templateName` | 模板名称 |
  137 +| `company` / `region` / `location` | 适用范围展示;未迁移 scope 库时 Company/Region 为 `All Companies` / `All Regions` |
  138 +| `partnerIds` / `regionIds` / `locationIds` | 对应 Id 数组 |
  139 +| `items` / `itemNames` | 模板内控件名称 |
  140 +| `contentsCount` | 控件数量 |
  141 +| `sizeText` | 如 `2x2inch` |
  142 +| `lastEdited` | 最近编辑时间(`LastModificationTime ?? CreationTime`) |
  143 +
  144 +---
  145 +
  146 +## 五、请求示例
  147 +
  148 +### 登录获取 Token
  149 +
  150 +```bash
  151 +curl -X POST "http://flus-test.3ffoodsafety.com/api/oauth/Login" \
  152 + -H "Content-Type: application/x-www-form-urlencoded" \
  153 + -d "userName=admin&password=123456"
  154 +```
  155 +
  156 +### 列表(第一页,默认排序)
  157 +
  158 +```bash
  159 +curl -G "http://flus-test.3ffoodsafety.com/api/app/label-template" \
  160 + -H "Authorization: Bearer {token}" \
  161 + --data-urlencode "SkipCount=1" \
  162 + --data-urlencode "MaxResultCount=10"
  163 +```
  164 +
  165 +### 带 Company 筛选
  166 +
  167 +```bash
  168 +curl -G "http://flus-test.3ffoodsafety.com/api/app/label-template" \
  169 + -H "Authorization: Bearer {token}" \
  170 + --data-urlencode "SkipCount=1" \
  171 + --data-urlencode "MaxResultCount=10" \
  172 + --data-urlencode "PartnerId={fl_partner.Id}"
  173 +```
  174 +
  175 +### 指定排序
  176 +
  177 +```bash
  178 +curl -G "http://flus-test.3ffoodsafety.com/api/app/label-template" \
  179 + -H "Authorization: Bearer {token}" \
  180 + --data-urlencode "SkipCount=1" \
  181 + --data-urlencode "MaxResultCount=10" \
  182 + --data-urlencode "Sorting=TemplateName asc"
  183 +```
  184 +
  185 +### 响应片段(示例)
  186 +
  187 +```json
  188 +{
  189 + "pageIndex": 1,
  190 + "pageSize": 10,
  191 + "totalCount": 3,
  192 + "totalPages": 1,
  193 + "items": [
  194 + {
  195 + "id": "tpl_n0b5h9_mpyssitm",
  196 + "templateCode": "tpl_n0b5h9_mpyssitm",
  197 + "templateName": "Retail Label w/Price Copy",
  198 + "company": "All Companies",
  199 + "region": "All Regions",
  200 + "location": "Ordos Airport, Store B",
  201 + "items": "Label Name, Price, Barcode",
  202 + "contentsCount": 5,
  203 + "sizeText": "2x2inch",
  204 + "lastEdited": "2026-06-04T08:30:00"
  205 + }
  206 + ]
  207 +}
  208 +```
  209 +
  210 +---
  211 +
  212 +## 六、验证步骤
  213 +
  214 +0. **重新编译并重启**(必做):
  215 + ```bash
  216 + cd "美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web"
  217 + dotnet build
  218 + ```
  219 + 停止正在运行的 Web 进程后重新启动;确认 Yi-SQL 中 **不再出现** `AppliedPartnerType`。
  220 +
  221 +1. **部署**包含 6-17 + 6-18 的后端并重启。
  222 +2. 调用 `GET /api/app/label-template?SkipCount=1&MaxResultCount=10` → 应 **200**,`totalCount >= 0`。
  223 +3. Web **Label Templates** 列表可加载,不再出现红色 **Failed to load label templates**。
  224 +4. 传无效 `PartnerId` / `GroupId` → **200** 且 `items=[]`(非 500)。
  225 +5. 不传 `Sorting` → 按最近编辑时间降序;传 `Sorting=TemplateName asc` → 按名称升序。
  226 +6. 分页:第 2 页 `SkipCount=2`,`totalCount` 与 UI 一致。
  227 +
  228 +### SQL 抽查(修复后 ORM 应生成的列)
  229 +
  230 +```sql
  231 +SELECT Id, TemplateCode, TemplateName, AppliedLocationType,
  232 + IFNULL(LastModificationTime, CreationTime) AS LastEdited
  233 +FROM fl_label_template
  234 +WHERE IsDeleted = 0
  235 +ORDER BY IFNULL(LastModificationTime, CreationTime) DESC, TemplateCode ASC
  236 +LIMIT 10;
  237 +```
  238 +
  239 +**不应再出现** `AppliedPartnerType` / `AppliedRegionType`。
  240 +
  241 +### 检查 scope 是否已迁移
  242 +
  243 +```sql
  244 +SELECT COUNT(*) AS scope_table_cnt
  245 +FROM information_schema.TABLES
  246 +WHERE TABLE_SCHEMA = DATABASE()
  247 + AND TABLE_NAME IN ('fl_label_template_partner', 'fl_label_template_region');
  248 +```
  249 +
  250 +`scope_table_cnt = 0` 时行为与 6-17 一致:仅 Location 维度落库与展示。
  251 +
  252 +---
  253 +
  254 +## 七、涉及代码
  255 +
  256 +| 文件 | 说明 |
  257 +|------|------|
  258 +| `Helpers/LabelTemplateQueryHelper.cs` | **新增** `ProjectListColumns` 强制 SQL 列白名单 |
  259 +| `Services/DbModels/FlLabelTemplateDbEntity.cs` | **移除** Partner/Region 列属性 |
  260 +| `Helpers/LabelTemplateScopeSchemaHelper.cs` | 列/表探测 + `SetAppliedScopeTypesAsync` raw SQL |
  261 +| `Services/LabelTemplateAppService.cs` | 安全排序、Create/Update 写 scope 列、列表健壮性 |
  262 +| `Helpers/LabelTemplateScopeHelper.cs` | 未迁移库 scope 过滤/展示(6-17) |
  263 +| `Helpers/LocationScopeBindingHelper.cs` | `ResolveFilteredLocationIdsForListAsync` |
  264 +| `Helpers/LabelTemplateListItemsHelper.cs` | Items 列 |
  265 +| `Dtos/LabelTemplate/LabelTemplateGetListInputVo.cs` | `PartnerId` 筛选 |
  266 +
  267 +---
  268 +
  269 +## 八、数据库迁移(可选)
  270 +
  271 +需完整 Company / Region 三维 scope 时,执行:
  272 +
  273 +`美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_label_template_scope.sql`
  274 +
  275 +未执行前:**列表可正常返回**(6-17 + 6-18),但无法持久化 Company/Region 多选明细。
  276 +
  277 +---
  278 +
  279 +## 九、App 标签预览 `POST /api/app/us-app-labeling/preview`
  280 +
  281 +### 现象
  282 +
  283 +App 标签预览页调用 preview 失败(500 或 400),常与 **label-template 列表** 同源:加载模板头时 ORM 仍 SELECT 不存在的 `AppliedPartnerType` / `AppliedRegionType`。
  284 +
  285 +另有两项逻辑缺陷(与 `6-11` 文档不一致):
  286 +
  287 +| # | 问题 | 后果 |
  288 +|---|------|------|
  289 +| 1 | `LabelAppService.PreviewAsync` 全表查询 `FlLabelTemplateDbEntity` | 未迁移 scope 列时 **Unknown column** → 500 |
  290 +| 2 | `UsAppLabelingAppService.PreviewAsync` 未向 `_labelAppService.PreviewAsync` 传 **`locationId`** | 模板含 Company 自动生成元素时报 **「预览/打印需要 locationId 以填充 Company 信息」** |
  291 +| 3 | 出参 **`labelId`** 仍返回 `fl_label.Id`(GUID) | 与 Print Log 当日序号 `yyyyMMdd-n` 不一致 |
  292 +
  293 +### 修复说明
  294 +
  295 +| 改动 | 说明 |
  296 +|------|------|
  297 +| `LabelAppService.PreviewAsync` | 模板头查询改用 `LabelTemplateQueryHelper.ProjectListColumns` |
  298 +| `UsAppLabelingAppService.PreviewAsync` | 传入 `LocationId`;`labelId` 改用 `ReportsPrintLogDailyLabelIdHelper.ResolveNextDailyLabelIdAsync` |
  299 +| `UsAppLabelingAppService.PrintAsync` | 解析模板时同步传入 `LocationId`(打印与预览 Company 填充一致) |
  300 +| `DashboardAppService` | 模板统计 Count 同样走 `ProjectListColumns` |
  301 +
  302 +### 接口说明
  303 +
  304 +| 项目 | 内容 |
  305 +|------|------|
  306 +| 方法 | `POST` |
  307 +| 路径 | `/api/app/us-app-labeling/preview` |
  308 +| 鉴权 | App Bearer Token |
  309 +
  310 +#### 入参(Body:`UsAppLabelPreviewInputVo`)
  311 +
  312 +| 字段 | 类型 | 必填 | 说明 |
  313 +|------|------|------|------|
  314 +| `locationId` | string | 是 | 当前门店 Id(`location.Id`) |
  315 +| `labelCode` | string | 是 | 标签编码(`fl_label.LabelCode`) |
  316 +| `productId` | string | 否 | 预览产品 Id;不传则取标签绑定第一个产品 |
  317 +| `baseTime` | DateTime | 否 | 日期/时间控件基准;也用于计算当日 `labelId` 序号;未传为服务器当前时间 |
  318 +| `printInputJson` | object | 否 | `PRINT_INPUT` 元素用户输入 |
  319 +
  320 +#### 出参(`UsAppLabelPreviewDto`)
  321 +
  322 +| 字段 | 说明 |
  323 +|------|------|
  324 +| **`labelId`** | 门店当日**下一个**打印序号 `yyyyMMdd-n`(预览不落库) |
  325 +| `locationId` / `labelCode` | 回传入参 |
  326 +| `template` | 已解析 AUTO_DB / PRINT_INPUT 的模板结构(含 Company 自动填充) |
  327 +| `labelLastEdited` | 标签最近编辑时间 |
  328 +| 其它 | `typeName`、`productName`、`templateProductDefaultValues` 等 |
  329 +
  330 +#### `labelId` 规则
  331 +
  332 +与 `6-11`、`get-print-log-list` 一致:`{baseTime 日期 yyyyMMdd}-{当日已有打印任务数 + 1}`。
  333 +
  334 +#### Company 自动元素
  335 +
  336 +模板含 Company 自动生成控件时,后端根据 **`locationId`** 查 `fl_partner` 填充 `config.text`(详见 `6-11` 第二节)。
  337 +
  338 +### 请求示例
  339 +
  340 +```bash
  341 +curl -X POST "http://flus-test.3ffoodsafety.com/api/app/us-app-labeling/preview" \
  342 + -H "Authorization: Bearer {token}" \
  343 + -H "Content-Type: application/json" \
  344 + -d '{
  345 + "locationId": "550e8400-e29b-41d4-a716-446655440000",
  346 + "labelCode": "LBL0001",
  347 + "productId": "PROD001",
  348 + "baseTime": "2026-06-18T09:00:00"
  349 + }'
  350 +```
  351 +
  352 +### 响应片段(示例)
  353 +
  354 +```json
  355 +{
  356 + "labelId": "20260618-3",
  357 + "locationId": "550e8400-e29b-41d4-a716-446655440000",
  358 + "labelCode": "LBL0001",
  359 + "labelLastEdited": "2026-06-01T08:30:09",
  360 + "template": {
  361 + "id": "tpl_xxx",
  362 + "width": 2,
  363 + "height": 2,
  364 + "unit": "inch",
  365 + "elements": []
  366 + }
  367 +}
  368 +```
  369 +
  370 +### 验证步骤
  371 +
  372 +1. 停服 → `dotnet build` → 重启(同 label-template 一节)。
  373 +2. App 进入标签预览页,Network 中 preview 应 **200**。
  374 +3. 响应 `labelId` 为 `yyyyMMdd-n`,非 GUID。
  375 +4. 模板含 Company 元素时,`template.elements` 中对应 `config.text` 为门店所属公司名。
  376 +5. 当日已有 N 条打印任务时,preview 返回 `-{N+1}`。
  377 +
  378 +### 涉及代码(preview)
  379 +
  380 +| 文件 | 说明 |
  381 +|------|------|
  382 +| `Services/UsAppLabelingAppService.cs` | `PreviewAsync` / `PrintAsync` 传 `LocationId`、当日 `labelId` |
  383 +| `Services/LabelAppService.cs` | `PreviewAsync` 模板头 `ProjectListColumns` |
  384 +| `Helpers/LabelTemplateQueryHelper.cs` | 列投影 |
  385 +| `Helpers/ReportsPrintLogDailyLabelIdHelper.cs` | `ResolveNextDailyLabelIdAsync` |
  386 +| `Helpers/PartnerCompanyDisplayHelper.cs` | Company 自动填充 |
  387 +
  388 +---
  389 +
  390 +## 十、App 打印日志 `POST /api/app/us-app-labeling/get-print-log-list`
  391 +
  392 +### 现象
  393 +
  394 +Postman 传 `printDate: "2026-06-16"` 返回 `totalCount: 0`,误以为接口异常。
  395 +
  396 +### 根因(查库核对)
  397 +
  398 +门店 `3a218397-8dda-a378-e024-ef89bcef8d24` 在测试库中:
  399 +
  400 +| 自然日(`DATE(IFNULL(PrintedAt, CreationTime))`) | 记录数 |
  401 +|---------------------------------------------------|--------|
  402 +| `2026-06-01` | **7** |
  403 +| `2026-05-31` | **3** |
  404 +| `2026-06-16` | **0** |
  405 +
  406 +**接口按入参日期筛选时,该日无数据则返回空列表,行为正确。** 文档/示例误用 `2026-06-16`,应改用 **`2026-06-01`** 验证。
  407 +
  408 +另:`PrintedAt` 入库多为 `null`,筛选实际走 **`CreationTime`**。
  409 +
  410 +### 本轮修复
  411 +
  412 +| 改动 | 说明 |
  413 +|------|------|
  414 +| 日期条件 | 改用 MySQL `DATE(IFNULL(t.PrintedAt, t.CreationTime)) = 'yyyy-MM-dd'`,避免 DateTime 区间比较时区偏差 |
  415 +| `printDateDay` | 新增字符串入参(`yyyy-MM-dd`),优先于 `printDate`,避免 JSON 仅日期 UTC 歧义 |
  416 +| 未传日期 | **`printDate` 与 `printDateDay` 均未传时不按日过滤**(返回该门店全部打印记录,兼容 App 未传参) |
  417 +| `labelId` | 列表出参改为当日序号 `yyyyMMdd-n`;`labelEntityId` 为 `fl_label.Id` |
  418 +
  419 +### 请求示例(有数据的日期)
  420 +
  421 +```bash
  422 +curl -X POST "http://192.168.1.4:19001/api/app/us-app-labeling/get-print-log-list" \
  423 + -H "Authorization: Bearer {token}" \
  424 + -H "Content-Type: application/json" \
  425 + -d '{
  426 + "locationId": "3a218397-8dda-a378-e024-ef89bcef8d24",
  427 + "skipCount": 1,
  428 + "maxResultCount": 20,
  429 + "printDateDay": "2026-06-01"
  430 + }'
  431 +```
  432 +
  433 +或使用 `"printDate": "2026-06-01"`(等价)。
  434 +
  435 +### 权限说明
  436 +
  437 +非 admin / 非 Partner 角色时,仅返回 **`CreatedBy = 当前用户`** 的记录;若 Token 用户不是打印人,即使日期正确也会空列表。
  438 +
  439 +### 部署
  440 +
  441 +修改在 `FoodLabeling.Application`,需 **停服 → dotnet build → 重启** 后 Postman 才生效。
  442 +
  443 +### 涉及代码
  444 +
  445 +| 文件 | 说明 |
  446 +|------|------|
  447 +| `Helpers/ReportsPrintLogDailyLabelIdHelper.cs` | `ResolvePrintLogFilterCalendarDay`、`ApplyPrintTaskCalendarDayFilter` |
  448 +| `Dtos/UsAppLabeling/PrintLogGetListInputVo.cs` | `PrintDateDay` |
  449 +| `Services/UsAppLabelingAppService.cs` | `GetPrintLogListAsync` |
  450 +
  451 +---
  452 +
  453 +## 关联文档
  454 +
  455 +- App Preview labelId / Company:`项目相关文档/6-11代码优化.md`
  456 +- 第一轮 scope 兼容:`项目相关文档/6-17代码优化.md`(第一节、第二节 get-print-log-list)
  457 +- 三维 scope 业务规则:`项目相关文档/6-4代码优化.md`
  458 +- 分页约定:`Helpers/PagedQueryConvention.cs`
... ...
美国版/Food Labeling Management App UniApp/src/pages/labels/labels.vue
... ... @@ -44,7 +44,7 @@
44 44 class="cat-icon"
45 45 :class="[
46 46 labelCategoryVisual(cat).mode === 'image' ? 'cat-icon--photo' : 'cat-icon--fallback',
47   - isTextIconVisual(labelCategoryVisual(cat)) ? 'cat-icon--text-fit' : 'cat-icon--fixed',
  47 + 'cat-icon--fixed',
48 48 ]"
49 49 :style="labelCategoryIconBoxStyle(cat)"
50 50 >
... ... @@ -54,16 +54,22 @@
54 54 class="cat-photo"
55 55 mode="aspectFill"
56 56 />
57   - <text
  57 + <view
58 58 v-else-if="labelCategoryVisual(cat).mode === 'colorText'"
59   - class="cat-icon-text cat-icon-text--on-color"
60   - :style="{ color: labelCategoryVisual(cat).textColor || '#ffffff' }"
  59 + class="cat-icon-text-inner"
61 60 >
62   - {{ labelCategoryVisual(cat).text }}
63   - </text>
64   - <text v-else-if="labelCategoryVisual(cat).mode === 'text'" class="cat-icon-text">
65   - {{ labelCategoryVisual(cat).text }}
66   - </text>
  61 + <text
  62 + class="cat-icon-text cat-icon-text--on-color cat-icon-text--wrap"
  63 + :style="{ color: labelCategoryVisual(cat).textColor || '#ffffff' }"
  64 + >
  65 + {{ labelCategoryVisual(cat).text }}
  66 + </text>
  67 + </view>
  68 + <view v-else-if="labelCategoryVisual(cat).mode === 'text'" class="cat-icon-text-inner">
  69 + <text class="cat-icon-text cat-icon-text--wrap">
  70 + {{ labelCategoryVisual(cat).text }}
  71 + </text>
  72 + </view>
67 73 </view>
68 74 <text class="cat-name">{{ cat.categoryName }}</text>
69 75 </view>
... ... @@ -120,9 +126,7 @@
120 126 productCategoryVisual(pCat).mode === 'image'
121 127 ? 'cat-header-thumb--photo'
122 128 : 'cat-header-thumb--fallback',
123   - isTextIconVisual(productCategoryVisual(pCat))
124   - ? 'cat-header-thumb--text-fit'
125   - : 'cat-header-thumb--fixed',
  129 + 'cat-header-thumb--fixed',
126 130 ]"
127 131 :style="catHeaderThumbStyle(pCat)"
128 132 >
... ... @@ -132,24 +136,30 @@
132 136 class="cat-photo"
133 137 mode="aspectFill"
134 138 />
135   - <text
  139 + <view
136 140 v-else-if="productCategoryVisual(pCat).mode === 'colorText'"
137   - class="cat-icon-text cat-icon-text--on-color cat-icon-text--header"
138   - :style="{ color: productCategoryVisual(pCat).textColor || '#ffffff' }"
  141 + class="cat-header-text-inner"
139 142 >
140   - {{ categoryHeaderThumbText(pCat) }}
141   - </text>
  143 + <text
  144 + class="cat-icon-text cat-icon-text--on-color cat-icon-text--header cat-icon-text--wrap"
  145 + :style="{ color: productCategoryVisual(pCat).textColor || '#ffffff' }"
  146 + >
  147 + {{ categoryHeaderThumbText(pCat) }}
  148 + </text>
  149 + </view>
142 150 <view
143 151 v-else-if="productCategoryVisual(pCat).mode === 'color'"
144 152 class="cat-header-color-fill"
145 153 :style="{ backgroundColor: productCategoryVisual(pCat).bg }"
146 154 />
147   - <text
  155 + <view
148 156 v-else-if="productCategoryVisual(pCat).mode === 'text'"
149   - class="cat-icon-text cat-icon-text--header"
  157 + class="cat-header-text-inner"
150 158 >
151   - {{ categoryHeaderThumbText(pCat) }}
152   - </text>
  159 + <text class="cat-icon-text cat-icon-text--header cat-icon-text--wrap">
  160 + {{ categoryHeaderThumbText(pCat) }}
  161 + </text>
  162 + </view>
153 163 <view v-else class="cat-header-fallback" :class="colorClassForName(pCat.name)">
154 164 <AppIcon name="food" size="sm" color="white" />
155 165 </view>
... ... @@ -199,19 +209,25 @@
199 209 class="food-img"
200 210 mode="aspectFill"
201 211 />
202   - <text
  212 + <view
203 213 v-else-if="productVisual(product, pCat).mode === 'colorText'"
204   - class="food-thumb-text food-thumb-text--on-color"
205   - :style="{ color: productVisual(product, pCat).textColor || '#ffffff' }"
  214 + class="food-thumb-text-wrap"
206 215 >
207   - {{ productThumbDisplayText(product, pCat) }}
208   - </text>
209   - <text
  216 + <text
  217 + class="food-thumb-text food-thumb-text--on-color"
  218 + :style="{ color: productVisual(product, pCat).textColor || '#ffffff' }"
  219 + >
  220 + {{ productThumbDisplayText(product, pCat) }}
  221 + </text>
  222 + </view>
  223 + <view
210 224 v-else-if="productVisual(product, pCat).mode === 'text'"
211   - class="food-thumb-text"
  225 + class="food-thumb-text-wrap"
212 226 >
213   - {{ productThumbDisplayText(product, pCat) }}
214   - </text>
  227 + <text class="food-thumb-text">
  228 + {{ productThumbDisplayText(product, pCat) }}
  229 + </text>
  230 + </view>
215 231 <view
216 232 v-else-if="productVisual(product, pCat).mode === 'color'"
217 233 class="food-thumb-color-fill"
... ... @@ -222,7 +238,7 @@
222 238 class="food-thumb-fallback"
223 239 :class="colorClassForName(product.productName)"
224 240 >
225   - <text class="food-thumb-text food-thumb-text--on-color">
  241 + <text class="food-thumb-text food-thumb-text--on-color food-thumb-text--wrap">
226 242 {{ productThumbFallbackText(product) }}
227 243 </text>
228 244 </view>
... ... @@ -319,13 +335,12 @@ function scaleRpx(base: number): number {
319 335 }
320 336  
321 337 const ICON_FIXED_RPX = 64
322   -const ICON_TEXT_MIN_RPX = 48
323 338  
324 339 function isTextIconVisual(v: CategoryVisualRender): boolean {
325 340 return v.mode === 'text' || v.mode === 'colorText'
326 341 }
327 342  
328   -/** 无文字(图片/纯色/占位):固定方形容器 */
  343 +/** 固定方形容器(图片/纯色/文字均不撑开) */
329 344 function fixedIconBoxStyle(sideRpx = ICON_FIXED_RPX): Record<string, string> {
330 345 const side = scaleRpx(sideRpx)
331 346 return {
... ... @@ -339,25 +354,6 @@ function fixedIconBoxStyle(sideRpx = ICON_FIXED_RPX): Record&lt;string, string&gt; {
339 354 }
340 355 }
341 356  
342   -/** 有 Display Text:宽高随文字,仅保留最小尺寸与最大宽度 */
343   -function textFitIconBoxStyle(opts?: { maxWidthRpx?: number; bg?: string }): Record<string, string> {
344   - const minSide = scaleRpx(ICON_TEXT_MIN_RPX)
345   - const padV = scaleRpx(8)
346   - const padH = scaleRpx(12)
347   - const style: Record<string, string> = {
348   - width: 'auto',
349   - height: 'auto',
350   - minWidth: `${minSide}rpx`,
351   - minHeight: `${minSide}rpx`,
352   - maxWidth: `${scaleRpx(opts?.maxWidthRpx ?? 168)}rpx`,
353   - maxHeight: 'none',
354   - padding: `${padV}rpx ${padH}rpx`,
355   - overflow: 'visible',
356   - }
357   - if (opts?.bg) style.backgroundColor = opts.bg
358   - return style
359   -}
360   -
361 357 const labelTree = ref<UsAppLabelCategoryTreeNodeDto[]>([])
362 358 const listLoading = ref(false)
363 359 const listError = ref('')
... ... @@ -473,10 +469,9 @@ function labelCategoryVisual(cat: UsAppLabelCategoryTreeNodeDto): CategoryVisual
473 469 function labelCategoryIconBoxStyle(cat: UsAppLabelCategoryTreeNodeDto): Record<string, string> {
474 470 const v = labelCategoryVisual(cat)
475 471 if (isTextIconVisual(v)) {
476   - return textFitIconBoxStyle({
477   - maxWidthRpx: 168,
478   - bg: v.mode === 'colorText' ? v.bg : undefined,
479   - })
  472 + const style = fixedIconBoxStyle()
  473 + if (v.mode === 'colorText') style.backgroundColor = v.bg
  474 + return style
480 475 }
481 476 if (v.mode === 'color') {
482 477 return { ...fixedIconBoxStyle(), backgroundColor: v.bg }
... ... @@ -558,15 +553,10 @@ function catHeaderThumbStyle(p: UsAppProductCategoryNodeDto): Record&lt;string, str
558 553 backgroundColor: '#f3f4f6',
559 554 }
560 555 if (isTextIconVisual(v)) {
561   - Object.assign(
562   - style,
563   - textFitIconBoxStyle({
564   - maxWidthRpx: 320,
565   - bg: v.mode === 'colorText' ? v.bg : undefined,
566   - }),
567   - )
  556 + Object.assign(style, fixedIconBoxStyle(72))
  557 + if (v.mode === 'colorText') style.backgroundColor = v.bg
568 558 } else {
569   - Object.assign(style, fixedIconBoxStyle())
  559 + Object.assign(style, fixedIconBoxStyle(72))
570 560 }
571 561 if (v.mode === 'color') {
572 562 style.backgroundColor = v.bg
... ... @@ -574,7 +564,7 @@ function catHeaderThumbStyle(p: UsAppProductCategoryNodeDto): Record&lt;string, str
574 564 return style
575 565 }
576 566  
577   -/** 分类标题行图标内文案:单行省略,避免换行裁切 */
  567 +/** 分类标题行图标内文案:Display Text 在框内换行展示 */
578 568 function categoryHeaderThumbText(p: UsAppProductCategoryNodeDto): string {
579 569 const v = productCategoryVisual(p)
580 570 const raw =
... ... @@ -590,12 +580,9 @@ function productThumbDisplayText(
590 580 ): string {
591 581 const v = productVisual(p, pCat)
592 582 if (v.mode !== 'text' && v.mode !== 'colorText') return ''
593   - const name = (p.productName ?? '').trim().toLowerCase()
594 583 const t = (v.text ?? '').trim()
595   - if (name && t.toLowerCase() === name) {
596   - return productThumbFallbackText(p)
597   - }
598   - return t || productThumbFallbackText(p)
  584 + const name = (p.productName ?? '').trim()
  585 + return t || name || '?'
599 586 }
600 587  
601 588 function showFoodSubtitle(p: UsAppLabelingProductNodeDto): boolean {
... ... @@ -904,6 +891,7 @@ const goBluetoothPage = () =&gt; {
904 891 }
905 892  
906 893 .cat-icon {
  894 + position: relative;
907 895 display: flex;
908 896 align-items: center;
909 897 justify-content: center;
... ... @@ -915,20 +903,21 @@ const goBluetoothPage = () =&gt; {
915 903 .cat-icon--fixed {
916 904 width: 64rpx;
917 905 height: 64rpx;
  906 + overflow: hidden;
918 907 }
919 908  
920   -.cat-icon--text-fit {
921   - width: auto;
922   - height: auto;
923   -}
924   -
925   -.cat-icon--text-fit .cat-icon-text,
926   -.cat-icon--text-fit .cat-icon-text--on-color {
927   - max-width: none;
928   - padding: 0;
929   - overflow: visible;
930   - text-overflow: clip;
931   - white-space: nowrap;
  909 +.cat-icon-text-inner {
  910 + position: absolute;
  911 + left: 0;
  912 + top: 0;
  913 + right: 0;
  914 + bottom: 0;
  915 + display: flex;
  916 + align-items: center;
  917 + justify-content: center;
  918 + overflow: hidden;
  919 + padding: 4rpx 6rpx;
  920 + box-sizing: border-box;
932 921 }
933 922  
934 923 .cat-icon--photo {
... ... @@ -951,26 +940,31 @@ const goBluetoothPage = () =&gt; {
951 940  
952 941 .cat-icon-text {
953 942 max-width: 100%;
954   - padding: 0 6rpx;
  943 + max-height: 100%;
  944 + padding: 0;
955 945 font-size: 20rpx;
956 946 font-weight: 700;
957 947 color: #111827;
958   - line-height: 1;
  948 + line-height: 1.15;
959 949 text-align: center;
960   - white-space: nowrap;
  950 + box-sizing: border-box;
  951 +}
  952 +
  953 +.cat-icon-text--wrap,
  954 +.cat-icon-text--on-color {
  955 + white-space: normal;
  956 + word-break: break-word;
961 957 overflow: hidden;
962   - text-overflow: ellipsis;
963 958 }
964 959  
965 960 .cat-icon-text--on-color {
966 961 max-width: 100%;
967   - padding: 0 4rpx;
  962 + max-height: 100%;
  963 + padding: 0;
968 964 font-size: 18rpx;
969 965 font-weight: 700;
970   - line-height: 1.1;
  966 + line-height: 1.15;
971 967 text-align: center;
972   - white-space: normal;
973   - word-break: break-word;
974 968 }
975 969  
976 970 .cat-name {
... ... @@ -1061,6 +1055,7 @@ const goBluetoothPage = () =&gt; {
1061 1055 }
1062 1056  
1063 1057 .cat-header-thumb {
  1058 + position: relative;
1064 1059 box-sizing: border-box;
1065 1060 }
1066 1061  
... ... @@ -1068,32 +1063,31 @@ const goBluetoothPage = () =&gt; {
1068 1063 overflow: hidden;
1069 1064 }
1070 1065  
1071   -.cat-header-thumb--text-fit {
1072   - overflow: visible;
1073   -}
1074   -
1075   -.cat-header .cat-header-thumb--text-fit .cat-icon-text,
1076   -.cat-header .cat-header-thumb--text-fit .cat-icon-text--on-color,
1077   -.cat-header .cat-header-thumb--text-fit .cat-icon-text--header {
1078   - max-width: none;
1079   - padding: 0;
1080   - overflow: visible;
1081   - text-overflow: clip;
1082   - white-space: nowrap;
1083   - word-break: normal;
  1066 +.cat-header-text-inner {
  1067 + position: absolute;
  1068 + left: 0;
  1069 + top: 0;
  1070 + right: 0;
  1071 + bottom: 0;
  1072 + display: flex;
  1073 + align-items: center;
  1074 + justify-content: center;
  1075 + overflow: hidden;
  1076 + padding: 4rpx 6rpx;
  1077 + box-sizing: border-box;
1084 1078 }
1085 1079  
1086 1080 .cat-header .cat-header-thumb .cat-icon-text,
1087 1081 .cat-header .cat-header-thumb .cat-icon-text--on-color,
1088 1082 .cat-header .cat-header-thumb .cat-icon-text--header {
1089 1083 font-size: 20rpx;
1090   - line-height: 1.1;
1091   - padding: 0 6rpx;
  1084 + line-height: 1.15;
  1085 + padding: 0;
1092 1086 max-width: 100%;
1093   - white-space: nowrap;
  1087 + max-height: 100%;
  1088 + white-space: normal;
  1089 + word-break: break-word;
1094 1090 overflow: hidden;
1095   - text-overflow: ellipsis;
1096   - word-break: normal;
1097 1091 }
1098 1092  
1099 1093 .cat-header-thumb--photo,
... ... @@ -1208,9 +1202,7 @@ const goBluetoothPage = () =&gt; {
1208 1202 }
1209 1203  
1210 1204 .food-img-wrap--fallback {
1211   - display: flex;
1212   - align-items: center;
1213   - justify-content: center;
  1205 + display: block;
1214 1206 }
1215 1207  
1216 1208 .food-img {
... ... @@ -1221,29 +1213,44 @@ const goBluetoothPage = () =&gt; {
1221 1213 height: 100%;
1222 1214 }
1223 1215  
1224   -.food-thumb-text {
  1216 +.food-thumb-text-wrap {
1225 1217 position: absolute;
1226 1218 left: 0;
1227 1219 top: 0;
  1220 + right: 0;
  1221 + bottom: 0;
1228 1222 width: 100%;
1229 1223 height: 100%;
1230 1224 display: flex;
1231 1225 align-items: center;
1232 1226 justify-content: center;
1233   - padding: 8rpx;
  1227 + padding: 10rpx 12rpx;
1234 1228 box-sizing: border-box;
  1229 + overflow: hidden;
  1230 +}
  1231 +
  1232 +.food-thumb-text {
  1233 + width: 100%;
  1234 + max-width: 100%;
  1235 + max-height: 100%;
1235 1236 font-size: 22rpx;
1236 1237 font-weight: 700;
1237 1238 color: #111827;
1238   - line-height: 1.15;
  1239 + line-height: 1.25;
1239 1240 text-align: center;
1240   - white-space: nowrap;
  1241 + white-space: normal;
  1242 + word-break: break-word;
1241 1243 overflow: hidden;
1242   - text-overflow: ellipsis;
  1244 + box-sizing: border-box;
  1245 +}
  1246 +
  1247 +.food-thumb-text--wrap {
  1248 + white-space: normal;
  1249 + word-break: break-word;
1243 1250 }
1244 1251  
1245 1252 .food-thumb-text--on-color {
1246   - font-size: 24rpx;
  1253 + font-size: 22rpx;
1247 1254 color: #ffffff;
1248 1255 }
1249 1256  
... ...
美国版/Food Labeling Management App UniApp/src/pages/labels/preview.vue
... ... @@ -294,6 +294,10 @@ import {
294 294 applyLabelIdDisplayToTemplate,
295 295 templateIncludesLabelIdElement,
296 296 } from '../../utils/labelPreview/labelIdElement'
  297 +import {
  298 + applyEmployeeDisplayToTemplate,
  299 + templateIncludesEmployeeElement,
  300 +} from '../../utils/labelPreview/employeeElement'
297 301 import { applyLiveDateTimeFieldsToTemplate } from '../../utils/labelPreview/printInputOffset'
298 302 import {
299 303 getLabelPrintRasterLayout,
... ... @@ -808,9 +812,8 @@ const locationName = ref(&#39;&#39;)
808 812 const printLabelDisplayId = ref('')
809 813  
810 814 const footerLabelIdDisplay = computed(() => {
811   - const daily = printLabelDisplayId.value.trim()
812   - const code = labelCode.value.trim()
813   - return daily || code || '—'
  815 + const id = printLabelDisplayId.value.trim()
  816 + return id || '—'
814 817 })
815 818  
816 819 const previewLoading = ref(true)
... ... @@ -1176,6 +1179,9 @@ function computeMergedPreviewTemplate(at?: Date): SystemLabelTemplate | null {
1176 1179 if (templateIncludesLabelIdElement(m) && printLabelDisplayId.value.trim()) {
1177 1180 m = applyLabelIdDisplayToTemplate(m, printLabelDisplayId.value.trim())
1178 1181 }
  1182 + if (templateIncludesEmployeeElement(m)) {
  1183 + m = applyEmployeeDisplayToTemplate(m)
  1184 + }
1179 1185 m = applyLiveDateTimeFieldsToTemplate(m, baseTime)
1180 1186 return m
1181 1187 }
... ... @@ -1345,7 +1351,7 @@ async function loadPreview() {
1345 1351 ? (nested as Record<string, unknown>)
1346 1352 : null
1347 1353  
1348   - /** 8.2 预览:labelLastEdited / printLabelDisplayId(兼容 data 嵌套、PascalCase) */
  1354 + /** 8.2 预览:labelLastEdited / labelId(兼容 printLabelDisplayId、PascalCase、data 嵌套) */
1349 1355 const readLastEdited = (L: Record<string, unknown> | null): string => {
1350 1356 if (!L) return ''
1351 1357 const v =
... ... @@ -1357,12 +1363,19 @@ async function loadPreview() {
1357 1363 }
1358 1364 const readPrintLabelDisplayId = (L: Record<string, unknown> | null): string => {
1359 1365 if (!L) return ''
1360   - const v =
1361   - L.printLabelDisplayId ??
1362   - L.PrintLabelDisplayId ??
1363   - L.labelDisplayId ??
1364   - L.LabelDisplayId
1365   - return v != null && String(v).trim() !== '' ? String(v).trim() : ''
  1366 + const keys = [
  1367 + 'printLabelDisplayId',
  1368 + 'PrintLabelDisplayId',
  1369 + 'labelDisplayId',
  1370 + 'LabelDisplayId',
  1371 + 'labelId',
  1372 + 'LabelId',
  1373 + ]
  1374 + for (const key of keys) {
  1375 + const v = L[key]
  1376 + if (v != null && String(v).trim() !== '') return String(v).trim()
  1377 + }
  1378 + return ''
1366 1379 }
1367 1380  
1368 1381 const leStr = readLastEdited(root) || readLastEdited(inner)
... ...
美国版/Food Labeling Management App UniApp/src/pages/more/print-log.vue
... ... @@ -35,9 +35,9 @@
35 35 <view class="date-filter-bar">
36 36 <view class="date-field">
37 37 <AppDatePicker
38   - :model-value="selectedDate"
  38 + :model-value="datePickerModelValue"
39 39 :max="todayYmd"
40   - placeholder="All dates"
  40 + placeholder="ALL"
41 41 dialog-title="Print date"
42 42 @update:model-value="onDateConfirm"
43 43 @cancel="onDateCancel"
... ... @@ -45,7 +45,7 @@
45 45 </view>
46 46 <view
47 47 class="today-btn"
48   - :class="{ active: selectedDate === todayYmd }"
  48 + :class="{ active: isTodayFilter }"
49 49 @click="selectToday"
50 50 >
51 51 <text class="today-btn-text">Today</text>
... ... @@ -188,34 +188,53 @@ function formatYmd (d: Date): string {
188 188 }
189 189  
190 190 const todayYmd = formatYmd(new Date())
191   -/** 已生效的筛选日期;空字符串表示查询全部(不传 printDate) */
192   -const selectedDate = ref('')
  191 +/**
  192 + * null = 不传 printDateDay,后端不按日过滤(6-18 返回该门店全部记录);
  193 + * yyyy-MM-dd = 确认后传 printDateDay 筛选该自然日。
  194 + */
  195 +const filterDateYmd = ref<string | null>(todayYmd)
  196 +
  197 +const isTodayFilter = computed(() => filterDateYmd.value === todayYmd)
  198 +const isAllDatesFilter = computed(() => filterDateYmd.value === null)
  199 +/** 查全部时不传日期,控件显示 placeholder「ALL」 */
  200 +const datePickerModelValue = computed(() => filterDateYmd.value ?? '')
193 201  
194 202 function toPrintDatePayload (ymd: string): string {
195   - const date = (ymd || '').trim()
196   - if (!date) return ''
197   - return `${date}T00:00:00`
  203 + return (ymd || '').trim()
  204 +}
  205 +
  206 +function formatMdY (ymd: string): string {
  207 + const [y, m, d] = ymd.split('-')
  208 + if (!y || !m || !d) return ymd
  209 + return `${m}/${d}/${y}`
  210 +}
  211 +
  212 +/** 6-18:未传 printDateDay 时不带该字段;选定日期时传 yyyy-MM-dd */
  213 +function resolvePrintDateDayForApi (): string | undefined {
  214 + if (filterDateYmd.value === null) return undefined
  215 + const payload = toPrintDatePayload(filterDateYmd.value)
  216 + return payload || undefined
198 217 }
199 218  
200 219 const emptyStateText = computed(() => {
201   - const date = (selectedDate.value || '').trim()
202   - if (!date) return 'No print records'
203   - const [y, m, d] = date.split('-')
204   - return `No print records for ${m}/${d}/${y}`
  220 + if (isAllDatesFilter.value) return 'No print records'
  221 + const ymd = filterDateYmd.value ?? todayYmd
  222 + return `No print records for ${formatMdY(ymd)}`
205 223 })
206 224  
207 225 function onDateConfirm (value: string) {
208   - selectedDate.value = (value || '').trim()
  226 + const next = (value || '').trim()
  227 + filterDateYmd.value = next || todayYmd
209 228 loadPage(true)
210 229 }
211 230  
212 231 function onDateCancel () {
213   - selectedDate.value = ''
  232 + filterDateYmd.value = null
214 233 loadPage(true)
215 234 }
216 235  
217 236 function selectToday () {
218   - selectedDate.value = todayYmd
  237 + filterDateYmd.value = todayYmd
219 238 loadPage(true)
220 239 }
221 240  
... ... @@ -312,7 +331,7 @@ async function loadPage (reset: boolean) {
312 331 locationId,
313 332 skipCount: p,
314 333 maxResultCount: pageSize,
315   - printDate: toPrintDatePayload(selectedDate.value) || undefined,
  334 + printDateDay: resolvePrintDateDayForApi(),
316 335 })
317 336 if (reset) {
318 337 items.value = res.items
... ...
美国版/Food Labeling Management App UniApp/src/services/usAppLabeling.ts
... ... @@ -472,21 +472,25 @@ export async function fetchUsAppLabelReport (
472 472 return normalizeUsAppLabelReport(raw)
473 473 }
474 474  
475   -/** 接口 10:分页打印日志 */
  475 +/** 接口 10:分页打印日志(6-18 支持 printDateDay / printDate 按自然日筛选) */
476 476 export async function fetchUsAppPrintLogList (input: PrintLogGetListInputVo) {
477   - const printDate = (input.printDate || '').trim()
478   - const key = `print-log:${input.locationId}:${printDate}:${input.skipCount ?? 1}:${input.maxResultCount ?? 20}`
  477 + const printDateDay = (input.printDateDay || input.printDate || '').trim()
  478 + const dateKey = printDateDay || '__all_dates__'
  479 + const key = `print-log:${input.locationId}:${dateKey}:${input.skipCount ?? 1}:${input.maxResultCount ?? 20}`
479 480 return fetchWithOfflineCache('labeling', key, async () => {
  481 + const body: Record<string, unknown> = {
  482 + locationId: input.locationId,
  483 + skipCount: input.skipCount ?? 1,
  484 + maxResultCount: input.maxResultCount ?? 20,
  485 + }
  486 + if (printDateDay) {
  487 + body.printDateDay = printDateDay
  488 + }
480 489 const raw = await usAppApiRequest<unknown>({
481 490 path: '/api/app/us-app-labeling/get-print-log-list',
482 491 method: 'POST',
483 492 auth: true,
484   - data: {
485   - locationId: input.locationId,
486   - skipCount: input.skipCount ?? 1,
487   - maxResultCount: input.maxResultCount ?? 20,
488   - ...(printDate ? { printDate } : {}),
489   - },
  493 + data: body,
490 494 })
491 495 return extractPagedItems<PrintLogItemDto>(raw)
492 496 })
... ...
美国版/Food Labeling Management App UniApp/src/types/usAppLabeling.ts
... ... @@ -73,8 +73,9 @@ export interface UsAppLabelPreviewInputVo {
73 73  
74 74 /** 8.2 预览响应(解包后常见字段,供类型参考) */
75 75 export interface UsAppLabelPreviewDto {
  76 + /** 门店当日打印序号(yyyyMMdd-n),页脚 Label ID 与模板 Label ID 控件展示用 */
76 77 labelId?: string
77   - /** 模板含 Label ID 控件时,接口返回的门店当日打印序号(yyyyMMdd-n),用于画布预览/出纸 */
  78 + /** 与 labelId 同源(部分环境字段名) */
78 79 printLabelDisplayId?: string
79 80 labelLastEdited?: string
80 81 labelCode?: string
... ... @@ -113,12 +114,17 @@ export interface UsAppLabelPrintOutputDto {
113 114 mergedTemplateJson?: string | null
114 115 }
115 116  
116   -/** 接口 10 分页入参 */
  117 +/** 接口 10 分页入参(6-18 get-print-log-list) */
117 118 export interface PrintLogGetListInputVo {
118 119 locationId: string
119 120 skipCount?: number
120 121 maxResultCount?: number
121   - /** 打印日期(自然日),如 2026-06-16T00:00:00;不传时由后端按约定处理 */
  122 + /**
  123 + * 打印日期(自然日),优先使用 `printDateDay`(`yyyy-MM-dd`),避免 JSON DateTime UTC 歧义。
  124 + * 与 `printDate` 等价;二者均未传时不按日过滤(返回该门店全部记录)。
  125 + */
  126 + printDateDay?: string
  127 + /** @deprecated 请用 printDateDay;仍可与 printDateDay 二选一传参 */
122 128 printDate?: string
123 129 }
124 130  
... ...
美国版/Food Labeling Management App UniApp/src/utils/labelPreview/employeeElement.ts 0 → 100644
  1 +import type { SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
  2 +
  3 +function normalizePaletteSlug (raw: string): string {
  4 + return String(raw ?? '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '')
  5 +}
  6 +
  7 +function readTypeAdd (el: SystemTemplateElementBase): string {
  8 + return String((el as SystemTemplateElementBase & { typeAdd?: string }).typeAdd ?? '').trim().toLowerCase()
  9 +}
  10 +
  11 +/** 当前登录用户展示名(与侧栏 / Profile 一致) */
  12 +export function getLoggedInEmployeeDisplayName (): string {
  13 + const name = String(uni.getStorageSync('userName') || '').trim()
  14 + if (name) return name
  15 + const email = String(uni.getStorageSync('user_email') || '').trim()
  16 + if (email) {
  17 + const at = email.indexOf('@')
  18 + return at > 0 ? email.slice(0, at) : email
  19 + }
  20 + return 'Employee'
  21 +}
  22 +
  23 +/** 是否为模板「Entered Automatically → Employee」控件 */
  24 +export function isEmployeeTemplateElement (el: SystemTemplateElementBase): boolean {
  25 + const typeAdd = readTypeAdd(el)
  26 + if (typeAdd.startsWith('auto_') && typeAdd.includes('employee')) return true
  27 +
  28 + const en = normalizePaletteSlug(String(el.elementName ?? ''))
  29 + if (/^employee\d*$/.test(en)) return true
  30 +
  31 + const vst = String(el.valueSourceType ?? '').toUpperCase()
  32 + const type = String(el.type ?? '').toUpperCase()
  33 + if (vst === 'AUTO_DB' && type === 'TEXT_STATIC' && /^employee/.test(en)) return true
  34 +
  35 + return false
  36 +}
  37 +
  38 +export function templateIncludesEmployeeElement (
  39 + template: SystemLabelTemplate | null | undefined,
  40 +): boolean {
  41 + return !!(template?.elements?.some(isEmployeeTemplateElement))
  42 +}
  43 +
  44 +/** 将当前登录人姓名写入 Employee AUTO 控件(预览/出纸同源) */
  45 +export function applyEmployeeDisplayToTemplate (
  46 + template: SystemLabelTemplate,
  47 + employeeName?: string | null,
  48 +): SystemLabelTemplate {
  49 + const name = String(employeeName ?? '').trim() || getLoggedInEmployeeDisplayName()
  50 + const elements = (template.elements || []).map((el) => {
  51 + if (!isEmployeeTemplateElement(el)) return el
  52 + const cfg = { ...(el.config || {}) } as Record<string, unknown>
  53 + return {
  54 + ...el,
  55 + config: { ...cfg, text: name, Text: name },
  56 + }
  57 + })
  58 + return { ...template, elements }
  59 +}
... ...
美国版/Food Labeling Management App UniApp/src/utils/labelPreview/normalizePreviewTemplate.ts
1 1 import type { SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
  2 +import { normalizePrintOrientation } from '../print/printOrientation'
2 3 import {
3 4 applyLiveDateTimeFieldsToTemplate,
4 5 resolveTemplateDefaultValueForElement,
... ... @@ -492,6 +493,7 @@ export function normalizeLabelTemplateFromPreviewApi(payload: unknown): SystemLa
492 493 showRuler: !!(t.showRuler ?? t.ShowRuler),
493 494 showGrid: !!(t.showGrid ?? t.ShowGrid),
494 495 border: String(t.border ?? t.Border ?? t.BorderType ?? t.borderType ?? 'none'),
  496 + printOrientation: normalizePrintOrientation(t.printOrientation ?? t.PrintOrientation),
495 497 elements,
496 498 }
497 499 }
... ...
美国版/Food Labeling Management App UniApp/src/utils/labelPreview/renderLabelPreviewCanvas.ts
1 1 import type { RawImageDataSource, SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
  2 +import { applyPrintOrientationCanvasTransform, normalizePrintOrientation } from '../print/printOrientation'
2 3 import { resolveMediaUrlForApp, storedValueLooksLikeImagePath } from '../resolveMediaUrl'
3 4 import { sortElementsForPreview } from './normalizePreviewTemplate'
4 5 import { resolveElementDateTimeDisplay } from './printInputOffset'
  6 +import { getLoggedInEmployeeDisplayName, isEmployeeTemplateElement } from './employeeElement'
5 7 import QRCode from 'qrcode'
6 8 import { readInvertColors } from '../invertColorsConfig'
7 9  
... ... @@ -127,6 +129,11 @@ function wrapTextToWidth(text: string, maxChars: number): string[] {
127 129 function previewTextForElement(element: SystemTemplateElementBase, baseTime: Date = new Date()): string {
128 130 const type = String(element.type || '').toUpperCase()
129 131 const config = element.config || {}
  132 + if (isEmployeeTemplateElement(element)) {
  133 + const cfgText = cfgStr(config, ['text', 'Text'], '').trim()
  134 + if (cfgText && cfgText.toLowerCase() !== 'text') return applyConfigPrefix(config, cfgText)
  135 + return applyConfigPrefix(config, getLoggedInEmployeeDisplayName())
  136 + }
130 137 if (type === 'DATE' || type === 'TIME' || type === 'DURATION') {
131 138 const live = resolveElementDateTimeDisplay(element, baseTime)
132 139 if (live != null && live.trim()) return live
... ... @@ -406,6 +413,7 @@ function runLabelPreviewCanvasDraw(
406 413 scale: number
407 414 ): Promise<void> {
408 415 const sorted = sortElementsForPreview(template.elements || [])
  416 + const printOrientation = normalizePrintOrientation(template.printOrientation)
409 417  
410 418 return new Promise((resolve) => {
411 419 const ctx = uni.createCanvasContext(canvasId, componentInstance)
... ... @@ -413,9 +421,16 @@ function runLabelPreviewCanvasDraw(
413 421 ctx.scale(scale, scale)
414 422 ctx.fillRect(0, 0, cw, ch)
415 423  
  424 + const rotated = printOrientation === 'horizontal'
  425 + if (rotated) {
  426 + ctx.save()
  427 + applyPrintOrientationCanvasTransform(ctx, cw, ch, printOrientation)
  428 + }
  429 +
416 430 const drawRest = (index: number) => {
417 431 if (index >= sorted.length) {
418 432 strokeTemplatePaperBorder(ctx, template, cw, ch)
  433 + if (rotated) ctx.restore()
419 434 ctx.draw(false, () => resolve())
420 435 return
421 436 }
... ... @@ -475,15 +490,12 @@ function runLabelPreviewCanvasDraw(
475 490 ...NUTRITION_FIXED_ITEMS.map((item) => {
476 491 const value = nutritionFixedField(config, item.key, 'value')
477 492 const unit = nutritionFixedField(config, item.key, 'unit')
478   - if (!value) return null
479 493 return { label: item.label, value: nutritionValueWithLessThan(value, unit) }
480   - }).filter(Boolean) as Array<{ label: string; value: string }>,
481   - ...nutritionExtraRows(config)
482   - .filter((r) => r.value)
483   - .map((r) => ({
484   - label: r.name || 'Other',
485   - value: nutritionValueWithLessThan(r.value, r.unit),
486   - })),
  494 + }),
  495 + ...nutritionExtraRows(config).map((r) => ({
  496 + label: r.name || 'Other',
  497 + value: nutritionValueWithLessThan(r.value, r.unit),
  498 + })),
487 499 ]
488 500  
489 501 const drawPair = (label: string, value: string, fs: number, bold = false): boolean => {
... ... @@ -526,8 +538,9 @@ function runLabelPreviewCanvasDraw(
526 538 }
527 539  
528 540 if (calories) drawPair('Calories', nutritionValueWithLessThan(calories, ''), Math.max(bodySize, 9), true)
529   - if (servingsPerContainer) drawPair('Servings Per Container', servingsPerContainer, bodySize)
530   - if (servingSize) drawPair('Serving Size', servingSize, bodySize)
  541 + else drawPair('Calories', '', Math.max(bodySize, 9), true)
  542 + drawPair('Servings Per Container', servingsPerContainer, bodySize)
  543 + drawPair('Serving Size', servingSize, bodySize)
531 544 for (const row of rows) {
532 545 if (!drawPair(row.label, row.value, bodySize, true)) break
533 546 }
... ...
美国版/Food Labeling Management App UniApp/src/utils/print/printOrientation.ts 0 → 100644
  1 +export type PrintOrientation = 'horizontal' | 'vertical'
  2 +
  3 +/** 与 Web normalizePrintOrientation 一致:默认竖打 */
  4 +export function normalizePrintOrientation(raw: unknown): PrintOrientation {
  5 + const v = String(raw ?? '').trim().toLowerCase()
  6 + return v === 'horizontal' ? 'horizontal' : 'vertical'
  7 +}
  8 +
  9 +/** 横打时内容相对纸张旋转 90°(纸张 W×H 不变) */
  10 +export function shouldRotatePrintContent(orientation: PrintOrientation): boolean {
  11 + return orientation === 'horizontal'
  12 +}
  13 +
  14 +/** 在 canvas 上应用模板级打印方向(与 Web printContentLayerStyle 一致) */
  15 +export function applyPrintOrientationCanvasTransform(
  16 + ctx: UniApp.CanvasContext,
  17 + cw: number,
  18 + ch: number,
  19 + orientation: PrintOrientation,
  20 +): void {
  21 + if (!shouldRotatePrintContent(orientation)) return
  22 + ctx.translate(cw / 2, ch / 2)
  23 + ctx.rotate(Math.PI / 2)
  24 + ctx.translate(-cw / 2, -ch / 2)
  25 +}
... ...
美国版/Food Labeling Management App UniApp/src/utils/print/types/printer.ts
... ... @@ -64,6 +64,7 @@ export type LabelTemplateData = Record&lt;string, LabelTemplateValue&gt;
64 64 export type PrinterTemplateUnit = 'inch' | 'mm' | 'cm' | 'px'
65 65 export type SystemTemplateRotation = 'horizontal' | 'vertical'
66 66 export type SystemTemplateTextAlign = 'left' | 'center' | 'right'
  67 +export type PrintOrientation = 'horizontal' | 'vertical'
67 68  
68 69 export interface SystemTemplateElementBase {
69 70 id: string
... ... @@ -93,6 +94,8 @@ export interface SystemLabelTemplate {
93 94 showGrid?: boolean
94 95 /** 整标签外框:none / line / dotted */
95 96 border?: string
  97 + /** 模板打印方向:horizontal=横打(内容旋转90°),vertical=竖打(默认) */
  98 + printOrientation?: PrintOrientation
96 99 elements: SystemTemplateElementBase[]
97 100 }
98 101  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/Label/LabelTemplatePreviewDto.cs
... ... @@ -40,6 +40,10 @@ public class LabelTemplatePreviewDto
40 40 [JsonPropertyName("border")]
41 41 public string Border { get; set; } = "none";
42 42  
  43 + /// <summary>打印方向:vertical / horizontal</summary>
  44 + [JsonPropertyName("printOrientation")]
  45 + public string PrintOrientation { get; set; } = "vertical";
  46 +
43 47 [JsonPropertyName("elements")]
44 48 public List<LabelTemplateElementDto> Elements { get; set; } = new();
45 49 }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/LabelTemplate/LabelTemplateCreateInputVo.cs
... ... @@ -60,6 +60,10 @@ public class LabelTemplateCreateInputVo
60 60 [JsonPropertyName("border")]
61 61 public string BorderType { get; set; } = "none";
62 62  
  63 + /// <summary>打印方向:vertical / horizontal</summary>
  64 + [JsonPropertyName("printOrientation")]
  65 + public string PrintOrientationType { get; set; } = "vertical";
  66 +
63 67 /// <summary>
64 68 /// 预留:前端可能不传;如果不传则默认 true
65 69 /// </summary>
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/LabelTemplate/LabelTemplateGetOutputDto.cs
... ... @@ -34,6 +34,10 @@ public class LabelTemplateGetOutputDto
34 34 [JsonPropertyName("border")]
35 35 public string BorderType { get; set; } = "none";
36 36  
  37 + /// <summary>打印方向:vertical / horizontal</summary>
  38 + [JsonPropertyName("printOrientation")]
  39 + public string PrintOrientationType { get; set; } = "vertical";
  40 +
37 41 public int VersionNo { get; set; }
38 42  
39 43 public bool State { get; set; }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/FlLabelTemplateDbEntity.cs
... ... @@ -47,6 +47,9 @@ public class FlLabelTemplateDbEntity
47 47 /// <summary>整标签外框:none / line / dotted</summary>
48 48 public string BorderType { get; set; } = "none";
49 49  
  50 + /// <summary>打印方向:vertical=竖打(默认),horizontal=横打(内容旋转90°,纸张尺寸不变)</summary>
  51 + public string PrintOrientationType { get; set; } = "vertical";
  52 +
50 53 public int VersionNo { get; set; }
51 54  
52 55 public bool State { get; set; }
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelAppService.cs
... ... @@ -894,9 +894,22 @@ public class LabelAppService : ApplicationService, ILabelAppService
894 894 ShowRuler = template.ShowRuler,
895 895 ShowGrid = template.ShowGrid,
896 896 Border = NormalizeTemplateBorderType(template.BorderType),
  897 + PrintOrientation = NormalizePrintOrientationType(template.PrintOrientationType),
897 898 Elements = resolvedElements
898 899 };
899 900 }
900 901  
  902 + private static string NormalizeTemplateBorderType(string? raw)
  903 + {
  904 + var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
  905 + return v is "line" or "dotted" ? v : "none";
  906 + }
  907 +
  908 + private static string NormalizePrintOrientationType(string? raw)
  909 + {
  910 + var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
  911 + return v == "horizontal" ? "horizontal" : "vertical";
  912 + }
  913 +
901 914 }
902 915  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTemplateAppService.cs
... ... @@ -185,6 +185,7 @@ public class LabelTemplateAppService : ApplicationService, ILabelTemplateAppServ
185 185 ShowRuler = template.ShowRuler,
186 186 ShowGrid = template.ShowGrid,
187 187 BorderType = NormalizeTemplateBorderType(template.BorderType),
  188 + PrintOrientationType = NormalizePrintOrientationType(template.PrintOrientationType),
188 189 VersionNo = template.VersionNo,
189 190 State = template.State,
190 191 Elements = MapElements(),
... ... @@ -241,6 +242,7 @@ public class LabelTemplateAppService : ApplicationService, ILabelTemplateAppServ
241 242 ShowRuler = input.ShowRuler,
242 243 ShowGrid = input.ShowGrid,
243 244 BorderType = NormalizeTemplateBorderType(input.BorderType),
  245 + PrintOrientationType = NormalizePrintOrientationType(input.PrintOrientationType),
244 246 VersionNo = 1,
245 247 State = input.State
246 248 };
... ... @@ -298,6 +300,7 @@ public class LabelTemplateAppService : ApplicationService, ILabelTemplateAppServ
298 300 template.ShowRuler = input.ShowRuler;
299 301 template.ShowGrid = input.ShowGrid;
300 302 template.BorderType = NormalizeTemplateBorderType(input.BorderType);
  303 + template.PrintOrientationType = NormalizePrintOrientationType(input.PrintOrientationType);
301 304 template.State = input.State;
302 305 template.VersionNo = template.VersionNo + 1;
303 306 template.LastModifierId = CurrentUser?.Id?.ToString();
... ... @@ -536,5 +539,11 @@ public class LabelTemplateAppService : ApplicationService, ILabelTemplateAppServ
536 539 var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
537 540 return v is "line" or "dotted" ? v : "none";
538 541 }
  542 +
  543 + private static string NormalizePrintOrientationType(string? raw)
  544 + {
  545 + var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
  546 + return v == "horizontal" ? "horizontal" : "vertical";
  547 + }
539 548 }
540 549  
... ...
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/scripts/fl_label_template_print_orientation.sql 0 → 100644
  1 +-- fl_label_template 增加打印方向字段(vertical=竖打默认,horizontal=横打内容旋转90°)
  2 +SET @db = DATABASE();
  3 +
  4 +SET @sql = IF(
  5 + (SELECT COUNT(*) FROM information_schema.COLUMNS
  6 + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'fl_label_template' AND COLUMN_NAME = 'PrintOrientationType') = 0,
  7 + 'ALTER TABLE `fl_label_template` ADD COLUMN `PrintOrientationType` varchar(20) NOT NULL DEFAULT ''vertical'' COMMENT ''打印方向:vertical/horizontal'' AFTER `BorderType`',
  8 + 'SELECT ''PrintOrientationType already exists'' AS msg'
  9 +);
  10 +PREPARE stmt FROM @sql;
  11 +EXECUTE stmt;
  12 +DEALLOCATE PREPARE stmt;
... ...
美国版/Food Labeling Management Platform/.env.local
1   -# VITE_API_BASE_URL=http://192.168.31.87:19001
2   -VITE_API_BASE_URL=http://flus-test.3ffoodsafety.com
  1 +VITE_API_BASE_URL=http://192.168.31.88:19001
  2 +# VITE_API_BASE_URL=http://flus-test.3ffoodsafety.com
... ...
美国版/Food Labeling Management Platform/build/assets/index-CydGaE-m.js 0 → 100644
No preview for this file type
美国版/Food Labeling Management Platform/build/assets/index-I9iAS7du.js deleted
No preview for this file type
美国版/Food Labeling Management Platform/build/index.html
... ... @@ -5,7 +5,7 @@
5 5 <meta charset="UTF-8" />
6 6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 7 <title>Food Labeling Management Platform</title>
8   - <script type="module" crossorigin src="/assets/index-I9iAS7du.js"></script>
  8 + <script type="module" crossorigin src="/assets/index-CydGaE-m.js"></script>
9 9 <link rel="stylesheet" crossorigin href="/assets/index-BFajuDEY.css">
10 10 </head>
11 11  
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelCategoriesView.tsx
... ... @@ -74,7 +74,8 @@ import {
74 74 } from "../../lib/categoryScopeForm";
75 75 import { CategoryScopeFields } from "../shared/category-scope-fields";
76 76 import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
77   -import { resolvePictureUrlForDisplay } from "../../services/imageUploadService";
  77 +import { CategoryButtonAppearancePreview } from "../ui/category-button-appearance-preview";
  78 +import { CategoryButtonVisualThumb } from "../ui/category-button-visual-thumb";
78 79 import type { LabelCategoryDto, LabelCategoryCreateInput, LabelCategoryUpdateInput } from "../../types/labelCategory";
79 80 import {
80 81 FORM_DIALOG_CONTENT_CLASS,
... ... @@ -231,59 +232,10 @@ function renderCategoryPhotoCell(item: LabelCategoryDto) {
231 232 categoryPhotoUrl: item.categoryPhotoUrl,
232 233 categoryName: item.categoryName,
233 234 });
234   -
235   - if (visual.mode === "image") {
236   - const url = visual.imageUrl ? resolvePictureUrlForDisplay(visual.imageUrl) : "";
237   - return url ? (
238   - <div className="w-10 h-10 rounded-[12px] border border-gray-200 overflow-hidden shadow-sm bg-gray-50">
239   - <img src={url} alt="" className="w-full h-full object-cover" />
240   - </div>
241   - ) : (
242   - <span className="text-sm font-normal text-gray-900">—</span>
243   - );
244   - }
245   -
246   - if (visual.mode === "colorText") {
247   - return (
248   - <div
249   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm flex items-center justify-center px-1 overflow-hidden"
250   - style={{
251   - backgroundColor: visual.bg,
252   - color: visual.textColor || "#ffffff",
253   - }}
254   - title={`${visual.text}`}
255   - >
256   - <span className="text-xs font-normal leading-tight text-center line-clamp-2 break-all">
257   - {visual.text}
258   - </span>
259   - </div>
260   - );
261   - }
262   -
263   - if (visual.mode === "color") {
264   - return (
265   - <div
266   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm"
267   - style={{ backgroundColor: visual.bg }}
268   - title={visual.bg}
269   - />
270   - );
271   - }
272   -
273   - if (visual.mode === "text") {
274   - return (
275   - <div
276   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm bg-gray-50 flex items-center justify-center px-1 overflow-hidden"
277   - title={visual.text}
278   - >
279   - <span className="text-xs font-normal text-gray-800 text-center line-clamp-2 break-all">
280   - {visual.text}
281   - </span>
282   - </div>
283   - );
  235 + if (visual.mode === "none") {
  236 + return <span className="text-sm font-normal text-gray-900">—</span>;
284 237 }
285   -
286   - return <span className="text-sm font-normal text-gray-900">—</span>;
  238 + return <CategoryButtonVisualThumb visual={visual} size="md" />;
287 239 }
288 240  
289 241 export function LabelCategoriesView() {
... ... @@ -627,11 +579,22 @@ export function LabelCategoriesView() {
627 579  
628 580 <div className="flex-1 overflow-auto pt-6">
629 581 <div className="rounded-md border bg-white shadow-sm">
630   - <Table>
  582 + <Table className="table-fixed">
  583 + <colgroup>
  584 + <col className="w-[16%]" />
  585 + <col className="w-16" />
  586 + <col className="w-[14%]" />
  587 + <col className="w-[20%]" />
  588 + <col className="w-24" />
  589 + <col className="w-28" />
  590 + <col className="w-24" />
  591 + <col className="w-[14%]" />
  592 + <col className="w-24" />
  593 + </colgroup>
631 594 <TableHeader>
632 595 <TableRow className="bg-gray-50 hover:bg-gray-50">
633 596 <TableHead className="text-sm font-semibold text-gray-900 min-w-[160px]">Label Category</TableHead>
634   - <TableHead className="text-sm font-semibold text-gray-900 w-[120px]">Display</TableHead>
  597 + <TableHead className="text-sm font-semibold text-gray-900 w-16 max-w-16">Display</TableHead>
635 598 <TableHead className="text-sm font-semibold text-gray-900 min-w-[140px]">Region</TableHead>
636 599 <TableHead className="text-sm font-semibold text-gray-900 min-w-[200px]">Location</TableHead>
637 600 <TableHead className="text-sm font-semibold text-gray-900 w-[110px]">Status</TableHead>
... ... @@ -663,7 +626,9 @@ export function LabelCategoriesView() {
663 626 <TableCell className="text-sm font-normal text-gray-900 whitespace-nowrap">
664 627 {toDisplay(item.categoryName)}
665 628 </TableCell>
666   - <TableCell>{renderCategoryPhotoCell(item)}</TableCell>
  629 + <TableCell className="!whitespace-normal align-middle w-16 max-w-16 p-2">
  630 + {renderCategoryPhotoCell(item)}
  631 + </TableCell>
667 632 <TableCell
668 633 className="text-sm font-normal text-gray-900 whitespace-nowrap max-w-[180px] truncate"
669 634 title={regionText}
... ... @@ -968,6 +933,7 @@ function CreateLabelCategoryDialog({
968 933 const locPayload = buildSpecifiedLocationPayload(
969 934 locations,
970 935 partners,
  936 + groups,
971 937 scopePartnerId,
972 938 selectedRegionNames,
973 939 selectedLocationIds,
... ... @@ -1196,6 +1162,14 @@ function CreateLabelCategoryDialog({
1196 1162 </div>
1197 1163 ) : null}
1198 1164  
  1165 + <CategoryButtonAppearancePreview
  1166 + apSel={apSel}
  1167 + displayText={displayTextForPhoto}
  1168 + buttonBgColor={buttonBgColor}
  1169 + imageUrl={apSel.image ? String(form.categoryPhotoUrl ?? "").trim() : ""}
  1170 + fallbackName={form.categoryName.trim() || displayTextForPhoto.trim()}
  1171 + />
  1172 +
1199 1173 <div className="space-y-2">
1200 1174 <Label>Order *</Label>
1201 1175 <Input
... ... @@ -1430,6 +1404,7 @@ function EditLabelCategoryDialog({
1430 1404 const locPayload = buildSpecifiedLocationPayload(
1431 1405 locations,
1432 1406 partners,
  1407 + groups,
1433 1408 scopePartnerId,
1434 1409 selectedRegionNames,
1435 1410 selectedLocationIds,
... ... @@ -1658,6 +1633,14 @@ function EditLabelCategoryDialog({
1658 1633 </div>
1659 1634 ) : null}
1660 1635  
  1636 + <CategoryButtonAppearancePreview
  1637 + apSel={apSel}
  1638 + displayText={displayTextForPhoto}
  1639 + buttonBgColor={buttonBgColor}
  1640 + imageUrl={apSel.image ? String(form.categoryPhotoUrl ?? "").trim() : ""}
  1641 + fallbackName={form.categoryName.trim() || displayTextForPhoto.trim()}
  1642 + />
  1643 +
1661 1644 <div className="space-y-2">
1662 1645 <Label>Order *</Label>
1663 1646 <Input
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateDataEntryView.tsx
... ... @@ -51,6 +51,7 @@ import type { ProductDto } from &#39;../../types/product&#39;;
51 51 import type { LabelTypeDto } from '../../types/labelType';
52 52 import {
53 53 buildTemplateBarcodeQrDefaultsFromCodeValue,
  54 + buildTemplateLabelBindingDefaults,
54 55 isTemplateSectionBarcodeOrQrElement,
55 56 } from '../../lib/productCodeValueTemplate';
56 57  
... ... @@ -103,12 +104,12 @@ function DataEntryOffsetCell({
103 104 }) {
104 105 const { unit, value: num } = offsetFieldUiStateFromStored(value);
105 106 return (
106   - <div className="flex flex-wrap items-center gap-2 min-w-0 max-w-[220px]">
  107 + <div className="flex items-center gap-1.5 min-w-0 max-w-[168px]">
107 108 <Select
108 109 value={unit}
109 110 onValueChange={(u) => onValueChange(serializePrintInputOffset(u, num))}
110 111 >
111   - <SelectTrigger className="h-10 min-w-0 flex-1 bg-white text-sm border-gray-300">
  112 + <SelectTrigger className="h-9 w-[118px] shrink-0 bg-white text-xs border-gray-300 px-2 [&>span]:line-clamp-1">
112 113 <SelectValue />
113 114 </SelectTrigger>
114 115 <SelectContent>
... ... @@ -121,7 +122,7 @@ function DataEntryOffsetCell({
121 122 </Select>
122 123 <Input
123 124 type="number"
124   - className="h-10 w-20 shrink-0 border-gray-300 bg-white"
  125 + className="h-9 w-14 shrink-0 border-gray-300 bg-white px-2 text-sm"
125 126 value={num}
126 127 onChange={(e) => onValueChange(serializePrintInputOffset(unit, e.target.value))}
127 128 placeholder="Val"
... ... @@ -158,9 +159,7 @@ function DataEntryValueCell({
158 159 value={value}
159 160 onChange={onValueChange}
160 161 uploadSubDir="label-template-data"
161   - oneImageOnly
162 162 boxClassName={DATA_ENTRY_IMAGE_BOX}
163   - hint="Upload stores full URL/path for save."
164 163 />
165 164 );
166 165 }
... ... @@ -325,10 +324,8 @@ export function LabelTemplateDataEntryView({
325 324 const pid = productId.trim();
326 325 const product = products.find((p) => p.id === pid);
327 326 const cv = (product?.codeValue ?? '').trim();
328   - const scanDefaults = buildTemplateBarcodeQrDefaultsFromCodeValue(
329   - (templateDto?.elements ?? []) as LabelElement[],
330   - cv,
331   - );
  327 + const elements = (templateDto?.elements ?? []) as LabelElement[];
  328 + const scanDefaults = buildTemplateBarcodeQrDefaultsFromCodeValue(elements, cv);
332 329 setRows((prev) =>
333 330 prev.map((r) => {
334 331 if (r.id !== rowId) return r;
... ... @@ -343,6 +340,29 @@ export function LabelTemplateDataEntryView({
343 340 [products, templateDto],
344 341 );
345 342  
  343 + const applyLabelTypeToRow = useCallback(
  344 + (rowId: string, labelTypeId: string) => {
  345 + const ltid = labelTypeId.trim();
  346 + const labelType = types.find((t) => t.id === ltid);
  347 + const labelTypeName = (labelType?.typeName ?? labelType?.typeCode ?? '').trim();
  348 + const labelDefaults = buildTemplateLabelBindingDefaults(
  349 + (templateDto?.elements ?? []) as LabelElement[],
  350 + { labelTypeName },
  351 + );
  352 + setRows((prev) =>
  353 + prev.map((r) => {
  354 + if (r.id !== rowId) return r;
  355 + return {
  356 + ...r,
  357 + labelTypeId: ltid,
  358 + fieldValues: { ...r.fieldValues, ...labelDefaults },
  359 + };
  360 + }),
  361 + );
  362 + },
  363 + [types, templateDto],
  364 + );
  365 +
346 366 const setFieldValue = useCallback(
347 367 (rowId: string, elementId: string, value: string) => {
348 368 setRows((prev) =>
... ... @@ -394,10 +414,17 @@ export function LabelTemplateDataEntryView({
394 414 }
395 415 }
396 416 const product = products.find((p) => p.id === r.productId.trim());
  417 + const labelType = types.find((t) => t.id === r.labelTypeId.trim());
397 418 Object.assign(
398 419 defaultValues,
399 420 buildTemplateBarcodeQrDefaultsFromCodeValue(fullElements, product?.codeValue),
400 421 );
  422 + Object.assign(
  423 + defaultValues,
  424 + buildTemplateLabelBindingDefaults(fullElements, {
  425 + labelTypeName: labelType?.typeName ?? labelType?.typeCode,
  426 + }),
  427 + );
401 428 return {
402 429 productId: r.productId.trim(),
403 430 labelTypeId: r.labelTypeId.trim(),
... ... @@ -542,7 +569,7 @@ export function LabelTemplateDataEntryView({
542 569 <TableCell className="align-top py-2">
543 570 <SearchableSelect
544 571 value={row.labelTypeId}
545   - onValueChange={(v) => updateRow(row.id, { labelTypeId: v })}
  572 + onValueChange={(v) => applyLabelTypeToRow(row.id, v)}
546 573 options={labelTypeOptions}
547 574 placeholder="Select label type"
548 575 searchPlaceholder="Search type…"
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/LabelCanvas.tsx
... ... @@ -48,14 +48,14 @@ export function printContentLayerStyle(
48 48 baseW: number,
49 49 baseH: number,
50 50 ): React.CSSProperties {
51   - if (orientation !== 'vertical') return {};
  51 + if (orientation !== 'horizontal') return {};
52 52 return {
53 53 transform: 'rotate(90deg)',
54 54 transformOrigin: `${baseW / 2}px ${baseH / 2}px`,
55 55 };
56 56 }
57 57  
58   -/** 竖打 preview 层 rotate(90deg) 的逆变换:画布本地坐标 → 模板坐标 */
  58 +/** 横打 preview 层 rotate(90deg) 的逆变换:画布本地坐标 → 模板坐标 */
59 59 export function canvasLocalToTemplateSpace(
60 60 localX: number,
61 61 localY: number,
... ... @@ -63,7 +63,7 @@ export function canvasLocalToTemplateSpace(
63 63 baseW: number,
64 64 baseH: number,
65 65 ): { x: number; y: number } {
66   - if (orientation !== 'vertical') {
  66 + if (orientation !== 'horizontal') {
67 67 return { x: localX, y: localY };
68 68 }
69 69 const cx = baseW / 2;
... ... @@ -89,17 +89,17 @@ export function clientToCanvasLocalPoint(
89 89 };
90 90 }
91 91  
92   -/** 竖打时将画布位移增量映射到模板坐标增量 */
  92 +/** 横打时将画布位移增量映射到模板坐标增量 */
93 93 export function mapPointerDeltaToTemplateSpace(
94 94 dx: number,
95 95 dy: number,
96 96 orientation: PrintOrientation,
97 97 ): { dx: number; dy: number } {
98   - if (orientation !== 'vertical') return { dx, dy };
  98 + if (orientation !== 'horizontal') return { dx, dy };
99 99 return { dx: dy, dy: -dx };
100 100 }
101 101  
102   -/** 根据指针位置与抓取偏移计算模板坐标(竖打跟随视觉方向) */
  102 +/** 根据指针位置与抓取偏移计算模板坐标(横打跟随视觉方向) */
103 103 export function templatePositionFromPointerGrab(
104 104 localX: number,
105 105 localY: number,
... ... @@ -118,14 +118,14 @@ export function templatePositionFromPointerGrab(
118 118  
119 119 const ELEMENT_DRAG_THRESHOLD_PX = 4;
120 120  
121   -/** 竖打预览 rotate(90deg) 时,屏幕拖拽增量映射到模板宽/高增量 */
  121 +/** 横打预览 rotate(90deg) 时,屏幕拖拽增量映射到模板宽/高增量 */
122 122 export function elementResizeDeltaFromPointer(
123 123 dlx: number,
124 124 dly: number,
125 125 handleId: string,
126 126 orientation: PrintOrientation,
127 127 ): { dw: number; dh: number } {
128   - if (orientation === 'vertical') {
  128 + if (orientation === 'horizontal') {
129 129 let dw = 0;
130 130 let dh = 0;
131 131 if (handleId.includes('e')) dw += dly;
... ... @@ -143,6 +143,24 @@ export function elementResizeDeltaFromPointer(
143 143 return { dw, dh };
144 144 }
145 145  
  146 +/** 将画布本地坐标系中的指针位移转为模板坐标系增量(横打已含 rotate 逆变换) */
  147 +export function templatePointerDeltaFromCanvasLocals(
  148 + startLocalX: number,
  149 + startLocalY: number,
  150 + currentLocalX: number,
  151 + currentLocalY: number,
  152 + orientation: PrintOrientation,
  153 + baseW: number,
  154 + baseH: number,
  155 +): { dtx: number; dty: number } {
  156 + const start = canvasLocalToTemplateSpace(startLocalX, startLocalY, orientation, baseW, baseH);
  157 + const current = canvasLocalToTemplateSpace(currentLocalX, currentLocalY, orientation, baseW, baseH);
  158 + return {
  159 + dtx: current.x - start.x,
  160 + dty: current.y - start.y,
  161 + };
  162 +}
  163 +
146 164 export function computeResizedElementBox(
147 165 elX: number,
148 166 elY: number,
... ... @@ -332,9 +350,9 @@ export function clampLabelElementBox(
332 350 baseW: number,
333 351 baseH: number,
334 352 marginPx: number = LABEL_CANVAS_SAFE_MARGIN_PX,
335   - orientation: PrintOrientation = 'horizontal',
  353 + orientation: PrintOrientation = 'vertical',
336 354 ): { x: number; y: number; w: number; h: number } {
337   - if (orientation === 'vertical') {
  355 + if (orientation === 'horizontal') {
338 356 const cx = baseW / 2;
339 357 const cy = baseH / 2;
340 358 const minX = cx - cy + marginPx;
... ... @@ -397,9 +415,9 @@ function clampDragPosition(
397 415 baseW: number,
398 416 baseH: number,
399 417 marginPx: number,
400   - orientation: PrintOrientation = 'horizontal',
  418 + orientation: PrintOrientation = 'vertical',
401 419 ): { x: number; y: number } {
402   - if (orientation === 'vertical') {
  420 + if (orientation === 'horizontal') {
403 421 const cx = baseW / 2;
404 422 const cy = baseH / 2;
405 423 const minX = cx - cy + marginPx;
... ... @@ -542,7 +560,7 @@ function ElementSelectionFrame({
542 560 paperWidthTemplate,
543 561 paperHeightTemplate,
544 562 displayUnit,
545   - printOrientation = 'horizontal',
  563 + printOrientation = 'vertical',
546 564 interactive = false,
547 565 onResizePointerDown,
548 566 }: {
... ... @@ -583,10 +601,10 @@ function ElementSelectionFrame({
583 601 const heightOnLeft = x >= 36;
584 602 const heightLineX = heightOnLeft ? x - 12 : x + w + 12;
585 603 const heightTextX = heightOnLeft ? heightLineX - 8 : heightLineX + 8;
586   - // 竖打预览旋转后,屏幕上的横/竖跨度与模板宽/高对调,标注跟随视觉
587   - const isPortraitPrint = printOrientation === 'vertical';
588   - const displayWidthLabel = isPortraitPrint ? hValue : wValue;
589   - const displayHeightLabel = isPortraitPrint ? wValue : hValue;
  604 + // 横打预览旋转后,屏幕上的横/竖跨度与模板宽/高对调,标注跟随视觉
  605 + const isRotatedPrintPreview = printOrientation === 'horizontal';
  606 + const displayWidthLabel = isRotatedPrintPreview ? hValue : wValue;
  607 + const displayHeightLabel = isRotatedPrintPreview ? wValue : hValue;
590 608  
591 609 return (
592 610 <>
... ... @@ -1471,8 +1489,8 @@ function ElementContent({
1471 1489 </div>
1472 1490 );
1473 1491 }
1474   - const format = 'HH:mm';
1475   - const example = format.replace('HH', '12').replace('mm', '30');
  1492 + const d = new Date();
  1493 + const example = formatDateByPreset('HH:mm', d);
1476 1494 return (
1477 1495 <div className="w-full h-full flex items-center justify-center overflow-hidden">
1478 1496 <div className="px-1 overflow-hidden whitespace-nowrap" style={{ ...commonStyle, ...rotateBoxStyle }}>
... ... @@ -1561,23 +1579,20 @@ function ElementContent({
1561 1579 const nutritionTitleSize = Number(cfg.nutritionTitleFontSize ?? cfg.NutritionTitleFontSize ?? 16) || 16;
1562 1580 const baseRows = NUTRITION_FIXED_ITEMS.map((item) => {
1563 1581 const value = nutritionFixedField(cfg, item.key, 'value');
1564   - const unit = nutritionFixedField(cfg, item.key, 'unit');
1565   - if (!value) return null;
  1582 + const unit = nutritionFixedField(cfg, item.key, 'unit') || (item.defaultUnit ?? '');
1566 1583 return {
1567 1584 id: item.key,
1568 1585 label: item.label,
1569 1586 value,
1570 1587 unit,
1571 1588 };
1572   - }).filter(Boolean) as Array<{ id: string; label: string; value: string; unit: string }>;
1573   - const extraRows = nutritionExtraRows(cfg)
1574   - .filter((item) => item.value.trim())
1575   - .map((item) => ({
1576   - id: item.id,
1577   - label: item.name.trim() || 'Other',
1578   - value: item.value.trim(),
1579   - unit: item.unit.trim(),
1580   - }));
  1589 + });
  1590 + const extraRows = nutritionExtraRows(cfg).map((item) => ({
  1591 + id: item.id,
  1592 + label: item.name.trim() || 'Other',
  1593 + value: item.value.trim(),
  1594 + unit: item.unit.trim(),
  1595 + }));
1581 1596 const rows = [...baseRows, ...extraRows];
1582 1597 const formatNutritionValue = (value: string, unit: string): string => {
1583 1598 const v = String(value ?? '').trim();
... ... @@ -1593,37 +1608,29 @@ function ElementContent({
1593 1608 <div className="font-bold border-b border-black pb-0.5" style={{ fontSize: `${nutritionTitleSize}px` }}>
1594 1609 Nutrition Facts
1595 1610 </div>
1596   - {calories ? (
1597   - <div className="flex items-center justify-between py-0.5 mt-0.5">
1598   - <span className="font-semibold text-[10px]">Calories</span>
1599   - <span className="font-semibold text-[10px]">{formatNutritionValue(calories, '')}</span>
1600   - </div>
1601   - ) : null}
1602   - {servingsPerContainer ? (
1603   - <div className="flex items-center justify-between py-0.5 text-[10px]">
1604   - <span>Servings Per Container</span>
1605   - <span>{servingsPerContainer}</span>
1606   - </div>
1607   - ) : null}
1608   - {servingSize ? (
1609   - <div className="flex items-center justify-between pb-0.5 text-[10px]">
1610   - <span>Serving Size</span>
1611   - <span>{servingSize}</span>
1612   - </div>
1613   - ) : null}
  1611 + <div className="flex items-center justify-between py-0.5 mt-0.5 border-b border-black">
  1612 + <span className="font-semibold text-[10px]">Calories</span>
  1613 + <span className="font-semibold text-[10px]">
  1614 + {calories ? formatNutritionValue(calories, '') : ''}
  1615 + </span>
  1616 + </div>
  1617 + <div className="flex items-center justify-between py-0.5 text-[10px]">
  1618 + <span>Servings Per Container</span>
  1619 + <span>{servingsPerContainer}</span>
  1620 + </div>
  1621 + <div className="flex items-center justify-between pb-0.5 text-[10px] border-b border-black">
  1622 + <span>Serving Size</span>
  1623 + <span>{servingSize}</span>
  1624 + </div>
1614 1625 <div className="flex-1 min-h-0 overflow-hidden pt-0.5">
1615   - {rows.length === 0 ? (
1616   - <div className="text-[7px] text-gray-500">No nutrients</div>
1617   - ) : (
1618   - rows.slice(0, 18).map((row) => (
1619   - <div key={row.id} className="flex items-center justify-between py-[1px] text-[10px]">
1620   - <span className="truncate font-medium">{row.label}</span>
1621   - <span className="shrink-0 font-medium">
1622   - {formatNutritionValue(row.value, row.unit)}
1623   - </span>
1624   - </div>
1625   - ))
1626   - )}
  1626 + {rows.map((row) => (
  1627 + <div key={row.id} className="flex items-center justify-between py-[1px] text-[10px]">
  1628 + <span className="truncate font-medium">{row.label}</span>
  1629 + <span className="shrink-0 font-medium">
  1630 + {formatNutritionValue(row.value, row.unit)}
  1631 + </span>
  1632 + </div>
  1633 + ))}
1627 1634 </div>
1628 1635 </div>
1629 1636 );
... ... @@ -1731,7 +1738,7 @@ export function LabelCanvas({
1731 1738 onPreviewRulerUnitChange,
1732 1739 liveElementPatch = null,
1733 1740 onLiveElementPatchChange,
1734   - printOrientation = 'horizontal',
  1741 + printOrientation = 'vertical',
1735 1742 onPrintOrientationChange,
1736 1743 }: LabelCanvasProps) {
1737 1744 const scrollContainerRef = useRef<HTMLDivElement>(null);
... ... @@ -1805,7 +1812,7 @@ export function LabelCanvas({
1805 1812 const widthPx = baseW * scale;
1806 1813 const heightPx = baseH * scale;
1807 1814 const showGrid = template.showGrid !== false;
1808   - const isPortraitPrint = printOrientation === 'vertical';
  1815 + const isRotatedPrintPreview = printOrientation === 'horizontal';
1809 1816 const effectiveCanvasBorder = canvasBorder ?? template.border ?? 'none';
1810 1817 const canvasBorderClass =
1811 1818 effectiveCanvasBorder === 'line'
... ... @@ -1974,9 +1981,16 @@ export function LabelCanvas({
1974 1981 if (!local) return;
1975 1982  
1976 1983 const { id, corner, startLocalX, startLocalY, w, h, elX, elY } = session;
1977   - const dlx = local.x - startLocalX;
1978   - const dly = local.y - startLocalY;
1979   - const resized = computeResizedElementBox(elX, elY, w, h, corner, dlx, dly, printOrientation);
  1984 + const { dtx, dty } = templatePointerDeltaFromCanvasLocals(
  1985 + startLocalX,
  1986 + startLocalY,
  1987 + local.x,
  1988 + local.y,
  1989 + printOrientation,
  1990 + baseW,
  1991 + baseH,
  1992 + );
  1993 + const resized = computeResizedElementBox(elX, elY, w, h, corner, dtx, dty, 'horizontal');
1980 1994 const clamped = clampLabelElementBox(
1981 1995 snapToGrid(resized.x),
1982 1996 snapToGrid(resized.y),
... ... @@ -2065,6 +2079,7 @@ export function LabelCanvas({
2065 2079 document.addEventListener('pointermove', onMove);
2066 2080 document.addEventListener('pointerup', onUp);
2067 2081 document.addEventListener('pointercancel', onUp);
  2082 + (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
2068 2083 },
2069 2084 [
2070 2085 template.elements,
... ... @@ -2159,9 +2174,16 @@ export function LabelCanvas({
2159 2174 if (!local) return;
2160 2175  
2161 2176 requestUpdate(() => {
2162   - const dlx = local.x - startLocalX;
2163   - const dly = local.y - startLocalY;
2164   - const resized = computeResizedElementBox(elX, elY, w, h, corner, dlx, dly, printOrientation);
  2177 + const { dtx, dty } = templatePointerDeltaFromCanvasLocals(
  2178 + startLocalX,
  2179 + startLocalY,
  2180 + local.x,
  2181 + local.y,
  2182 + printOrientation,
  2183 + baseW,
  2184 + baseH,
  2185 + );
  2186 + const resized = computeResizedElementBox(elX, elY, w, h, corner, dtx, dty, 'horizontal');
2165 2187 const clamped = clampLabelElementBox(
2166 2188 snapToGrid(resized.x),
2167 2189 snapToGrid(resized.y),
... ... @@ -2665,7 +2687,8 @@ export function LabelCanvas({
2665 2687 ref={canvasRef}
2666 2688 tabIndex={0}
2667 2689 className={cn(
2668   - 'absolute left-0 top-0 bg-white shadow-lg outline-none overflow-hidden',
  2690 + 'absolute left-0 top-0 shadow-lg outline-none',
  2691 + isRotatedPrintPreview ? 'overflow-visible' : 'overflow-hidden',
2669 2692 canvasBorderClass,
2670 2693 isPanning ? 'cursor-grabbing' : 'cursor-grab'
2671 2694 )}
... ... @@ -2676,11 +2699,6 @@ export function LabelCanvas({
2676 2699 transformOrigin: 'top left',
2677 2700 pointerEvents: isSpacePressed ? 'none' : 'auto',
2678 2701 cursor: paperResizeCursor ?? undefined,
2679   - backgroundImage: showGrid
2680   - ? `linear-gradient(to right, rgba(0,0,0,0.06) 1px, transparent 1px),
2681   - linear-gradient(to bottom, rgba(0,0,0,0.06) 1px, transparent 1px)`
2682   - : undefined,
2683   - backgroundSize: showGrid ? `${GRID_SIZE}px ${GRID_SIZE}px` : undefined,
2684 2702 }}
2685 2703 onClick={(e) => {
2686 2704 if (suppressCanvasClickDeselectRef.current) {
... ... @@ -2736,9 +2754,20 @@ export function LabelCanvas({
2736 2754 onPointerUp={handlePointerUp}
2737 2755 onKeyDown={handleKeyDown}
2738 2756 >
  2757 + <div
  2758 + className="pointer-events-none absolute inset-0 overflow-hidden bg-white"
  2759 + style={{
  2760 + backgroundImage: showGrid
  2761 + ? `linear-gradient(to right, rgba(0,0,0,0.06) 1px, transparent 1px),
  2762 + linear-gradient(to bottom, rgba(0,0,0,0.06) 1px, transparent 1px)`
  2763 + : undefined,
  2764 + backgroundSize: showGrid ? `${GRID_SIZE}px ${GRID_SIZE}px` : undefined,
  2765 + }}
  2766 + aria-hidden
  2767 + />
2739 2768 <CanvasSafeMarginOverlay baseW={baseW} baseH={baseH} />
2740 2769 <div
2741   - className="absolute left-0 top-0"
  2770 + className="absolute left-0 top-0 overflow-visible"
2742 2771 style={{
2743 2772 width: baseW,
2744 2773 height: baseH,
... ... @@ -2850,7 +2879,7 @@ export function LabelPreviewOnly({
2850 2879 previewAsPrinted = false,
2851 2880 highlightElementId = null,
2852 2881 previewRulerUnit = "cm",
2853   - printOrientation = "horizontal",
  2882 + printOrientation = "vertical",
2854 2883 }: {
2855 2884 template: LabelTemplate;
2856 2885 canvasBorder?: 'none' | 'line' | 'dotted';
... ... @@ -2861,11 +2890,11 @@ export function LabelPreviewOnly({
2861 2890 highlightElementId?: string | null;
2862 2891 /** 选中框尺寸读数单位(与编辑器预览标尺一致) */
2863 2892 previewRulerUnit?: PreviewRulerDisplayUnit;
2864   - /** 竖打时内容整体旋转 90°,纸张尺寸不变;未传时读 template.printOrientation */
  2893 + /** 横打时内容整体旋转 90°,纸张尺寸不变;未传时读 template.printOrientation */
2865 2894 printOrientation?: PrintOrientation;
2866 2895 }) {
2867 2896 const effectivePrintOrientation =
2868   - printOrientation ?? template.printOrientation ?? 'horizontal';
  2897 + printOrientation ?? template.printOrientation ?? 'vertical';
2869 2898 /** 画布 = 模板 width×height×unit(如 2inch×2inch → 192×192px),控件 x/y/width/height 与编辑区 1:1 */
2870 2899 const baseW = unitToPx(Number(template.width) || 0, template.unit);
2871 2900 const baseH = unitToPx(Number(template.height) || 0, template.unit);
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/PropertiesPanel.tsx
... ... @@ -104,7 +104,7 @@ export function PropertiesPanel({
104 104 onDeleteElement,
105 105 readOnlyTemplateCode = false,
106 106 previewRulerUnit = 'cm',
107   - printOrientation = 'horizontal',
  107 + printOrientation = 'vertical',
108 108 }: PropertiesPanelProps) {
109 109 void template;
110 110 void onTemplateChange;
... ... @@ -172,9 +172,9 @@ export function PropertiesPanel({
172 172 }
173 173 />
174 174 </div>
175   - {printOrientation === 'vertical' ? (
  175 + {printOrientation === 'horizontal' ? (
176 176 <p className="text-[10px] leading-snug text-gray-500">
177   - Width / Height follow paper axes (W×H), not the rotated preview. Switch to horizontal to align with what you see on screen.
  177 + Width / Height follow paper axes (W×H), not the rotated preview. Switch to vertical to align with what you see on screen.
178 178 </p>
179 179 ) : null}
180 180 {!isBlankElement ? (
... ... @@ -1125,27 +1125,26 @@ function ElementConfigFields({
1125 1125 case 'NUTRITION':
1126 1126 {
1127 1127 const extraRows = nutritionExtraRows(cfg);
1128   - const applyFixedNutrients = (
1129   - key: string,
1130   - field: 'value' | 'unit',
1131   - nextValue: string,
1132   - ) => {
  1128 + const applyFixedNutrientUnit = (key: string, nextUnit: string) => {
1133 1129 const fixedRows = NUTRITION_FIXED_ITEMS.map((item) => {
1134   - const current = {
  1130 + const unit =
  1131 + nutritionFixedField(cfg, item.key, 'unit') || (item.defaultUnit ?? '');
  1132 + return {
1135 1133 key: item.key,
1136 1134 label: item.label,
1137   - value: nutritionFixedField(cfg, item.key, 'value'),
1138   - unit: nutritionFixedField(cfg, item.key, 'unit'),
  1135 + value: '',
  1136 + unit: item.key === key ? nextUnit : unit,
1139 1137 };
1140   - if (item.key !== key) return current;
1141   - return { ...current, [field]: nextValue };
1142 1138 });
1143 1139 const keyPatch: Record<string, unknown> = { fixedNutrients: fixedRows };
1144   - const target = fixedRows.find((item) => item.key === key);
1145   - if (target) {
1146   - keyPatch[key] = target.value;
1147   - keyPatch[`${key}Unit`] = target.unit;
  1140 + for (const item of NUTRITION_FIXED_ITEMS) {
  1141 + keyPatch[item.key] = '';
  1142 + const row = fixedRows.find((r) => r.key === item.key);
  1143 + if (row?.unit) keyPatch[`${item.key}Unit`] = row.unit;
1148 1144 }
  1145 + keyPatch.calories = '';
  1146 + keyPatch.servingsPerContainer = '';
  1147 + keyPatch.servingSize = '';
1149 1148 onChange(keyPatch);
1150 1149 };
1151 1150  
... ... @@ -1164,11 +1163,11 @@ function ElementConfigFields({
1164 1163  
1165 1164 const updateExtraNutrient = (
1166 1165 id: string,
1167   - field: keyof NutritionExtraItem,
  1166 + field: 'name' | 'unit',
1168 1167 nextValue: string,
1169 1168 ) => {
1170 1169 const next = extraRows.map((item) =>
1171   - item.id === id ? { ...item, [field]: nextValue } : item,
  1170 + item.id === id ? { ...item, [field]: nextValue, value: '' } : item,
1172 1171 );
1173 1172 update('extraNutrients', next);
1174 1173 };
... ... @@ -1183,7 +1182,7 @@ function ElementConfigFields({
1183 1182 return (
1184 1183 <>
1185 1184 <div>
1186   - <Label className="text-xs">Nutrition summary</Label>
  1185 + <Label className="text-xs">Nutrition Facts layout</Label>
1187 1186 <div className="space-y-2 mt-1">
1188 1187 <div className="grid grid-cols-[1fr_90px] gap-2 items-center">
1189 1188 <span className="text-xs text-gray-600">Nutrition Facts title (px)</span>
... ... @@ -1196,90 +1195,38 @@ function ElementConfigFields({
1196 1195 className="h-8 text-sm"
1197 1196 />
1198 1197 </div>
1199   - <div className="grid grid-cols-[1fr_90px] gap-2 items-center">
1200   - <span className="text-xs text-gray-600">Servings Per Container</span>
1201   - <Input
1202   - value={cfgPickStr(cfg, ['servingsPerContainer', 'ServingsPerContainer'], '')}
1203   - onChange={(e) => update('servingsPerContainer', e.target.value)}
1204   - className="h-8 text-sm"
1205   - placeholder="e.g. 8"
1206   - />
1207   - </div>
1208   - <div className="grid grid-cols-[1fr_90px] gap-2 items-center">
1209   - <span className="text-xs text-gray-600">Serving Size</span>
1210   - <Input
1211   - value={cfgPickStr(cfg, ['servingSize', 'ServingSize'], '')}
1212   - onChange={(e) => update('servingSize', e.target.value)}
1213   - className="h-8 text-sm"
1214   - placeholder="e.g. 1 cup"
1215   - />
1216   - </div>
1217   - <div className="grid grid-cols-[1fr_90px] gap-2 items-center">
1218   - <span className="text-xs text-gray-600">Calories</span>
1219   - <Input
1220   - value={cfgPickStr(cfg, ['calories', 'Calories'], '')}
1221   - onChange={(e) => update('calories', e.target.value)}
1222   - className="h-8 text-sm"
1223   - placeholder="e.g. 120"
1224   - />
1225   - </div>
1226 1198 </div>
  1199 + <p className="text-[10px] text-gray-400 mt-2">
  1200 + Servings, calories and nutrient values are entered when creating labels or in Bulk Add.
  1201 + </p>
1227 1202 </div>
1228 1203 <div>
1229   - <div className="flex items-center justify-between mb-1">
1230   - <Label className="text-xs">Nutrition table</Label>
1231   - <Button type="button" variant="outline" className="h-7 px-2 text-xs" onClick={addExtraNutrient}>
1232   - Add nutrient
1233   - </Button>
1234   - </div>
  1204 + <Label className="text-xs">Nutrition table structure</Label>
1235 1205 <div className="space-y-1.5 mt-1">
1236   - <div className="grid grid-cols-[1fr_78px_58px_26px] gap-1.5 items-center text-[10px] text-gray-500 px-0.5">
  1206 + <div className="grid grid-cols-[1fr_58px_26px] gap-1.5 items-center text-[10px] text-gray-500 px-0.5">
1237 1207 <span>Name</span>
1238   - <span>Value</span>
1239 1208 <span>Unit</span>
1240 1209 <span />
1241 1210 </div>
1242 1211 {NUTRITION_FIXED_ITEMS.map((item) => (
1243   - <div key={item.key} className="grid grid-cols-[1fr_78px_58px_26px] gap-1.5 items-center">
  1212 + <div key={item.key} className="grid grid-cols-[1fr_58px_26px] gap-1.5 items-center">
1244 1213 <span className="text-xs text-gray-600">{item.label}</span>
1245 1214 <Input
1246   - value={nutritionFixedField(cfg, item.key, 'value')}
1247   - onChange={(e) =>
1248   - applyFixedNutrients(item.key, 'value', e.target.value)
1249   - }
1250   - className="h-8 text-sm"
1251   - placeholder="Value"
1252   - />
1253   - <Input
1254 1215 value={nutritionFixedField(cfg, item.key, 'unit') || (item.defaultUnit ?? '')}
1255   - onChange={(e) =>
1256   - applyFixedNutrients(item.key, 'unit', e.target.value)
1257   - }
  1216 + onChange={(e) => applyFixedNutrientUnit(item.key, e.target.value)}
1258 1217 className="h-8 text-sm"
1259 1218 placeholder="Unit"
1260 1219 />
1261 1220 <span />
1262 1221 </div>
1263 1222 ))}
1264   - </div>
1265   - </div>
1266   - <div className="space-y-2">
1267   - {extraRows.length === 0 ? (
1268   - <p className="text-[10px] text-gray-400">No custom nutrients yet.</p>
1269   - ) : (
1270   - extraRows.map((row) => (
1271   - <div key={row.id} className="grid grid-cols-[1fr_78px_58px_26px] gap-1.5 items-center">
  1223 + {extraRows.map((row) => (
  1224 + <div key={row.id} className="grid grid-cols-[1fr_58px_26px] gap-1.5 items-center">
1272 1225 <Input
1273 1226 value={row.name}
1274 1227 onChange={(e) => updateExtraNutrient(row.id, 'name', e.target.value)}
1275 1228 className="h-8 text-sm"
1276   - placeholder="Name"
1277   - />
1278   - <Input
1279   - value={row.value}
1280   - onChange={(e) => updateExtraNutrient(row.id, 'value', e.target.value)}
1281   - className="h-8 text-sm"
1282   - placeholder="Value"
  1229 + placeholder="Nutrient name"
1283 1230 />
1284 1231 <Input
1285 1232 value={row.unit}
... ... @@ -1297,10 +1244,18 @@ function ElementConfigFields({
1297 1244 <Trash2 className="h-3.5 w-3.5" />
1298 1245 </Button>
1299 1246 </div>
1300   - ))
1301   - )}
1302   - <div className="text-[10px] text-gray-400">
1303   - Unit is appended after value in template preview.
  1247 + ))}
  1248 + </div>
  1249 + <Button
  1250 + type="button"
  1251 + variant="outline"
  1252 + className="h-7 px-2 text-xs mt-2"
  1253 + onClick={addExtraNutrient}
  1254 + >
  1255 + Add Nutrient
  1256 + </Button>
  1257 + <div className="text-[10px] text-gray-400 mt-2">
  1258 + Unit is appended after the value when printing.
1304 1259 </div>
1305 1260 </div>
1306 1261 </>
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplateEditor/index.tsx
... ... @@ -39,6 +39,7 @@ import { LabelCanvas, LabelPreviewOnly, clampLabelElementBox, mergeLabelElementL
39 39 import type { PreviewRulerDisplayUnit } from '@/utils/previewRulerUnits';
40 40 import { PropertiesPanel } from './PropertiesPanel';
41 41 import { createLabelTemplate, getLabelTemplate, getLabelTemplates, updateLabelTemplate } from '../../../services/labelTemplateService';
  42 +import { sanitizeNutritionElementsForTemplateEditor } from '../../../lib/nutritionManualEntry';
42 43 import { getLocations } from '../../../services/locationService';
43 44 import { getGroups } from '../../../services/groupService';
44 45 import { getPartners } from '../../../services/partnerService';
... ... @@ -99,7 +100,12 @@ export function LabelTemplateEditor({
99 100 }: LabelTemplateEditorProps) {
100 101 const scopeAuth = useCategoryScopeAuth();
101 102 const [template, setTemplate] = useState<LabelTemplate>(() => {
102   - if (initialTemplate) return { ...initialTemplate };
  103 + if (initialTemplate) {
  104 + return {
  105 + ...initialTemplate,
  106 + elements: sanitizeNutritionElementsForTemplateEditor(initialTemplate.elements),
  107 + };
  108 + }
103 109 const next = createDefaultTemplate(templateId ?? undefined);
104 110 return {
105 111 ...next,
... ... @@ -140,7 +146,7 @@ export function LabelTemplateEditor({
140 146 [template, liveElementPatch],
141 147 );
142 148  
143   - const printOrientation = template.printOrientation ?? 'horizontal';
  149 + const printOrientation = template.printOrientation ?? 'vertical';
144 150  
145 151 useEffect(() => {
146 152 let cancelled = false;
... ... @@ -302,11 +308,13 @@ export function LabelTemplateEditor({
302 308 printOrientation: normalizePrintOrientation(
303 309 apiTemplate.printOrientation ?? (apiTemplate as Record<string, unknown>).PrintOrientation,
304 310 ),
305   - elements: (apiTemplate.elements ?? []).map((raw, idx) => {
306   - const el = raw as LabelElement;
307   - const en = (el.elementName ?? '').trim();
308   - return { ...el, elementName: en || `element${idx + 1}` };
309   - }),
  311 + elements: sanitizeNutritionElementsForTemplateEditor(
  312 + (apiTemplate.elements ?? []).map((raw, idx) => {
  313 + const el = raw as LabelElement;
  314 + const en = (el.elementName ?? '').trim();
  315 + return { ...el, elementName: en || `element${idx + 1}` };
  316 + }),
  317 + ),
310 318 });
311 319 setTemplate(copied);
312 320 setLiveElementPatch(null);
... ... @@ -357,7 +365,7 @@ export function LabelTemplateEditor({
357 365 unit === "cm" ? value * 37.8 : value * 96;
358 366 const baseW = unitToPx(prev.width, prev.unit);
359 367 const baseH = unitToPx(prev.height, prev.unit);
360   - const orientation = prev.printOrientation ?? 'horizontal';
  368 + const orientation = prev.printOrientation ?? 'vertical';
361 369 return {
362 370 ...prev,
363 371 elements: prev.elements.map((el) => {
... ... @@ -590,9 +598,11 @@ export function LabelTemplateEditor({
590 598 showRuler: true,
591 599 showGrid: template.showGrid ?? true,
592 600 border: template.border ?? 'none',
593   - printOrientation: template.printOrientation ?? 'horizontal',
  601 + printOrientation: template.printOrientation ?? 'vertical',
594 602 state: true,
595   - elements: labelElementsToApiPayload(template.elements),
  603 + elements: labelElementsToApiPayload(
  604 + sanitizeNutritionElementsForTemplateEditor(template.elements),
  605 + ),
596 606 ...scopePayload.body,
597 607 };
598 608  
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTemplatesView.tsx
... ... @@ -390,7 +390,7 @@ export function LabelTemplatesView({ onTemplateEditorOverlayChange }: LabelTempl
390 390 showRuler: apiTemplate.showRuler ?? true,
391 391 showGrid: apiTemplate.showGrid ?? true,
392 392 border: apiTemplate.border ?? 'none',
393   - printOrientation: apiTemplate.printOrientation ?? 'horizontal',
  393 + printOrientation: apiTemplate.printOrientation ?? 'vertical',
394 394 elements: (apiTemplate.elements ?? []).map((raw, idx) => {
395 395 const el = raw as LabelElement;
396 396 const en = (el.elementName ?? "").trim();
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelTypesView.tsx
... ... @@ -873,6 +873,7 @@ function CreateLabelTypeDialog({
873 873 const locPayload = buildSpecifiedLocationPayload(
874 874 locations,
875 875 partners,
  876 + groups,
876 877 scopePartnerId,
877 878 selectedRegionNames,
878 879 selectedLocationIds,
... ... @@ -1101,6 +1102,7 @@ function EditLabelTypeDialog({
1101 1102 const locPayload = buildSpecifiedLocationPayload(
1102 1103 locations,
1103 1104 partners,
  1105 + groups,
1104 1106 scopePartnerId,
1105 1107 selectedRegionNames,
1106 1108 selectedLocationIds,
... ...
美国版/Food Labeling Management Platform/src/components/labels/LabelsList.tsx
... ... @@ -75,12 +75,12 @@ import {
75 75 isDataEntryTableColumnElement,
76 76 isDateTimeDataEntryField,
77 77 labelElementsToApiPayload,
  78 + normalizePrintOrientation,
78 79 normalizeTemplateBorder,
79 80 sortTemplateElementsForDisplay,
80 81 } from "../../types/labelTemplate";
81 82 import {
82   - applyOffsetToDate,
83   - formatDateByPreset,
  83 + applyLiveDateTimePreviewToElements,
84 84 LABEL_FORM_OFFSET_UNITS,
85 85 normalizeLabelFormOffsetInput,
86 86 offsetFieldUiStateFromStored,
... ... @@ -98,6 +98,9 @@ import {
98 98 import {
99 99 applyProductCodeValueToLabelElements,
100 100 buildTemplateBarcodeQrDefaultsFromCodeValue,
  101 + buildTemplateLabelBindingDefaults,
  102 + isTemplateLabelNameElement,
  103 + isTemplateLabelTypeElement,
101 104 isTemplateSectionBarcodeOrQrElement,
102 105 } from "../../lib/productCodeValueTemplate";
103 106 import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
... ... @@ -172,9 +175,7 @@ function hydrateLabelRegionScopeFromDto(
172 175 };
173 176 }
174 177  
175   - const regionNames = groupIds
176   - .map((id) => (groups.find((g) => g.id === id)?.groupName ?? "").trim())
177   - .filter(Boolean);
  178 + const regionNames = groupIds.filter(Boolean);
178 179 return { partnerId, regionNames: [...new Set(regionNames)] };
179 180 }
180 181  
... ... @@ -353,36 +354,24 @@ function buildCreateLabelPreviewTemplate(
353 354 const tmpl = dtoToEditorTemplate(apiTpl);
354 355 const now = new Date();
355 356 for (const el of tmpl.elements) {
356   - if (!isDataEntryTableColumnElement(el)) continue;
357 357 const cfg = { ...(el.config as Record<string, unknown>) };
358 358 delete cfg.__previewFormatted;
359 359 const id = el.id;
360 360 const type = canonicalElementType(el.type);
  361 + if (!isDataEntryTableColumnElement(el)) {
  362 + el.config = cfg;
  363 + continue;
  364 + }
361 365 if (isDateTimeDataEntryField(el)) {
362 366 const pair = dateOffsets[id] ?? { unit: "Days", value: "" };
363 367 const unit = pair.unit || "Days";
364 368 const norm = normalizeLabelFormOffsetInput(pair.value);
365 369 if (norm.kind === "invalid") {
366   - cfg.__previewFormatted = "";
  370 + cfg.text = "";
  371 + } else if (norm.kind === "zero") {
  372 + cfg.text = serializePrintInputOffset(unit, "0");
367 373 } else {
368   - const amount = norm.kind === "zero" ? 0 : norm.amount;
369   - const d = applyOffsetToDate(now, amount, unit);
370   - if (type === "DATE") {
371   - const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
372   - const format =
373   - (typeof cfg.format === "string" && cfg.format.trim()
374   - ? cfg.format
375   - : typeof cfg.Format === "string" && cfg.Format.trim()
376   - ? cfg.Format
377   - : it === "datetime"
378   - ? "YYYY-MM-DD HH:mm"
379   - : "DD/MM/YYYY") ?? "DD/MM/YYYY";
380   - cfg.__previewFormatted = formatDateByPreset(format, d);
381   - } else if (type === "TIME") {
382   - cfg.__previewFormatted = formatDateByPreset("HH:mm", d);
383   - } else {
384   - cfg.__previewFormatted = `${amount} ${unit}`;
385   - }
  374 + cfg.text = serializePrintInputOffset(unit, norm.storeValue);
386 375 }
387 376 } else {
388 377 const v = textValues[id] ?? "";
... ... @@ -393,6 +382,7 @@ function buildCreateLabelPreviewTemplate(
393 382 }
394 383 el.config = cfg;
395 384 }
  385 + tmpl.elements = applyLiveDateTimePreviewToElements(tmpl.elements, now);
396 386 for (const el of tmpl.elements) {
397 387 if (canonicalElementType(el.type) !== "NUTRITION") continue;
398 388 const manual = nutritionByElementId[el.id] ?? {};
... ... @@ -409,6 +399,7 @@ function collectTemplateDefaultValuesForSave(
409 399 dateOffsets: Record<string, { unit: string; value: string }>,
410 400 nutritionByElementId: Record<string, Record<string, string>>,
411 401 productCodeValue?: string | null,
  402 + labelBindings?: { labelName?: string | null; labelTypeName?: string | null },
412 403 ): Record<string, string> {
413 404 const out: Record<string, string> = {};
414 405 for (const el of getDataEntryElements(latest)) {
... ... @@ -441,6 +432,10 @@ function collectTemplateDefaultValuesForSave(
441 432 productCodeValue,
442 433 ),
443 434 );
  435 + Object.assign(
  436 + out,
  437 + buildTemplateLabelBindingDefaults((latest.elements ?? []) as LabelElement[], labelBindings ?? {}),
  438 + );
444 439 return out;
445 440 }
446 441  
... ... @@ -487,6 +482,72 @@ function hydrateLabelFormInputFromProductDefaults(
487 482 return { textValues, dateOffsets, nutritionByElementId };
488 483 }
489 484  
  485 +function mergeLabelBindingsIntoTextValues(
  486 + textValues: Record<string, string>,
  487 + elements: LabelElement[],
  488 + bindings: { labelName?: string | null; labelTypeName?: string | null },
  489 + options?: { onlyWhenEmpty?: boolean; storedValues?: Record<string, string> },
  490 +): Record<string, string> {
  491 + const out = { ...textValues };
  492 + const binds = buildTemplateLabelBindingDefaults(elements, bindings);
  493 + for (const el of elements) {
  494 + if (!isTemplateLabelNameElement(el) && !isTemplateLabelTypeElement(el)) continue;
  495 + const bindVal = binds[el.id];
  496 + if (!bindVal) continue;
  497 + if (options?.onlyWhenEmpty) {
  498 + const stored = String(options.storedValues?.[el.id] ?? out[el.id] ?? "").trim();
  499 + if (stored) {
  500 + out[el.id] = stored;
  501 + continue;
  502 + }
  503 + }
  504 + out[el.id] = bindVal;
  505 + }
  506 + return out;
  507 +}
  508 +
  509 +function clearTemplateLabelNameFields(
  510 + textValues: Record<string, string>,
  511 + elements: LabelElement[],
  512 +): Record<string, string> {
  513 + const out = { ...textValues };
  514 + for (const el of elements) {
  515 + if (isTemplateLabelNameElement(el)) out[el.id] = "";
  516 + }
  517 + return out;
  518 +}
  519 +
  520 +function resolveLabelFormTemplateTextValues(
  521 + template: LabelTemplateDto,
  522 + productId: string,
  523 + labelTypeId: string,
  524 + labelTypeName: string,
  525 +): Record<string, string> {
  526 + const empty = emptyLabelFormTemplateInputState(template);
  527 + const pid = productId.trim();
  528 + const ltid = labelTypeId.trim();
  529 + const elements = (template.elements ?? []) as LabelElement[];
  530 +
  531 + if (pid && ltid) {
  532 + const hydrated = hydrateLabelFormInputFromProductDefaults(template, pid, ltid);
  533 + let textValues = { ...empty.textValues, ...hydrated.textValues };
  534 + textValues = clearTemplateLabelNameFields(textValues, elements);
  535 + textValues = mergeLabelBindingsIntoTextValues(
  536 + textValues,
  537 + elements,
  538 + { labelTypeName },
  539 + { onlyWhenEmpty: true, storedValues: hydrated.textValues },
  540 + );
  541 + return textValues;
  542 + }
  543 +
  544 + let textValues = { ...empty.textValues };
  545 + if (ltid && labelTypeName) {
  546 + textValues = mergeLabelBindingsIntoTextValues(textValues, elements, { labelTypeName });
  547 + }
  548 + return textValues;
  549 +}
  550 +
490 551 function emptyLabelFormTemplateInputState(template: LabelTemplateDto | null): {
491 552 textValues: Record<string, string>;
492 553 dateOffsets: Record<string, { unit: string; value: string }>;
... ... @@ -531,6 +592,9 @@ function dtoToEditorTemplate(apiTemplate: LabelTemplateDto): LabelTemplate {
531 592 showRuler: apiTemplate.showRuler ?? true,
532 593 showGrid: apiTemplate.showGrid ?? true,
533 594 border: normalizeTemplateBorder(apiTemplate.border),
  595 + printOrientation: normalizePrintOrientation(
  596 + apiTemplate.printOrientation ?? (apiTemplate as Record<string, unknown>).PrintOrientation,
  597 + ),
534 598 elements: (apiTemplate.elements ?? []).map((raw, idx) => {
535 599 const el = raw as LabelElement;
536 600 const en = (el.elementName ?? "").trim();
... ... @@ -686,7 +750,13 @@ function useLabelFormReferenceData(open: boolean, scopeIds: LabelFormReferenceSc
686 750 getProductLocations({ skipCount: 1, maxResultCount: 2000 }),
687 751 ]);
688 752 const locAll = locRes.items ?? [];
689   - const locItems = locationsScopedForCategoryForm(locAll, partners, partnerId, regionNames);
  753 + const locItems = locationsScopedForCategoryForm(
  754 + locAll,
  755 + partners,
  756 + partnerId,
  757 + regionNames,
  758 + groups,
  759 + );
690 760 const allowedLocIds = new Set(locItems.map((l) => l.id).filter(Boolean));
691 761  
692 762 const [catLists, typeLists, prodLists, menuCatLists] = await Promise.all([
... ... @@ -1738,7 +1808,16 @@ function CreateLabelDialog({
1738 1808 }
1739 1809 }, [effectivePartnerId]);
1740 1810  
1741   - const regionScopeReady = !!(effectivePartnerId && selectedRegionNames.length > 0);
  1811 + const createScopeGroupIds = useMemo(
  1812 + () => regionNamesToGroupIds(selectedRegionNames, groups, effectivePartnerId),
  1813 + [selectedRegionNames, groups, effectivePartnerId],
  1814 + );
  1815 +
  1816 + const regionScopeReady = !!(
  1817 + effectivePartnerId &&
  1818 + selectedRegionNames.length > 0 &&
  1819 + createScopeGroupIds.length > 0
  1820 + );
1742 1821  
1743 1822 const scopeBootstrapLoading = refLoading || (!scopeAuth.requireCompanySelection && scopeAuth.loadingPartner);
1744 1823  
... ... @@ -1751,8 +1830,8 @@ function CreateLabelDialog({
1751 1830  
1752 1831 const locationsInScope = useMemo(() => {
1753 1832 if (!regionScopeReady) return [];
1754   - return locations;
1755   - }, [locations, regionScopeReady]);
  1833 + return locationsForRegionGroups(locations, groups, createScopeGroupIds);
  1834 + }, [locations, groups, createScopeGroupIds, regionScopeReady]);
1756 1835  
1757 1836 useEffect(() => {
1758 1837 if (!open) return;
... ... @@ -1862,23 +1941,24 @@ function CreateLabelDialog({
1862 1941 const tpl = await getLabelTemplate(code);
1863 1942 if (cancelled) return;
1864 1943 setSelectedTemplate(tpl);
1865   - const els = getCreateLabelTemplateInputElements(tpl);
1866   - const nextValues: Record<string, string> = {};
1867   - const nextOffsets: Record<string, { unit: string; value: string }> = {};
1868   - for (const el of els) {
1869   - nextValues[el.id] = "";
1870   - if (isDateTimeDataEntryField(el)) {
1871   - nextOffsets[el.id] = { unit: "Days", value: "" };
1872   - }
1873   - }
1874   - setTemplateDataValues(nextValues);
1875   - setTemplateDateOffsets(nextOffsets);
1876   - const nuts = listNutritionElements((tpl.elements ?? []) as LabelElement[]);
1877   - const nextNut: Record<string, Record<string, string>> = {};
1878   - for (const n of nuts) {
1879   - nextNut[n.id] = nutritionManualValuesFromTemplateConfig(n);
  1944 + const pid = (form.productIds[0] ?? "").trim();
  1945 + const ltid = form.labelTypeId.trim();
  1946 + const labelTypeName = (() => {
  1947 + if (!ltid) return "";
  1948 + const t = labelTypesScoped.find((x) => x.id === ltid) ?? types.find((x) => x.id === ltid);
  1949 + return (t?.typeName ?? t?.typeCode ?? "").trim();
  1950 + })();
  1951 + const empty = emptyLabelFormTemplateInputState(tpl);
  1952 + if (pid && ltid) {
  1953 + const hydrated = hydrateLabelFormInputFromProductDefaults(tpl, pid, ltid);
  1954 + setTemplateDataValues(resolveLabelFormTemplateTextValues(tpl, pid, ltid, labelTypeName));
  1955 + setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
  1956 + setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
  1957 + } else {
  1958 + setTemplateDataValues(resolveLabelFormTemplateTextValues(tpl, pid, ltid, labelTypeName));
  1959 + setTemplateDateOffsets(empty.dateOffsets);
  1960 + setNutritionByElementId(empty.nutritionByElementId);
1880 1961 }
1881   - setNutritionByElementId(nextNut);
1882 1962 } catch (e: any) {
1883 1963 if (cancelled) return;
1884 1964 setSelectedTemplate(null);
... ... @@ -1897,6 +1977,34 @@ function CreateLabelDialog({
1897 1977 };
1898 1978 }, [open, form.templateCode]);
1899 1979  
  1980 + useEffect(() => {
  1981 + if (!open || !selectedTemplate) return;
  1982 + const pid = (form.productIds[0] ?? "").trim();
  1983 + const ltid = form.labelTypeId.trim();
  1984 + if (!pid && !ltid) return;
  1985 + const labelTypeName = (() => {
  1986 + if (!ltid) return "";
  1987 + const t = labelTypesScoped.find((x) => x.id === ltid) ?? types.find((x) => x.id === ltid);
  1988 + return (t?.typeName ?? t?.typeCode ?? "").trim();
  1989 + })();
  1990 + if (pid && ltid) {
  1991 + const hydrated = hydrateLabelFormInputFromProductDefaults(selectedTemplate, pid, ltid);
  1992 + const empty = emptyLabelFormTemplateInputState(selectedTemplate);
  1993 + setTemplateDataValues(
  1994 + resolveLabelFormTemplateTextValues(selectedTemplate, pid, ltid, labelTypeName),
  1995 + );
  1996 + setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
  1997 + setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
  1998 + return;
  1999 + }
  2000 + const elements = (selectedTemplate.elements ?? []) as LabelElement[];
  2001 + setTemplateDataValues((prev) =>
  2002 + mergeLabelBindingsIntoTextValues(prev, elements, {
  2003 + labelTypeName: ltid ? labelTypeName : undefined,
  2004 + }),
  2005 + );
  2006 + }, [open, selectedTemplate, form.productIds, form.labelTypeId, productsScoped, labelTypesScoped, types]);
  2007 +
1900 2008 const submit = async () => {
1901 2009 const partnerErr = scopePartnerValidationMessage(
1902 2010 scopeAuth.requireCompanySelection,
... ... @@ -1962,12 +2070,20 @@ function CreateLabelDialog({
1962 2070 const p = productsScoped.find((x) => x.id === pid);
1963 2071 return (p?.codeValue ?? "").trim();
1964 2072 })();
  2073 + const pid = form.productIds[0]?.trim() ?? "";
  2074 + const product = productsScoped.find((x) => x.id === pid);
  2075 + const labelType =
  2076 + labelTypesScoped.find((x) => x.id === labelTypeId) ?? types.find((x) => x.id === labelTypeId);
1965 2077 const inputDefaultValues = collectTemplateDefaultValuesForSave(
1966 2078 latest,
1967 2079 templateDataValues,
1968 2080 templateDateOffsets,
1969 2081 nutritionByElementId,
1970 2082 productCodeValue,
  2083 + {
  2084 + labelName: form.labelName,
  2085 + labelTypeName: labelType?.typeName ?? labelType?.typeCode,
  2086 + },
1971 2087 );
1972 2088 const defaultsMap = buildTemplateDefaultsMap(latest);
1973 2089 for (const productId of form.productIds) {
... ... @@ -2129,6 +2245,23 @@ function CreateLabelDialog({
2129 2245 });
2130 2246 }, [open, selectedTemplate, selectedProductCodeValue]);
2131 2247  
  2248 + /** Label Name 模板控件:随 General Settings 中 Label Name 输入框同步 */
  2249 + useEffect(() => {
  2250 + if (!open || !selectedTemplate) return;
  2251 + const name = form.labelName;
  2252 + setTemplateDataValues((prev) => {
  2253 + let changed = false;
  2254 + const next = { ...prev };
  2255 + for (const el of (selectedTemplate.elements ?? []) as LabelElement[]) {
  2256 + if (!isTemplateLabelNameElement(el)) continue;
  2257 + if (next[el.id] === name) continue;
  2258 + next[el.id] = name;
  2259 + changed = true;
  2260 + }
  2261 + return changed ? next : prev;
  2262 + });
  2263 + }, [open, selectedTemplate, form.labelName]);
  2264 +
2132 2265 const previewTemplate = useMemo(
2133 2266 () =>
2134 2267 buildCreateLabelPreviewTemplate(
... ... @@ -2561,72 +2694,6 @@ function EditLabelDialog({
2561 2694 >({});
2562 2695  
2563 2696 useEffect(() => {
2564   - if (!open) {
2565   - setSelectedTemplate(null);
2566   - setTemplateDataValues({});
2567   - setTemplateDateOffsets({});
2568   - setNutritionByElementId({});
2569   - return;
2570   - }
2571   - const code = form.templateCode.trim();
2572   - if (!code) {
2573   - setSelectedTemplate(null);
2574   - setTemplateDataValues({});
2575   - setTemplateDateOffsets({});
2576   - setNutritionByElementId({});
2577   - return;
2578   - }
2579   - let cancelled = false;
2580   - (async () => {
2581   - setTemplateLoading(true);
2582   - try {
2583   - const tpl = await getLabelTemplate(code);
2584   - if (cancelled) return;
2585   - setSelectedTemplate(tpl);
2586   - const pid = (form.productIds[0] ?? "").trim();
2587   - const ltid = form.labelTypeId.trim();
2588   - const empty = emptyLabelFormTemplateInputState(tpl);
2589   - if (pid && ltid) {
2590   - const hydrated = hydrateLabelFormInputFromProductDefaults(tpl, pid, ltid);
2591   - setTemplateDataValues({ ...empty.textValues, ...hydrated.textValues });
2592   - setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
2593   - setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
2594   - } else {
2595   - setTemplateDataValues(empty.textValues);
2596   - setTemplateDateOffsets(empty.dateOffsets);
2597   - setNutritionByElementId(empty.nutritionByElementId);
2598   - }
2599   - } catch (e: any) {
2600   - if (cancelled) return;
2601   - setSelectedTemplate(null);
2602   - setTemplateDataValues({});
2603   - setTemplateDateOffsets({});
2604   - setNutritionByElementId({});
2605   - toast.error("Failed to load template fields.", {
2606   - description: e?.message ? String(e.message) : "Please select another template.",
2607   - });
2608   - } finally {
2609   - if (!cancelled) setTemplateLoading(false);
2610   - }
2611   - })();
2612   - return () => {
2613   - cancelled = true;
2614   - };
2615   - }, [open, form.templateCode]);
2616   -
2617   - useEffect(() => {
2618   - if (!open || !selectedTemplate) return;
2619   - const pid = (form.productIds[0] ?? "").trim();
2620   - const ltid = form.labelTypeId.trim();
2621   - if (!pid || !ltid) return;
2622   - const hydrated = hydrateLabelFormInputFromProductDefaults(selectedTemplate, pid, ltid);
2623   - const empty = emptyLabelFormTemplateInputState(selectedTemplate);
2624   - setTemplateDataValues({ ...empty.textValues, ...hydrated.textValues });
2625   - setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
2626   - setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
2627   - }, [open, selectedTemplate, form.productIds, form.labelTypeId]);
2628   -
2629   - useEffect(() => {
2630 2697 if (!open || !label?.id) return;
2631 2698  
2632 2699 const id = label.id;
... ... @@ -2793,6 +2860,103 @@ function EditLabelDialog({
2793 2860 const typesLoadingEditScope =
2794 2861 editScopeReady && (labelTypeIdsInEditRegion === null || editScopedLoading);
2795 2862  
  2863 + useEffect(() => {
  2864 + if (!open) {
  2865 + setSelectedTemplate(null);
  2866 + setTemplateDataValues({});
  2867 + setTemplateDateOffsets({});
  2868 + setNutritionByElementId({});
  2869 + return;
  2870 + }
  2871 + const code = form.templateCode.trim();
  2872 + if (!code) {
  2873 + setSelectedTemplate(null);
  2874 + setTemplateDataValues({});
  2875 + setTemplateDateOffsets({});
  2876 + setNutritionByElementId({});
  2877 + return;
  2878 + }
  2879 + let cancelled = false;
  2880 + (async () => {
  2881 + setTemplateLoading(true);
  2882 + try {
  2883 + const tpl = await getLabelTemplate(code);
  2884 + if (cancelled) return;
  2885 + setSelectedTemplate(tpl);
  2886 + const pid = (form.productIds[0] ?? "").trim();
  2887 + const ltid = form.labelTypeId.trim();
  2888 + const labelTypeName = (() => {
  2889 + if (!ltid) return "";
  2890 + const t =
  2891 + labelTypesScopedEdit.find((x) => x.id === ltid) ?? types.find((x) => x.id === ltid);
  2892 + return (t?.typeName ?? t?.typeCode ?? "").trim();
  2893 + })();
  2894 + const empty = emptyLabelFormTemplateInputState(tpl);
  2895 + if (pid && ltid) {
  2896 + const hydrated = hydrateLabelFormInputFromProductDefaults(tpl, pid, ltid);
  2897 + setTemplateDataValues(resolveLabelFormTemplateTextValues(tpl, pid, ltid, labelTypeName));
  2898 + setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
  2899 + setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
  2900 + } else {
  2901 + setTemplateDataValues(resolveLabelFormTemplateTextValues(tpl, pid, ltid, labelTypeName));
  2902 + setTemplateDateOffsets(empty.dateOffsets);
  2903 + setNutritionByElementId(empty.nutritionByElementId);
  2904 + }
  2905 + } catch (e: any) {
  2906 + if (cancelled) return;
  2907 + setSelectedTemplate(null);
  2908 + setTemplateDataValues({});
  2909 + setTemplateDateOffsets({});
  2910 + setNutritionByElementId({});
  2911 + toast.error("Failed to load template fields.", {
  2912 + description: e?.message ? String(e.message) : "Please select another template.",
  2913 + });
  2914 + } finally {
  2915 + if (!cancelled) setTemplateLoading(false);
  2916 + }
  2917 + })();
  2918 + return () => {
  2919 + cancelled = true;
  2920 + };
  2921 + }, [open, form.templateCode, form.productIds, form.labelTypeId, productsScopedEdit, labelTypesScopedEdit, types]);
  2922 +
  2923 + useEffect(() => {
  2924 + if (!open || !selectedTemplate) return;
  2925 + const pid = (form.productIds[0] ?? "").trim();
  2926 + const ltid = form.labelTypeId.trim();
  2927 + if (!pid && !ltid) return;
  2928 + const labelTypeName = (() => {
  2929 + if (!ltid) return "";
  2930 + const t =
  2931 + labelTypesScopedEdit.find((x) => x.id === ltid) ?? types.find((x) => x.id === ltid);
  2932 + return (t?.typeName ?? t?.typeCode ?? "").trim();
  2933 + })();
  2934 + if (pid && ltid) {
  2935 + const hydrated = hydrateLabelFormInputFromProductDefaults(selectedTemplate, pid, ltid);
  2936 + const empty = emptyLabelFormTemplateInputState(selectedTemplate);
  2937 + setTemplateDataValues(
  2938 + resolveLabelFormTemplateTextValues(selectedTemplate, pid, ltid, labelTypeName),
  2939 + );
  2940 + setTemplateDateOffsets({ ...empty.dateOffsets, ...hydrated.dateOffsets });
  2941 + setNutritionByElementId({ ...empty.nutritionByElementId, ...hydrated.nutritionByElementId });
  2942 + return;
  2943 + }
  2944 + const elements = (selectedTemplate.elements ?? []) as LabelElement[];
  2945 + setTemplateDataValues((prev) =>
  2946 + mergeLabelBindingsIntoTextValues(prev, elements, {
  2947 + labelTypeName: ltid ? labelTypeName : undefined,
  2948 + }),
  2949 + );
  2950 + }, [
  2951 + open,
  2952 + selectedTemplate,
  2953 + form.productIds,
  2954 + form.labelTypeId,
  2955 + productsScopedEdit,
  2956 + labelTypesScopedEdit,
  2957 + types,
  2958 + ]);
  2959 +
2796 2960 const submit = async () => {
2797 2961 if (!label?.id) return;
2798 2962 const partnerErr = scopePartnerValidationMessage(
... ... @@ -2858,12 +3022,21 @@ function EditLabelDialog({
2858 3022 const p = productsScopedEdit.find((x) => x.id === pid);
2859 3023 return (p?.codeValue ?? "").trim();
2860 3024 })();
  3025 + const pid = form.productIds[0]?.trim() ?? "";
  3026 + const product = productsScopedEdit.find((x) => x.id === pid);
  3027 + const labelType =
  3028 + labelTypesScopedEdit.find((x) => x.id === labelTypeId) ??
  3029 + types.find((x) => x.id === labelTypeId);
2861 3030 const inputDefaultValues = collectTemplateDefaultValuesForSave(
2862 3031 latest,
2863 3032 templateDataValues,
2864 3033 templateDateOffsets,
2865 3034 nutritionByElementId,
2866 3035 productCodeValue,
  3036 + {
  3037 + labelName: form.labelName,
  3038 + labelTypeName: labelType?.typeName ?? labelType?.typeCode,
  3039 + },
2867 3040 );
2868 3041 const defaultsMap = buildTemplateDefaultsMap(latest);
2869 3042 for (const productId of form.productIds) {
... ... @@ -3020,6 +3193,23 @@ function EditLabelDialog({
3020 3193 });
3021 3194 }, [open, selectedTemplate, editSelectedProductCodeValue]);
3022 3195  
  3196 + /** Label Name 模板控件:随 General Settings 中 Label Name 输入框同步 */
  3197 + useEffect(() => {
  3198 + if (!open || !selectedTemplate) return;
  3199 + const name = form.labelName;
  3200 + setTemplateDataValues((prev) => {
  3201 + let changed = false;
  3202 + const next = { ...prev };
  3203 + for (const el of (selectedTemplate.elements ?? []) as LabelElement[]) {
  3204 + if (!isTemplateLabelNameElement(el)) continue;
  3205 + if (next[el.id] === name) continue;
  3206 + next[el.id] = name;
  3207 + changed = true;
  3208 + }
  3209 + return changed ? next : prev;
  3210 + });
  3211 + }, [open, selectedTemplate, form.labelName]);
  3212 +
3023 3213 const editPreviewTemplate = useMemo(
3024 3214 () =>
3025 3215 buildCreateLabelPreviewTemplate(
... ...
美国版/Food Labeling Management Platform/src/components/labels/MultipleOptionsView.tsx
... ... @@ -890,6 +890,7 @@ function CreateMultipleOptionDialog({
890 890 const locPayload = buildSpecifiedLocationPayload(
891 891 locations,
892 892 partners,
  893 + groups,
893 894 scopePartnerId,
894 895 selectedRegionNames,
895 896 selectedLocationIds,
... ... @@ -1189,6 +1190,7 @@ function EditMultipleOptionDialog({
1189 1190 const locPayload = buildSpecifiedLocationPayload(
1190 1191 locations,
1191 1192 partners,
  1193 + groups,
1192 1194 scopePartnerId,
1193 1195 selectedRegionNames,
1194 1196 selectedLocationIds,
... ...
美国版/Food Labeling Management Platform/src/components/people/PeopleView.tsx
... ... @@ -106,6 +106,7 @@ import { useAuth } from &quot;../auth/AuthProvider&quot;;
106 106 import {
107 107 canMutateAccountManagementStructure,
108 108 canMutateRegionAndLocationStructure,
  109 + isCompanyAdminRole,
109 110 } from "../../lib/accountManagementAccess";
110 111 import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
111 112 import { skipCountForPage } from "../../lib/paginationQuery";
... ... @@ -220,6 +221,14 @@ function displayRoleNameForUi(name: string | null | undefined, fallback?: string
220 221 return s;
221 222 }
222 223  
  224 +function isCompanyAdminRoleOption(role: RoleDto | null | undefined): boolean {
  225 + if (!role) return false;
  226 + return isCompanyAdminRole({
  227 + roleDisplay: role.roleName ?? null,
  228 + roleCodes: role.roleCode ? [role.roleCode] : [],
  229 + });
  230 +}
  231 +
223 232 export type ProfileEditIntent = { userId: string; nonce: number };
224 233  
225 234 export type PeopleViewProps = {
... ... @@ -3260,6 +3269,24 @@ function MemberDialog({
3260 3269 [regionSelectOptions, selectedRegionIds],
3261 3270 );
3262 3271  
  3272 + const selectedRole = useMemo(
  3273 + () => roleOptions.find((r) => r.id === roleId) ?? null,
  3274 + [roleOptions, roleId],
  3275 + );
  3276 +
  3277 + const isCompanyAdminSelected = useMemo(
  3278 + () => isCompanyAdminRoleOption(selectedRole),
  3279 + [selectedRole],
  3280 + );
  3281 +
  3282 + useEffect(() => {
  3283 + if (!open || !isCompanyAdminSelected) return;
  3284 + setSelectedRegionIds(new Set());
  3285 + setSelectedLocationIds(new Set());
  3286 + setScopedLocationOptions([]);
  3287 + setLocationKeyword("");
  3288 + }, [open, isCompanyAdminSelected]);
  3289 +
3263 3290 const selectedLocationIdsForSubmit = useMemo(() => {
3264 3291 const allowedNorm = new Set(
3265 3292 locationsForMemberPicker.map((l) => normLocationId(l.id)).filter(Boolean),
... ... @@ -3283,8 +3310,10 @@ function MemberDialog({
3283 3310 if (!String(phone ?? "").trim()) return false;
3284 3311 if (!roleId.trim()) return false;
3285 3312 if (!companyId.trim()) return false;
3286   - if (selectedRegionIdsForSubmit.length === 0) return false;
3287   - if (selectedLocationIdsForSubmit.length === 0) return false;
  3313 + if (!isCompanyAdminSelected) {
  3314 + if (selectedRegionIdsForSubmit.length === 0) return false;
  3315 + if (selectedLocationIdsForSubmit.length === 0) return false;
  3316 + }
3288 3317 if (!isEdit && !password.trim()) return false;
3289 3318 return true;
3290 3319 }, [
... ... @@ -3294,6 +3323,7 @@ function MemberDialog({
3294 3323 phone,
3295 3324 roleId,
3296 3325 companyId,
  3326 + isCompanyAdminSelected,
3297 3327 selectedRegionIdsForSubmit,
3298 3328 selectedLocationIdsForSubmit,
3299 3329 isEdit,
... ... @@ -3359,8 +3389,10 @@ function MemberDialog({
3359 3389 if (!String(phone ?? "").trim()) missing.push("Phone");
3360 3390 if (!roleId.trim()) missing.push("Role");
3361 3391 if (!companyId.trim()) missing.push("Company");
3362   - if (selectedRegionIdsForSubmit.length === 0) missing.push("Region");
3363   - if (selectedLocationIdsForSubmit.length === 0) missing.push("Locations");
  3392 + if (!isCompanyAdminSelected) {
  3393 + if (selectedRegionIdsForSubmit.length === 0) missing.push("Region");
  3394 + if (selectedLocationIdsForSubmit.length === 0) missing.push("Locations");
  3395 + }
3364 3396 if (!isEdit && !password.trim()) missing.push("Password");
3365 3397 toast.error("Missing required fields.", {
3366 3398 description: `Please fill: ${missing.join(", ")}.`,
... ... @@ -3372,8 +3404,8 @@ function MemberDialog({
3372 3404 // 新增模式
3373 3405 setSubmitting(true);
3374 3406 try {
3375   - const locationIds = selectedLocationIdsForSubmit;
3376   - const regionIds = selectedRegionIdsForSubmit;
  3407 + const locationIds = isCompanyAdminSelected ? [] : selectedLocationIdsForSubmit;
  3408 + const regionIds = isCompanyAdminSelected ? [] : selectedRegionIdsForSubmit;
3377 3409 const partnerId = companyId.trim();
3378 3410 console.log("[MemberDialog] Creating user", { fullName, userName, roleId, partnerId, regionIds, locationIds });
3379 3411 await createTeamMember({
... ... @@ -3403,8 +3435,8 @@ function MemberDialog({
3403 3435 // 编辑模式
3404 3436 setSubmitting(true);
3405 3437 try {
3406   - const locationIds = selectedLocationIdsForSubmit;
3407   - const regionIds = selectedRegionIdsForSubmit;
  3438 + const locationIds = isCompanyAdminSelected ? [] : selectedLocationIdsForSubmit;
  3439 + const regionIds = isCompanyAdminSelected ? [] : selectedRegionIdsForSubmit;
3408 3440 const partnerId = companyId.trim();
3409 3441 console.log("[MemberDialog] Updating user", { id: member.id, fullName, userName, roleId, partnerId, regionIds, locationIds });
3410 3442 await updateTeamMember(member.id, {
... ... @@ -3517,6 +3549,13 @@ function MemberDialog({
3517 3549 const newRoleId = (v && v.trim()) ? v.trim() : "";
3518 3550 console.log("[MemberDialog] Role changed", { old: roleId, new: newRoleId, v });
3519 3551 setRoleId(newRoleId);
  3552 + const nextRole = roleOptions.find((r) => r.id === newRoleId) ?? null;
  3553 + if (isCompanyAdminRoleOption(nextRole)) {
  3554 + setSelectedRegionIds(new Set());
  3555 + setSelectedLocationIds(new Set());
  3556 + setScopedLocationOptions([]);
  3557 + setLocationKeyword("");
  3558 + }
3520 3559 }}
3521 3560 disabled={loadingRoles}
3522 3561 >
... ... @@ -3533,7 +3572,7 @@ function MemberDialog({
3533 3572 </Select>
3534 3573 </div>
3535 3574  
3536   - <div className="grid grid-cols-2 gap-4">
  3575 + <div className={isCompanyAdminSelected ? "space-y-2" : "grid grid-cols-2 gap-4"}>
3537 3576 <div className="space-y-2">
3538 3577 <Label>Company *</Label>
3539 3578 <Select
... ... @@ -3541,9 +3580,11 @@ function MemberDialog({
3541 3580 onValueChange={(v) => {
3542 3581 const next = (v && v.trim()) ? v.trim() : "";
3543 3582 setCompanyId(next);
3544   - setSelectedRegionIds(new Set());
3545   - setSelectedLocationIds(new Set());
3546   - setScopedLocationOptions([]);
  3583 + if (!isCompanyAdminSelected) {
  3584 + setSelectedRegionIds(new Set());
  3585 + setSelectedLocationIds(new Set());
  3586 + setScopedLocationOptions([]);
  3587 + }
3547 3588 }}
3548 3589 disabled={loadingRoles || loadingPartnersGroups}
3549 3590 >
... ... @@ -3563,28 +3604,31 @@ function MemberDialog({
3563 3604 </SelectContent>
3564 3605 </Select>
3565 3606 </div>
3566   - <div className="space-y-2">
3567   - <Label>Region *</Label>
3568   - <SearchableMultiSelect
3569   - values={selectedRegionIdsForSubmit}
3570   - onValuesChange={(next) => setSelectedRegionIds(new Set(next))}
3571   - options={regionMultiSelectOptions}
3572   - placeholder={
3573   - !companyId.trim()
3574   - ? "Select company first"
3575   - : loadingPartnersGroups
3576   - ? "Loading regions..."
3577   - : "Select region(s)…"
3578   - }
3579   - searchPlaceholder="Search regions…"
3580   - emptyText="No regions for this company."
3581   - selectAllRowLabel="ALL"
3582   - disabled={loadingRoles || loadingPartnersGroups || !companyId.trim()}
3583   - className="h-10 rounded-md border border-gray-200 bg-white"
3584   - />
3585   - </div>
  3607 + {!isCompanyAdminSelected ? (
  3608 + <div className="space-y-2">
  3609 + <Label>Region *</Label>
  3610 + <SearchableMultiSelect
  3611 + values={selectedRegionIdsForSubmit}
  3612 + onValuesChange={(next) => setSelectedRegionIds(new Set(next))}
  3613 + options={regionMultiSelectOptions}
  3614 + placeholder={
  3615 + !companyId.trim()
  3616 + ? "Select company first"
  3617 + : loadingPartnersGroups
  3618 + ? "Loading regions..."
  3619 + : "Select region(s)…"
  3620 + }
  3621 + searchPlaceholder="Search regions…"
  3622 + emptyText="No regions for this company."
  3623 + selectAllRowLabel="ALL"
  3624 + disabled={loadingRoles || loadingPartnersGroups || !companyId.trim()}
  3625 + className="h-10 rounded-md border border-gray-200 bg-white"
  3626 + />
  3627 + </div>
  3628 + ) : null}
3586 3629 </div>
3587 3630  
  3631 + {!isCompanyAdminSelected ? (
3588 3632 <div className="space-y-2">
3589 3633 <Label>Locations *</Label>
3590 3634 <div className="flex items-center justify-between gap-2">
... ... @@ -3652,6 +3696,7 @@ function MemberDialog({
3652 3696 </ScrollArea>
3653 3697 <p className="text-xs text-gray-500">* Users must be assigned to at least one location.</p>
3654 3698 </div>
  3699 + ) : null}
3655 3700  
3656 3701 <div className="flex items-center gap-2 pt-2">
3657 3702 <Switch id="member-status" checked={state} onCheckedChange={setState} />
... ...
美国版/Food Labeling Management Platform/src/components/products/ProductsView.tsx
... ... @@ -59,6 +59,7 @@ import {
59 59 normalizeDisplayText,
60 60 visualInputFromAppearanceAndValueArray,
61 61 } from "../../lib/categoryButtonAppearance";
  62 +import { CategoryButtonAppearancePreview } from "../ui/category-button-appearance-preview";
62 63 import { CategoryButtonVisualThumb } from "../ui/category-button-visual-thumb";
63 64 import {
64 65 FORM_DIALOG_CONTENT_CLASS,
... ... @@ -925,7 +926,6 @@ export function ProductsView() {
925 926 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Location</TableHead>
926 927 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Product Category</TableHead>
927 928 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Product</TableHead>
928   - <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Product ID</TableHead>
929 929 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Product Code</TableHead>
930 930 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Status</TableHead>
931 931 <TableHead className="text-sm font-semibold text-gray-900 text-center whitespace-nowrap">Actions</TableHead>
... ... @@ -934,13 +934,13 @@ export function ProductsView() {
934 934 <TableBody>
935 935 {loading ? (
936 936 <TableRow>
937   - <TableCell colSpan={8} className="text-center text-sm font-normal text-gray-900 py-10">
  937 + <TableCell colSpan={7} className="text-center text-sm font-normal text-gray-900 py-10">
938 938 Loading...
939 939 </TableCell>
940 940 </TableRow>
941 941 ) : products.length === 0 ? (
942 942 <TableRow>
943   - <TableCell colSpan={8} className="text-center text-sm font-normal text-gray-900 py-10">
  943 + <TableCell colSpan={7} className="text-center text-sm font-normal text-gray-900 py-10">
944 944 No products found.
945 945 </TableCell>
946 946 </TableRow>
... ... @@ -995,9 +995,6 @@ export function ProductsView() {
995 995 <span className="truncate">{toDisplay(p.productName)}</span>
996 996 </div>
997 997 </TableCell>
998   - <TableCell className="border-r text-sm font-normal text-gray-900 whitespace-nowrap tabular-nums">
999   - {p.id}
1000   - </TableCell>
1001 998 <TableCell className="border-r text-sm font-normal text-gray-900 whitespace-nowrap">
1002 999 {toDisplay(p.productCode)}
1003 1000 </TableCell>
... ... @@ -1116,12 +1113,23 @@ export function ProductsView() {
1116 1113 </div>
1117 1114 ) : (
1118 1115 <div className="bg-white border border-gray-200 shadow-sm rounded-md overflow-hidden flex flex-col">
1119   - <Table>
  1116 + <Table className="table-fixed">
  1117 + <colgroup>
  1118 + <col />
  1119 + <col className="w-16" />
  1120 + <col className="w-16" />
  1121 + <col className="w-[14%]" />
  1122 + <col className="w-[18%]" />
  1123 + <col className="w-16" />
  1124 + <col className="w-20" />
  1125 + <col className="w-36" />
  1126 + <col className="w-[72px]" />
  1127 + </colgroup>
1120 1128 <TableHeader>
1121 1129 <TableRow className="bg-gray-100 hover:bg-gray-100">
1122 1130 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Category Name</TableHead>
1123 1131 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Code</TableHead>
1124   - <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Display</TableHead>
  1132 + <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap w-16 max-w-16">Display</TableHead>
1125 1133 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Region</TableHead>
1126 1134 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Location</TableHead>
1127 1135 <TableHead className="border-r text-sm font-semibold text-gray-900 whitespace-nowrap">Order</TableHead>
... ... @@ -1166,45 +1174,11 @@ export function ProductsView() {
1166 1174 <TableCell className="border-r text-sm font-normal text-gray-900 whitespace-nowrap">
1167 1175 {toDisplay(c.categoryCode)}
1168 1176 </TableCell>
1169   - <TableCell className="border-r">
1170   - {visual.mode === "image" ? (
1171   - <div className="w-10 h-10 rounded-[12px] border border-gray-200 overflow-hidden shadow-sm bg-gray-50">
1172   - <img
1173   - src={resolvePictureUrlForDisplay(visual.imageUrl)}
1174   - alt=""
1175   - className="w-full h-full object-cover"
1176   - />
1177   - </div>
1178   - ) : visual.mode === "colorText" ? (
1179   - <div
1180   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm flex items-center justify-center px-1 overflow-hidden"
1181   - style={{
1182   - backgroundColor: visual.bg,
1183   - color: visual.textColor || "#ffffff",
1184   - }}
1185   - title={`${visual.text}`}
1186   - >
1187   - <span className="text-xs font-normal leading-tight text-center line-clamp-2 break-all">
1188   - {visual.text}
1189   - </span>
1190   - </div>
1191   - ) : visual.mode === "color" ? (
1192   - <div
1193   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm"
1194   - style={{ backgroundColor: visual.bg }}
1195   - title={visual.bg}
1196   - />
1197   - ) : visual.mode === "text" ? (
1198   - <div
1199   - className="w-10 h-10 rounded-[12px] border border-gray-200 shadow-sm bg-gray-50 flex items-center justify-center px-1 overflow-hidden"
1200   - title={visual.text}
1201   - >
1202   - <span className="text-xs font-normal text-gray-800 text-center line-clamp-2 break-all">
1203   - {visual.text}
1204   - </span>
1205   - </div>
1206   - ) : (
  1177 + <TableCell className="border-r !whitespace-normal align-middle w-16 max-w-16 p-2">
  1178 + {visual.mode === "none" ? (
1207 1179 <span className="text-sm font-normal text-gray-900">—</span>
  1180 + ) : (
  1181 + <CategoryButtonVisualThumb visual={visual} size="md" />
1208 1182 )}
1209 1183 </TableCell>
1210 1184 <TableCell
... ... @@ -1688,6 +1662,7 @@ function ProductFormDialog({
1688 1662 const locPayload = buildSpecifiedLocationPayload(
1689 1663 locationsCatalog,
1690 1664 partners,
  1665 + groups,
1691 1666 effectivePartnerId,
1692 1667 selectedRegionNames,
1693 1668 selectedLocationIds,
... ... @@ -2304,6 +2279,7 @@ function ProductCategoryFormDialog({
2304 2279 const locPayload = buildSpecifiedLocationPayload(
2305 2280 locations,
2306 2281 partners,
  2282 + groups,
2307 2283 scopePartnerId,
2308 2284 selectedRegionNames,
2309 2285 selectedLocationIds,
... ... @@ -2572,6 +2548,14 @@ function ProductCategoryFormDialog({
2572 2548 </div>
2573 2549 ) : null}
2574 2550  
  2551 + <CategoryButtonAppearancePreview
  2552 + apSel={apSel}
  2553 + displayText={displayText}
  2554 + buttonBgColor={buttonBgColor}
  2555 + imageUrl={apSel.image ? buttonImageUrl.trim() : ""}
  2556 + fallbackName={categoryName.trim() || displayText.trim()}
  2557 + />
  2558 +
2575 2559 <div className="space-y-2">
2576 2560 <Label>Order *</Label>
2577 2561 <Input
... ...
美国版/Food Labeling Management Platform/src/components/shared/category-scope-fields.tsx
... ... @@ -8,6 +8,7 @@ import {
8 8 locationsScopedForTemplateScope,
9 9 regionOptionsForPartner,
10 10 regionOptionsForPartners,
  11 + regionSelectionToGroupNames,
11 12 } from "../../lib/categoryScopeForm";
12 13 import type { GroupListItem } from "../../types/group";
13 14 import type { LocationDto } from "../../types/location";
... ... @@ -132,6 +133,7 @@ export function CategoryScopeFields({
132 133 partners,
133 134 effectivePartnerId,
134 135 selectedRegionNames,
  136 + groups,
135 137 );
136 138 }, [
137 139 templateScopeMode,
... ... @@ -199,19 +201,19 @@ export function CategoryScopeFields({
199 201  
200 202 const onRegionMultiChange = useCallback(
201 203 (nextRegions: string[]) => {
202   - const names = nextRegions.map((x) => x.trim()).filter(Boolean);
  204 + const groupNames = regionSelectionToGroupNames(nextRegions, groups, effectivePartnerId);
203 205 onRegionChange(nextRegions);
204 206 onLocationChange(
205 207 selectedLocationIds.filter((id) => {
206 208 const loc = scopedLocations.find((l) => l.id === id);
207 209 if (!loc) return false;
208   - if (names.length === 0) return true;
  210 + if (groupNames.length === 0) return true;
209 211 const g = (loc.groupName ?? "").trim();
210   - return !!g && names.includes(g);
  212 + return !!g && groupNames.includes(g);
211 213 }),
212 214 );
213 215 },
214   - [onRegionChange, onLocationChange, selectedLocationIds, scopedLocations],
  216 + [onRegionChange, onLocationChange, selectedLocationIds, scopedLocations, groups, effectivePartnerId],
215 217 );
216 218  
217 219 const companyReady = templateScopeMode
... ...
美国版/Food Labeling Management Platform/src/components/ui/category-button-appearance-preview.tsx 0 → 100644
  1 +import { useMemo } from "react";
  2 +import { buildCategoryVisualFromAppearanceForm } from "../../lib/categoryButtonAppearance";
  3 +import { CategoryButtonVisualThumb } from "./category-button-visual-thumb";
  4 +import { Label } from "./label";
  5 +
  6 +type AppearanceSelection = { text: boolean; color: boolean; image: boolean };
  7 +
  8 +const SIZE_LABELS = [
  9 + { size: "sm" as const, label: "32×32" },
  10 + { size: "md" as const, label: "48×48" },
  11 + { size: "preview" as const, label: "App card" },
  12 +];
  13 +
  14 +export function CategoryButtonAppearancePreview({
  15 + apSel,
  16 + displayText,
  17 + buttonBgColor,
  18 + imageUrl,
  19 + fallbackName,
  20 +}: {
  21 + apSel: AppearanceSelection;
  22 + displayText: string;
  23 + buttonBgColor: string;
  24 + imageUrl: string;
  25 + fallbackName: string;
  26 +}) {
  27 + const visual = useMemo(
  28 + () =>
  29 + buildCategoryVisualFromAppearanceForm({
  30 + apSel,
  31 + displayText,
  32 + buttonBgColor,
  33 + imageUrl,
  34 + fallbackName,
  35 + }),
  36 + [apSel, displayText, buttonBgColor, imageUrl, fallbackName],
  37 + );
  38 +
  39 + return (
  40 + <div className="space-y-2">
  41 + <Label>Display preview</Label>
  42 + <div className="flex flex-wrap items-end gap-4 rounded-2xl border border-gray-200 bg-gray-50 p-3">
  43 + {SIZE_LABELS.map(({ size, label }) => (
  44 + <div key={size} className="flex flex-col items-center gap-1.5">
  45 + <CategoryButtonVisualThumb visual={visual} size={size} />
  46 + <span className="text-[10px] text-gray-500">{label}</span>
  47 + </div>
  48 + ))}
  49 + </div>
  50 + </div>
  51 + );
  52 +}
... ...
美国版/Food Labeling Management Platform/src/components/ui/category-button-visual-thumb.tsx
  1 +import type { CSSProperties } from "react";
1 2 import type { CategoryVisualRender } from "../../lib/categoryButtonAppearance";
2 3 import { resolvePictureUrlForDisplay } from "../../services/imageUploadService";
3 4 import { cn } from "./utils";
4 5  
5   -type Size = "sm" | "md";
  6 +type Size = "sm" | "md" | "preview";
6 7  
7   -const BOX: Record<Size, string> = {
8   - sm: "w-8 h-8 rounded-[8px]",
9   - md: "w-10 h-10 rounded-[12px]",
  8 +const THUMB_SIZE: Record<Size, { width: number; height: number }> = {
  9 + sm: { width: 32, height: 32 },
  10 + md: { width: 48, height: 48 },
  11 + preview: { width: 140, height: 81 },
10 12 };
11 13  
  14 +const TEXT_WRAP_STYLE: CSSProperties = {
  15 + display: "block",
  16 + width: "100%",
  17 + maxWidth: "100%",
  18 + minWidth: 0,
  19 + whiteSpace: "normal",
  20 + wordBreak: "break-word",
  21 + overflow: "hidden",
  22 + textAlign: "center",
  23 + lineHeight: 1.15,
  24 +};
  25 +
  26 +function thumbBoxStyle(size: Size, extra?: CSSProperties): CSSProperties {
  27 + const { width, height } = THUMB_SIZE[size];
  28 + return {
  29 + width,
  30 + height,
  31 + maxWidth: width,
  32 + minWidth: width,
  33 + maxHeight: height,
  34 + minHeight: height,
  35 + boxSizing: "border-box",
  36 + ...extra,
  37 + };
  38 +}
  39 +
  40 +function textThumbShellStyle(size: Size, extra?: CSSProperties): CSSProperties {
  41 + return thumbBoxStyle(size, {
  42 + display: "flex",
  43 + alignItems: "center",
  44 + justifyContent: "center",
  45 + overflow: "hidden",
  46 + padding: size === "preview" ? 4 : 2,
  47 + ...extra,
  48 + });
  49 +}
  50 +
12 51 /** 产品分类 / 产品列表:按 buttonAppearance + categoryPhotoUrl 渲染色块或图片 */
13 52 export function CategoryButtonVisualThumb({
14 53 visual,
... ... @@ -19,69 +58,64 @@ export function CategoryButtonVisualThumb({
19 58 size?: Size;
20 59 className?: string;
21 60 }) {
22   - const box = BOX[size];
  61 + const radius = size === "sm" ? 8 : size === "md" ? 12 : 14;
  62 + const fontSize = size === "sm" ? 10 : size === "md" ? 11 : 13;
23 63  
24 64 if (visual.mode === "image") {
25 65 return (
26 66 <div
27   - className={cn(
28   - box,
29   - "border border-gray-200 overflow-hidden shadow-sm bg-gray-50 shrink-0",
30   - className,
31   - )}
  67 + className={cn("border border-gray-200 overflow-hidden shadow-sm bg-gray-50 shrink-0", className)}
  68 + style={thumbBoxStyle(size, { borderRadius: radius })}
32 69 >
33 70 <img
34 71 src={resolvePictureUrlForDisplay(visual.imageUrl)}
35 72 alt=""
36   - className="w-full h-full object-cover"
  73 + className="h-full w-full object-cover"
37 74 />
38 75 </div>
39 76 );
40 77 }
  78 +
41 79 if (visual.mode === "colorText") {
42 80 return (
43 81 <div
44   - className={cn(
45   - box,
46   - "border border-gray-200 shadow-sm flex items-center justify-center px-0.5 overflow-hidden shrink-0",
47   - className,
48   - )}
49   - style={{
  82 + className={cn("border border-gray-200 shadow-sm shrink-0", className)}
  83 + style={textThumbShellStyle(size, {
  84 + borderRadius: radius,
50 85 backgroundColor: visual.bg,
51 86 color: visual.textColor || "#ffffff",
52   - }}
  87 + })}
53 88 title={visual.text}
54 89 >
55   - <span className="text-[10px] font-normal leading-tight text-center line-clamp-2 break-all">
56   - {visual.text}
57   - </span>
  90 + <span style={{ ...TEXT_WRAP_STYLE, fontSize }}>{visual.text}</span>
58 91 </div>
59 92 );
60 93 }
  94 +
61 95 if (visual.mode === "color") {
62 96 return (
63 97 <div
64   - className={cn(box, "border border-gray-200 shadow-sm shrink-0", className)}
65   - style={{ backgroundColor: visual.bg }}
  98 + className={cn("border border-gray-200 shadow-sm shrink-0", className)}
  99 + style={thumbBoxStyle(size, {
  100 + borderRadius: radius,
  101 + backgroundColor: visual.bg,
  102 + })}
66 103 title={visual.bg}
67 104 />
68 105 );
69 106 }
  107 +
70 108 if (visual.mode === "text") {
71 109 return (
72 110 <div
73   - className={cn(
74   - box,
75   - "border border-gray-200 shadow-sm bg-gray-50 flex items-center justify-center px-0.5 overflow-hidden shrink-0",
76   - className,
77   - )}
  111 + className={cn("border border-gray-200 shadow-sm bg-gray-50 shrink-0", className)}
  112 + style={textThumbShellStyle(size, { borderRadius: radius })}
78 113 title={visual.text}
79 114 >
80   - <span className="text-[10px] font-normal text-gray-800 text-center line-clamp-2 break-all">
81   - {visual.text}
82   - </span>
  115 + <span style={{ ...TEXT_WRAP_STYLE, fontSize, color: "#1f2937" }}>{visual.text}</span>
83 116 </div>
84 117 );
85 118 }
  119 +
86 120 return <span className={cn("text-sm font-normal text-gray-400 shrink-0", className)}>—</span>;
87 121 }
... ...
美国版/Food Labeling Management Platform/src/lib/categoryButtonAppearance.ts
... ... @@ -359,6 +359,25 @@ export function resolveProductButtonVisualFromDto(row: {
359 359 return { mode: "none" };
360 360 }
361 361  
  362 +/** 表单实时预览:由 Button Appearance 勾选与字段值构建展示形态 */
  363 +export function buildCategoryVisualFromAppearanceForm(input: {
  364 + apSel: { text: boolean; color: boolean; image: boolean };
  365 + displayText: string;
  366 + buttonBgColor: string;
  367 + imageUrl: string;
  368 + fallbackName: string;
  369 +}): CategoryVisualRender {
  370 + const tokens = tokensFromSelection(input.apSel);
  371 + return resolveCategoryButtonVisual({
  372 + buttonAppearance: tokens,
  373 + displayText: input.displayText,
  374 + buttonBgColor: input.buttonBgColor,
  375 + buttonImageUrl: input.imageUrl,
  376 + categoryName: input.fallbackName,
  377 + name: input.fallbackName,
  378 + });
  379 +}
  380 +
362 381 export function resolveCategoryButtonVisual(input: CategoryVisualInput): CategoryVisualRender {
363 382 const tokens = parseAppearanceTokens(input.buttonAppearance);
364 383 const categoryName = (input.categoryName ?? input.name ?? "").trim();
... ...
美国版/Food Labeling Management Platform/src/lib/categoryScopeForm.ts
... ... @@ -104,10 +104,15 @@ export function locationsScopedForCategoryForm(
104 104 locations: LocationDto[],
105 105 partners: PartnerListItem[],
106 106 partnerId: string,
107   - regionNames: string[],
  107 + regionSelection: string[],
  108 + groups?: GroupListItem[],
108 109 ): LocationDto[] {
109 110 const pn = partnerNameById(partners, partnerId);
110   - const regionSet = new Set(regionNames.map((x) => x.trim()).filter(Boolean));
  111 + const regionSet = new Set(
  112 + groups?.length
  113 + ? regionSelectionToGroupNames(regionSelection, groups, partnerId)
  114 + : regionSelection.map((x) => x.trim()).filter(Boolean),
  115 + );
111 116 return locations.filter((loc) => {
112 117 if (pn && (loc.partner ?? "").trim() !== pn) return false;
113 118 if (regionSet.size > 0) {
... ... @@ -223,6 +228,7 @@ export function hydrateLabelTemplateScopeFromDto(
223 228 export function buildSpecifiedLocationPayload(
224 229 locations: LocationDto[],
225 230 partners: PartnerListItem[],
  231 + groups: GroupListItem[],
226 232 selectedPartnerId: string,
227 233 selectedRegionNames: string[],
228 234 selectedLocationIds: string[],
... ... @@ -236,12 +242,24 @@ export function buildSpecifiedLocationPayload(
236 242 return { ok: false, message: "Selected company is invalid." };
237 243 }
238 244  
239   - const regionNamesClean = selectedRegionNames.map((x) => x.trim()).filter(Boolean);
240   - if (regionNamesClean.length === 0) {
  245 + const regionSelectionClean = selectedRegionNames.map((x) => x.trim()).filter(Boolean);
  246 + if (regionSelectionClean.length === 0) {
241 247 return { ok: false, message: "Please select at least one region." };
242 248 }
243 249  
244   - const scoped = locationsScopedForCategoryForm(locations, partners, partnerId, regionNamesClean);
  250 + const regionNameSet = new Set(
  251 + groups.length
  252 + ? regionSelectionToGroupNames(regionSelectionClean, groups, partnerId)
  253 + : regionSelectionClean,
  254 + );
  255 +
  256 + const scoped = locationsScopedForCategoryForm(
  257 + locations,
  258 + partners,
  259 + partnerId,
  260 + regionSelectionClean,
  261 + groups,
  262 + );
245 263 const scopedIds = new Set(scoped.map((l) => l.id));
246 264  
247 265 const locationIdsParsed = [
... ... @@ -259,7 +277,7 @@ export function buildSpecifiedLocationPayload(
259 277 const loc = scoped.find((l) => l.id === id);
260 278 if (!loc) return true;
261 279 const g = (loc.groupName ?? "").trim();
262   - return !g || !regionNamesClean.includes(g);
  280 + return !g || !regionNameSet.has(g);
263 281 });
264 282 if (locOutsideRegion) {
265 283 return {
... ... @@ -329,27 +347,49 @@ export function hydrateTemplateScopeFromDto(
329 347 return { partnerId, regionNames, locationIds };
330 348 }
331 349  
  350 +/** 区域多选值 → fl_group.Id(兼容 value 为 Id 或 groupName) */
332 351 export function regionNamesToGroupIds(
333   - names: string[],
  352 + selection: string[],
334 353 groups: GroupListItem[],
335 354 partnerId?: string,
336 355 ): string[] {
337 356 const pid = (partnerId ?? "").trim();
338 357 const out: string[] = [];
339 358 const seen = new Set<string>();
340   - for (const name of names.map((x) => x.trim()).filter(Boolean)) {
  359 + for (const token of selection.map((x) => x.trim()).filter(Boolean)) {
341 360 for (const g of groups) {
342 361 if (pid && g.partnerId !== pid) continue;
  362 + const id = String(g.id ?? "").trim();
343 363 const gn = (g.groupName ?? "").trim();
344   - if (gn === name && g.id && !seen.has(g.id)) {
345   - seen.add(g.id);
346   - out.push(g.id);
  364 + if (!id || seen.has(id)) continue;
  365 + if (id === token || gn === token) {
  366 + seen.add(id);
  367 + out.push(id);
  368 + break;
347 369 }
348 370 }
349 371 }
350 372 return out;
351 373 }
352 374  
  375 +/** 区域多选值 → groupName(供门店 scope 过滤) */
  376 +export function regionSelectionToGroupNames(
  377 + selection: string[],
  378 + groups: GroupListItem[],
  379 + partnerId?: string,
  380 +): string[] {
  381 + const names: string[] = [];
  382 + const seen = new Set<string>();
  383 + for (const id of regionNamesToGroupIds(selection, groups, partnerId)) {
  384 + const gn = (groups.find((g) => g.id === id)?.groupName ?? "").trim();
  385 + if (gn && !seen.has(gn)) {
  386 + seen.add(gn);
  387 + names.push(gn);
  388 + }
  389 + }
  390 + return names;
  391 +}
  392 +
353 393 /**
354 394 * 产品保存范围:勿传 partnerId(后端会展开为公司下全部门店)。
355 395 * - 已选区域下门店全选 → 仅传 groupIds(由后端展开为该区域全部门店)
... ... @@ -366,7 +406,7 @@ export function buildProductScopeSavePayload(
366 406 const pid = partnerId.trim();
367 407 const regionNamesClean = regionNames.map((x) => x.trim()).filter(Boolean);
368 408 const groupIds = regionNamesToGroupIds(regionNamesClean, groups, pid);
369   - const scoped = locationsScopedForCategoryForm(locations, partners, pid, regionNamesClean);
  409 + const scoped = locationsScopedForCategoryForm(locations, partners, pid, regionNamesClean, groups);
370 410 const scopedIdSet = new Set(scoped.map((l) => l.id));
371 411 const locIds = [
372 412 ...new Set(
... ...
美国版/Food Labeling Management Platform/src/lib/labelFormDatePreview.ts
1 1 import type { LabelElement } from "../types/labelTemplate";
2   -import { canonicalElementType, isDateTimeDataEntryField } from "../types/labelTemplate";
  2 +import {
  3 + canonicalElementType,
  4 + elementInputKey,
  5 + isDateTimeDataEntryField,
  6 + normalizeValueSourceTypeForElement,
  7 + resolvedTypeAddForPersist,
  8 +} from "../types/labelTemplate";
3 9  
4 10 /**
5 11 * 标签创建/编辑表单:相对时间偏移 + 按模板 format 预览(与 LabelCanvas formatDateByPreset 对齐)
... ... @@ -229,3 +235,168 @@ export function resolveStoredPrintValueToDisplayText(
229 235 return `${amount} ${unit}`;
230 236 }
231 237  
  238 +function applyElementPrefix(cfg: Record<string, unknown>, body: string): string {
  239 + const prefix = String(cfg.prefix ?? cfg.Prefix ?? "");
  240 + if (!prefix) return body;
  241 + if (body.startsWith(prefix)) return body;
  242 + return `${prefix}${body}`;
  243 +}
  244 +
  245 +function dateFormatPatternForElement(el: LabelElement, cfg: Record<string, unknown>): string {
  246 + const type = canonicalElementType(el.type);
  247 + if (type === "TIME") return "HH:mm";
  248 + const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
  249 + const raw =
  250 + (typeof cfg.format === "string" && cfg.format.trim()
  251 + ? cfg.format
  252 + : typeof cfg.Format === "string" && cfg.Format.trim()
  253 + ? cfg.Format
  254 + : it === "datetime"
  255 + ? "YYYY-MM-DD HH:mm"
  256 + : "DD/MM/YYYY") || "DD/MM/YYYY";
  257 + if (isLikelyResolvedDateTimeLiteral(raw) || OFFSET_UNIT_SET.has(raw)) {
  258 + return it === "datetime" ? "YYYY-MM-DD HH:mm" : "DD/MM/YYYY";
  259 + }
  260 + return raw;
  261 +}
  262 +
  263 +function readOffsetFromElementConfig(el: LabelElement): { amount: number; unit: string } | null {
  264 + const type = canonicalElementType(el.type);
  265 + const cfg = (el.config ?? {}) as Record<string, unknown>;
  266 + if (type === "DURATION") {
  267 + const unit = String(cfg.format ?? cfg.Format ?? "Days").trim() || "Days";
  268 + const u = OFFSET_UNIT_SET.has(unit) ? unit : "Days";
  269 + const rawV =
  270 + cfg.durationValue ??
  271 + cfg.value ??
  272 + cfg.offsetDays ??
  273 + cfg.DurationValue ??
  274 + cfg.Value ??
  275 + cfg.OffsetDays;
  276 + const val = Number(rawV);
  277 + return { amount: Number.isFinite(val) ? val : 0, unit: u };
  278 + }
  279 + const od = cfg.offsetDays ?? cfg.OffsetDays;
  280 + if (od != null && String(od).trim() !== "") {
  281 + const n = Number(od);
  282 + if (Number.isFinite(n)) return { amount: n, unit: "Days" };
  283 + }
  284 + const fmt = String(cfg.format ?? cfg.Format ?? "").trim();
  285 + if (fmt && OFFSET_UNIT_SET.has(fmt)) {
  286 + const rawV = cfg.durationValue ?? cfg.value ?? cfg.DurationValue ?? cfg.Value ?? 0;
  287 + const val = Number(rawV);
  288 + return { amount: Number.isFinite(val) ? val : 0, unit: fmt };
  289 + }
  290 + return null;
  291 +}
  292 +
  293 +function resolveFromOffsetAmount(
  294 + el: LabelElement,
  295 + amount: number,
  296 + unit: string,
  297 + base: Date,
  298 +): string {
  299 + const type = canonicalElementType(el.type);
  300 + const cfg = (el.config ?? {}) as Record<string, unknown>;
  301 + const d = applyOffsetToDate(base, amount, unit);
  302 + if (type === "DATE") {
  303 + return applyElementPrefix(cfg, formatDateByPreset(dateFormatPatternForElement(el, cfg), d));
  304 + }
  305 + if (type === "TIME") {
  306 + return applyElementPrefix(cfg, formatDateByPreset("HH:mm", d));
  307 + }
  308 + return applyElementPrefix(cfg, `${amount} ${unit}`.trim());
  309 +}
  310 +
  311 +/** 与 App isUniAppDateTimeOffsetField 对齐:含 auto current date/time 等相对基准解析字段 */
  312 +export function isDateTimeLiveResolveField(el: LabelElement): boolean {
  313 + const type = canonicalElementType(el.type);
  314 + const cfg = (el.config ?? {}) as Record<string, unknown>;
  315 + if (type === "TIME" || type === "DURATION") return true;
  316 + if (type !== "DATE") return false;
  317 + const it = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
  318 + if (it === "datetime" || it === "date") return true;
  319 + const ta = resolvedTypeAddForPersist(el).trim().toLowerCase().replace(/\s+/g, " ");
  320 + if (ta === "label_duration date" || ta.includes("duration date")) return true;
  321 + if (ta === "auto_current date" || ta.includes("current date")) return true;
  322 + if (ta === "auto_current time" || ta.includes("current time")) return true;
  323 + const nameHint = `${el.elementName ?? ""} ${elementInputKey(el)}`.toLowerCase();
  324 + if (/(durationdate|duration_date|duration\s*date)/.test(nameHint)) return true;
  325 + return false;
  326 +}
  327 +
  328 +/**
  329 + * 画布预览 / 打印:按基准时刻解析 DATE/TIME/DURATION(与 App resolveElementDateTimeDisplay 一致)。
  330 + */
  331 +export function resolveElementDateTimeDisplay(
  332 + el: LabelElement,
  333 + base: Date = new Date(),
  334 +): string | null {
  335 + const type = canonicalElementType(el.type);
  336 + if (type !== "DATE" && type !== "TIME" && type !== "DURATION") return null;
  337 +
  338 + const cfg = (el.config ?? {}) as Record<string, unknown>;
  339 + const vst = normalizeValueSourceTypeForElement(el);
  340 + const inputType = String(cfg.inputType ?? cfg.InputType ?? "").toLowerCase();
  341 + const rawText = String(cfg.text ?? cfg.Text ?? "").trim();
  342 +
  343 + const fromOffsetJson = (raw: string): string | null => {
  344 + const p = tryParsePrintInputOffsetStored(raw);
  345 + if (!p) return null;
  346 + const norm = normalizeLabelFormOffsetInput(p.value);
  347 + if (norm.kind === "invalid") return null;
  348 + const amount = norm.kind === "zero" ? 0 : norm.amount;
  349 + return resolveFromOffsetAmount(el, amount, p.unit || "Days", base);
  350 + };
  351 +
  352 + const jsonResolved =
  353 + (rawText ? fromOffsetJson(rawText) : null) ??
  354 + fromOffsetJson(String(cfg.format ?? cfg.Format ?? ""));
  355 + if (jsonResolved) return jsonResolved;
  356 +
  357 + if (vst === "PRINT_INPUT") {
  358 + if (
  359 + rawText &&
  360 + !tryParsePrintInputOffsetStored(rawText) &&
  361 + !isDateTimeLiveResolveField(el)
  362 + ) {
  363 + return applyElementPrefix(cfg, rawText);
  364 + }
  365 + if (
  366 + isDateTimeLiveResolveField(el) ||
  367 + inputType === "date" ||
  368 + inputType === "datetime" ||
  369 + type === "TIME"
  370 + ) {
  371 + const off = readOffsetFromElementConfig(el);
  372 + return resolveFromOffsetAmount(el, off?.amount ?? 0, off?.unit ?? "Days", base);
  373 + }
  374 + return null;
  375 + }
  376 +
  377 + const off = readOffsetFromElementConfig(el);
  378 + if (off) return resolveFromOffsetAmount(el, off.amount, off.unit, base);
  379 + return resolveFromOffsetAmount(el, 0, "Days", base);
  380 +}
  381 +
  382 +/** 预览前:按同一基准时刻重算所有 DATE/TIME/DURATION,写入 __previewFormatted */
  383 +export function applyLiveDateTimePreviewToElements(
  384 + elements: LabelElement[],
  385 + base: Date = new Date(),
  386 +): LabelElement[] {
  387 + return elements.map((el) => {
  388 + const type = canonicalElementType(el.type);
  389 + const needsLive =
  390 + type === "DATE" ||
  391 + type === "TIME" ||
  392 + type === "DURATION" ||
  393 + isDateTimeLiveResolveField(el);
  394 + if (!needsLive) return el;
  395 + const live = resolveElementDateTimeDisplay(el, base);
  396 + if (live == null || !String(live).trim()) return el;
  397 + const cfg = { ...(el.config as Record<string, unknown>) };
  398 + cfg.__previewFormatted = live;
  399 + return { ...el, config: cfg };
  400 + });
  401 +}
  402 +
... ...
美国版/Food Labeling Management Platform/src/lib/nutritionManualEntry.ts
... ... @@ -37,29 +37,6 @@ function fixedLabelForKey(key: string): string {
37 37 return hit?.label ?? key;
38 38 }
39 39  
40   -function readFixedValueFromCfg(cfg: Record<string, unknown>, key: string): string {
41   - const direct = cfg[key];
42   - if (direct != null && String(direct).trim() !== "") return String(direct).trim();
43   - const fixedRows = Array.isArray(cfg.fixedNutrients)
44   - ? (cfg.fixedNutrients as Record<string, unknown>[])
45   - : [];
46   - const row = fixedRows.find((item) => String(item.key ?? "").trim() === key);
47   - return String(row?.value ?? "").trim();
48   -}
49   -
50   -/** 与 LabelCanvas 营养成分展示一致:Calories 行是否应出现 */
51   -function templateCaloriesDisplay(cfg: Record<string, unknown>): string {
52   - return String(cfg.calories ?? cfg.Calories ?? readFixedValueFromCfg(cfg, "calories") ?? "").trim();
53   -}
54   -
55   -function templateServingsPerContainer(cfg: Record<string, unknown>): string {
56   - return String(cfg.servingsPerContainer ?? cfg.ServingsPerContainer ?? "").trim();
57   -}
58   -
59   -function templateServingSize(cfg: Record<string, unknown>): string {
60   - return String(cfg.servingSize ?? cfg.ServingSize ?? "").trim();
61   -}
62   -
63 40 function fakeNutritionElement(cfg: Record<string, unknown>): LabelElement {
64 41 return {
65 42 id: "__nutrition_cfg__",
... ... @@ -76,22 +53,16 @@ function fakeNutritionElement(cfg: Record&lt;string, unknown&gt;): LabelElement {
76 53  
77 54 /**
78 55 * 模板中每个 NUTRITION 元素在「录入 / 批量表」中展开的列(表头为营养成分名称)。
79   - * 仅包含模板里已配置非空展示值的项,与画布预览(LabelCanvas)营养成分表一致。
  56 + * 按模板固定表结构 + 自定义行出列;数值在 Label / Bulk Add 录入,不要求模板 config 里已有 value。
80 57 */
81 58 export function listNutritionManualFieldSpecs(el: LabelElement): NutritionManualFieldSpec[] {
82 59 if (canonicalElementType(el.type) !== "NUTRITION") return [];
83 60 const cfg = (el.config ?? {}) as Record<string, unknown>;
84   - const specs: NutritionManualFieldSpec[] = [];
85   -
86   - if (templateCaloriesDisplay(cfg)) {
87   - specs.push({ subKey: "calories", columnLabel: "Calories" });
88   - }
89   - if (templateServingsPerContainer(cfg)) {
90   - specs.push({ subKey: "servingsPerContainer", columnLabel: "Servings Per Container" });
91   - }
92   - if (templateServingSize(cfg)) {
93   - specs.push({ subKey: "servingSize", columnLabel: "Serving Size" });
94   - }
  61 + const specs: NutritionManualFieldSpec[] = [
  62 + { subKey: "servingsPerContainer", columnLabel: "Servings Per Container" },
  63 + { subKey: "servingSize", columnLabel: "Serving Size" },
  64 + { subKey: "calories", columnLabel: "Calories" },
  65 + ];
95 66  
96 67 const fixedArr = Array.isArray(cfg.fixedNutrients) ? (cfg.fixedNutrients as Record<string, unknown>[]) : [];
97 68 const seen = new Set<string>();
... ... @@ -99,16 +70,12 @@ export function listNutritionManualFieldSpecs(el: LabelElement): NutritionManual
99 70 for (const row of fixedArr) {
100 71 const key = String(row.key ?? "").trim();
101 72 if (!key || seen.has(key)) continue;
102   - const v = String(row.value ?? "").trim();
103   - if (!v) continue;
104 73 seen.add(key);
105 74 const label = String(row.label ?? "").trim() || fixedLabelForKey(key);
106 75 specs.push({ subKey: key, columnLabel: label });
107 76 }
108 77 } else {
109 78 for (const item of NUTRITION_FIXED_ITEMS) {
110   - const v = readFixedValueFromCfg(cfg, item.key).trim();
111   - if (!v) continue;
112 79 specs.push({ subKey: item.key, columnLabel: item.label });
113 80 }
114 81 }
... ... @@ -116,8 +83,6 @@ export function listNutritionManualFieldSpecs(el: LabelElement): NutritionManual
116 83 for (const ex of nutritionExtraRowsFromCfg(cfg)) {
117 84 const id = String(ex.id ?? "").trim();
118 85 if (!id) continue;
119   - const value = String(ex.value ?? "").trim();
120   - if (!value) continue;
121 86 const name = ex.name.trim() || "Other";
122 87 specs.push({ subKey: `extra:${id}:value`, columnLabel: name });
123 88 }
... ... @@ -128,57 +93,76 @@ export function listNutritionElements(elements: LabelElement[]): LabelElement[]
128 93 return (elements ?? []).filter((el) => canonicalElementType(el.type) === "NUTRITION");
129 94 }
130 95  
131   -/** 从模板 config 初始化手动录入 map */
132   -export function nutritionManualValuesFromTemplateConfig(el: LabelElement): Record<string, string> {
133   - const cfg = (el.config ?? {}) as Record<string, unknown>;
  96 +/** 从模板 config 初始化手动录入 map(模板不含数值,初始均为空) */
  97 +export function nutritionManualValuesFromTemplateConfig(_el: LabelElement): Record<string, string> {
  98 + const specs = listNutritionManualFieldSpecs(_el);
134 99 const out: Record<string, string> = {};
135   - const specs = listNutritionManualFieldSpecs(el);
136 100 for (const s of specs) {
137   - if (s.subKey === "calories") {
138   - out.calories = String(cfg.calories ?? cfg.Calories ?? readFixedValueFromCfg(cfg, "calories") ?? "").trim();
139   - continue;
140   - }
141   - if (s.subKey === "servingsPerContainer") {
142   - out.servingsPerContainer = String(cfg.servingsPerContainer ?? cfg.ServingsPerContainer ?? "").trim();
143   - continue;
144   - }
145   - if (s.subKey === "servingSize") {
146   - out.servingSize = String(cfg.servingSize ?? cfg.ServingSize ?? "").trim();
147   - continue;
148   - }
149   - if (s.subKey.startsWith("extra:") && s.subKey.endsWith(":value")) {
150   - const id = s.subKey.slice("extra:".length, -":value".length);
151   - const ex = nutritionExtraRowsFromCfg(cfg).find((r) => r.id === id);
152   - out[s.subKey] = (ex?.value ?? "").trim();
153   - continue;
154   - }
155   - out[s.subKey] = readFixedValueFromCfg(cfg, s.subKey);
  101 + out[s.subKey] = "";
156 102 }
157 103 return out;
158 104 }
159 105  
160   -function pickManual(
161   - manual: Record<string, string>,
162   - subKey: string,
163   - baseCfg: Record<string, unknown>,
164   -): string {
165   - const m = String(manual[subKey] ?? "").trim();
166   - if (m !== "") return m;
167   - if (subKey === "calories") {
168   - return String(baseCfg.calories ?? baseCfg.Calories ?? readFixedValueFromCfg(baseCfg, "calories") ?? "").trim();
169   - }
170   - if (subKey === "servingsPerContainer") {
171   - return String(baseCfg.servingsPerContainer ?? baseCfg.ServingsPerContainer ?? "").trim();
172   - }
173   - if (subKey === "servingSize") {
174   - return String(baseCfg.servingSize ?? baseCfg.ServingSize ?? "").trim();
175   - }
176   - if (subKey.startsWith("extra:") && subKey.endsWith(":value")) {
177   - const id = subKey.slice("extra:".length, -":value".length);
178   - const ex = nutritionExtraRowsFromCfg(baseCfg).find((r) => r.id === id);
179   - return (ex?.value ?? "").trim();
  106 +function pickManual(manual: Record<string, string>, subKey: string): string {
  107 + return String(manual[subKey] ?? "").trim();
  108 +}
  109 +
  110 +/**
  111 + * 模板编辑器持久化:仅保留表结构(单位、自定义行名称),清除所有展示数值。
  112 + */
  113 +export function sanitizeNutritionTemplateConfig(
  114 + cfg: Record<string, unknown>,
  115 +): Record<string, unknown> {
  116 + const out: Record<string, unknown> = { ...cfg };
  117 + out.calories = "";
  118 + out.servingsPerContainer = "";
  119 + out.servingSize = "";
  120 + delete out.Calories;
  121 + delete out.ServingsPerContainer;
  122 + delete out.ServingSize;
  123 +
  124 + const baseFixed = Array.isArray(out.fixedNutrients)
  125 + ? (out.fixedNutrients as Record<string, unknown>[])
  126 + : [];
  127 + const fixedArr = NUTRITION_FIXED_ITEMS.map((item) => {
  128 + const baseRow = baseFixed.find((r) => String(r.key ?? "").trim() === item.key);
  129 + const unit = String(baseRow?.unit ?? item.defaultUnit ?? "").trim();
  130 + return {
  131 + key: item.key,
  132 + label: String(baseRow?.label ?? item.label),
  133 + value: "",
  134 + unit,
  135 + };
  136 + });
  137 + out.fixedNutrients = fixedArr;
  138 +
  139 + for (const item of NUTRITION_FIXED_ITEMS) {
  140 + out[item.key] = "";
  141 + const unit = fixedArr.find((r) => r.key === item.key)?.unit;
  142 + if (unit) out[`${item.key}Unit`] = unit;
  143 + else delete out[`${item.key}Unit`];
180 144 }
181   - return readFixedValueFromCfg(baseCfg, subKey);
  145 +
  146 + out.extraNutrients = nutritionExtraRowsFromCfg(out).map((ex) => ({
  147 + id: ex.id,
  148 + name: ex.name,
  149 + value: "",
  150 + unit: ex.unit,
  151 + }));
  152 + return out;
  153 +}
  154 +
  155 +/** 模板编辑器:清除所有 NUTRITION 元素 config 中的展示数值 */
  156 +export function sanitizeNutritionElementsForTemplateEditor(
  157 + elements: LabelElement[],
  158 +): LabelElement[] {
  159 + return (elements ?? []).map((el) => {
  160 + if (canonicalElementType(el.type) !== "NUTRITION") return el;
  161 + return {
  162 + ...el,
  163 + config: sanitizeNutritionTemplateConfig((el.config ?? {}) as Record<string, unknown>),
  164 + };
  165 + });
182 166 }
183 167  
184 168 /**
... ... @@ -194,7 +178,7 @@ export function mergeNutritionManualIntoConfig(
194 178 const specSubKeys = new Set(specs.map((s) => s.subKey));
195 179  
196 180 if (specSubKeys.has("calories")) {
197   - const cal = pickManual(manual, "calories", baseCfg);
  181 + const cal = pickManual(manual, "calories");
198 182 if (cal) cfg.calories = cal;
199 183 else {
200 184 delete cfg.calories;
... ... @@ -206,14 +190,14 @@ export function mergeNutritionManualIntoConfig(
206 190 }
207 191  
208 192 if (specSubKeys.has("servingsPerContainer")) {
209   - cfg.servingsPerContainer = pickManual(manual, "servingsPerContainer", baseCfg);
  193 + cfg.servingsPerContainer = pickManual(manual, "servingsPerContainer");
210 194 } else {
211 195 cfg.servingsPerContainer = "";
212 196 delete cfg.ServingsPerContainer;
213 197 }
214 198  
215 199 if (specSubKeys.has("servingSize")) {
216   - cfg.servingSize = pickManual(manual, "servingSize", baseCfg);
  200 + cfg.servingSize = pickManual(manual, "servingSize");
217 201 } else {
218 202 cfg.servingSize = "";
219 203 delete cfg.ServingSize;
... ... @@ -226,7 +210,7 @@ export function mergeNutritionManualIntoConfig(
226 210 for (const s of specs) {
227 211 if (["calories", "servingsPerContainer", "servingSize"].includes(s.subKey)) continue;
228 212 if (s.subKey.startsWith("extra:")) continue;
229   - const v = pickManual(manual, s.subKey, baseCfg);
  213 + const v = pickManual(manual, s.subKey);
230 214 const baseRow = baseFixed.find((r) => String(r.key ?? "").trim() === s.subKey);
231 215 const unit = String(
232 216 baseRow?.unit ?? NUTRITION_FIXED_ITEMS.find((x) => x.key === s.subKey)?.defaultUnit ?? "",
... ... @@ -253,7 +237,7 @@ export function mergeNutritionManualIntoConfig(
253 237 newExtras.push({
254 238 id,
255 239 name: (base?.name ?? s.columnLabel).trim() || "Other",
256   - value: pickManual(manual, s.subKey, baseCfg),
  240 + value: pickManual(manual, s.subKey),
257 241 unit: String(base?.unit ?? "").trim(),
258 242 });
259 243 }
... ...
美国版/Food Labeling Management Platform/src/lib/productCodeValueTemplate.ts
... ... @@ -5,6 +5,22 @@ import {
5 5 resolvedTypeAddForPersist,
6 6 } from "../types/labelTemplate";
7 7  
  8 +function normalizeLabelPanelTypeAdd(el: LabelElement): string {
  9 + return resolvedTypeAddForPersist(el).trim().toLowerCase().replace(/\s+/g, " ");
  10 +}
  11 +
  12 +/** Label 面板 **Label Name**(typeAdd 如 label_Label Name) */
  13 +export function isTemplateLabelNameElement(el: LabelElement): boolean {
  14 + if (isTemplateSectionPersistedType(el)) return false;
  15 + return normalizeLabelPanelTypeAdd(el) === "label_label name";
  16 +}
  17 +
  18 +/** Label 面板 **Label Type**(typeAdd 如 label_Label Type) */
  19 +export function isTemplateLabelTypeElement(el: LabelElement): boolean {
  20 + if (isTemplateSectionPersistedType(el)) return false;
  21 + return normalizeLabelPanelTypeAdd(el) === "label_label type";
  22 +}
  23 +
8 24 /** Template 面板中的条形码 / 二维码(typeAdd 如 template_Barcode、template_QR Code) */
9 25 export function isTemplateSectionBarcodeOrQrElement(el: LabelElement): boolean {
10 26 if (!isTemplateSectionPersistedType(el)) return false;
... ... @@ -36,6 +52,21 @@ export function buildTemplateBarcodeQrDefaultsFromCodeValue(
36 52 return out;
37 53 }
38 54  
  55 +/** 将 Label Name 输入 / 标签类型名写入 elementId → 字符串,供 templateProductDefaults / 预览合并 */
  56 +export function buildTemplateLabelBindingDefaults(
  57 + elements: LabelElement[],
  58 + bindings: { labelName?: string | null; labelTypeName?: string | null },
  59 +): Record<string, string> {
  60 + const labelName = String(bindings.labelName ?? "").trim();
  61 + const labelTypeName = String(bindings.labelTypeName ?? "").trim();
  62 + const out: Record<string, string> = {};
  63 + for (const el of elements) {
  64 + if (labelName && isTemplateLabelNameElement(el)) out[el.id] = labelName;
  65 + if (labelTypeName && isTemplateLabelTypeElement(el)) out[el.id] = labelTypeName;
  66 + }
  67 + return out;
  68 +}
  69 +
39 70 /** 合并 codeValue 到元素 config.data(用于画布预览) */
40 71 export function applyProductCodeValueToLabelElements(
41 72 elements: LabelElement[],
... ...
美国版/Food Labeling Management Platform/src/services/labelTemplateService.ts
... ... @@ -288,6 +288,7 @@ function buildLabelTemplateScopeBody(input: LabelTemplateCreateInput): Record&lt;st
288 288 showRuler: input.showRuler ?? true,
289 289 showGrid: input.showGrid ?? true,
290 290 border: normalizeTemplateBorder(input.border),
  291 + printOrientation: normalizePrintOrientation(input.printOrientation),
291 292 state: input.state ?? true,
292 293 elements: input.elements,
293 294 };
... ...
美国版/Food Labeling Management Platform/src/types/labelTemplate.ts
... ... @@ -10,12 +10,12 @@ export type Unit = &#39;cm&#39; | &#39;inch&#39;;
10 10 export type AppliedLocation = 'ALL' | 'SPECIFIED';
11 11 export type Rotation = 'horizontal' | 'vertical';
12 12  
13   -/** 模板打印方向:横打 / 竖打(纸张 W×H 不变,竖打时控件整体旋转 90° 打印) */
  13 +/** 模板打印方向:横打 / 竖打(纸张 W×H 不变,横打时内容整体旋转 90° 打印) */
14 14 export type PrintOrientation = 'horizontal' | 'vertical';
15 15  
16 16 export function normalizePrintOrientation(raw: unknown): PrintOrientation {
17 17 const v = String(raw ?? '').trim().toLowerCase();
18   - return v === 'vertical' ? 'vertical' : 'horizontal';
  18 + return v === 'horizontal' ? 'horizontal' : 'vertical';
19 19 }
20 20  
21 21 export type Border = 'none' | 'line' | 'dotted';
... ... @@ -343,7 +343,7 @@ export function createDefaultTemplate(id?: string): LabelTemplate {
343 343 showRuler: true,
344 344 showGrid: true,
345 345 border: 'none',
346   - printOrientation: 'horizontal',
  346 + printOrientation: 'vertical',
347 347 elements: [],
348 348 };
349 349 }
... ... @@ -420,22 +420,12 @@ export function createDefaultElement(type: ElementType, x = 20, y = 20): LabelEl
420 420 nutritionTitleFontSize: 16,
421 421 servingsPerContainer: '',
422 422 servingSize: '',
423   - calories: '120',
424   - fat: '5',
425   - protein: '3',
426   - carbs: '10',
  423 + calories: '',
427 424 layout: 'standard',
428 425 fixedNutrients: NUTRITION_FIXED_ITEMS.map((item) => ({
429 426 key: item.key,
430 427 label: item.label,
431   - value:
432   - item.key === 'fat'
433   - ? '5'
434   - : item.key === 'protein'
435   - ? '3'
436   - : item.key === 'carbs'
437   - ? '10'
438   - : '',
  428 + value: '',
439 429 unit: item.defaultUnit ?? '',
440 430 })),
441 431 extraNutrients: [],
... ...