feat(报价单): 新增商品卡片并入栅格并改为手填比例
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

新增商品改为栅格第一格的卡片(与商品卡片同版式):搜索框 + 右上角 X、
成本/售价同排自适应、销售比例手填、右下角保存报价单;空明细也能看到。

销售比例按手填值落库,不再由成本/售价反算;填了须 >=100,否则拦下。
This commit is contained in:
雨天
2026-10-21 09:42:23 +08:00
parent b26a7c6e15
commit 173ffccb7e
7 changed files with 432 additions and 179 deletions
@@ -0,0 +1,55 @@
# 报价单「新增商品」卡片并入栅格(版式对齐)
- 日期:2026-10-21
- 来源:开发者附两张截图(现版式 vs 目标版式)——「这个图是我们现在的报价单的布局我现在需要你修改一下 布局调整为[目标图]这种 当前点击新增商品 出现的输入卡片 完全不像这种」
## 1. 改前(实测)
查看展开的报价单明细(`src/pages/customers/QuoteVersionManagement.tsx`):
| # | 事实 |
|---|---|
| F1 | 点「+ 新增商品」(`setInlineAddOpen(true)`)在**栅格上方**插一整行独立面板(`mb-3 app-surface ... p-3`),宽度撑满,与下方商品卡片**版式完全不同** |
| F2 | 面板内是「商品」标签 + 商品下拉 + 清除 ×、规格/单位文字行、成本/售价/比例三个输入、「保存」+「取消」两个按钮 |
| F3 | 商品卡片是 `grid-cols-1 md:grid-cols-2 xl:grid-cols-4` 里的 `QuoteItemCard`(标题 + 分类/状态标签 + 删除图标、规格/单位行、成本/售价、比例、无按钮) |
| F4 | 面板里的**销售比例输入框是死输入**:`inlineDraft.markup_ratio` 只在输入与重置处出现,提交(`appendQuoteSheetItemsApi`)**从未使用** |
| F5 | 明细为空时直接渲染空态文案,**即使卡片已打开也看不到它** |
## 2. 方案(只改版式,不改提交口径)
1. **位置**:新增卡片改为栅格**第一格**(`inlineAddOpen && expandedEditable` 时渲染,在已排序的商品卡片之前)。
2. **版式**(与 `QuoteItemCard` 同宽同风格:`app-surface rounded-xl border p-3 space-y-2 min-w-0`):
- 顶部:商品搜索下拉(`SearchableSelect` compact,占满除删除按钮外的宽度)+ 右上角 **X**(`quotes.action.delete` 作 title/aria,取消并清空草稿);
- 成本价 / 销售价一行(`w-20`,右对齐,`0.00` 占位);
- 销售比例一行:**手工填写**(2026-10-21 开发者「销售比例是自己填写的 不能智能填写」)—— 不从成本/售价反算;空 = 未设置,则显占位「如 120」;填了必须 ≥ 100,否则拦下并提示 `quotes.toast.invalidSaleRatio`(与弹窗保存同口径);
- 右下角绿色按钮「**保存报价单**」(复用既有词条 `quotes.form.saveCreate`)。
3. **空态**:`inlineAddOpen || 有明细` 就渲染栅格 ⇒ 空报价单也能看到新增卡片;无明细且未打开仍显示原空态文案。
4. **文案**:仅新增一个 placeholder `quotes.detail.searchProductPh`(zh「搜索商品名称」/ en / id)—— 取自开发者截图原文;其余词条全部复用。
5. **保存逻辑**:从 JSX 内联抽为 `saveInlineItem()`(与改前**同一条** `appendQuoteSheetItemsApi` 通道、同样的售价 > 0 校验、同样的成功/失败提示与明细刷新)。
6. **卡片内输入框版式(2026-10-21 二次/三次调整,附局部截图)**:
- 成本价 / 销售价**强制同一行**:价格行去掉 `flex-wrap`,两个字段各 `flex-1 min-w-0`、输入框 `w-full min-w-0 flex-1` 自适应伸缩(窄列也不换行);标签与 `¥` 用 `shrink-0` 不被压缩,数值右对齐;
- 销售比例框 `w-24`(居中);
- 比例标签不再摘掉百分号 —— 保留「**销售比例(%)**」全称,框后仍跟 `%`(与截图逐字一致);
- **商品卡片与新增卡片用同一套**(两张卡片并排时字段宽/对齐/标签必须一样)。
7. **销售比例回归「手填」(2026-10-21 开发者纠正)**:两张卡片的比例都改为**可编辑输入框**,值取服务端 `markup_ratio` 反推的「销售比例」文本(`quoteSaleRatioTextFromMarkup`),**不再由成本/售价实时推算**;
保存时按手填值落库:
- 卡片行保存 → `buildSheetItemsPayload` 的 `override.markupRatio`(旧写法在这里用 `quoteSaleRatio(cost, sale)` **反算覆盖**用户填的值,已删);
- 新增卡片 → `appendQuoteSheetItemsApi` 带 `markup_ratio`;
- 未改比例时原样回传服务端值(避开「反推 → 再反算」的舍入把数据改掉)。
## 3. 非目标
- 不改商品卡片(`QuoteItemCard`)的版式与保存方式(失焦提交)。
- 不改 `append-items` 接口、判重口径(同 SKU)与任何服务端行为。
- **一次只开一张新增卡片**(再点「+ 新增商品」不叠加);目标截图里并列两张空卡片暂不实现。
## 4. 验收
1. 点「+ 新增商品」⇒ 栅格第一格出现新增卡片,宽高与商品卡片同一栅格列,不再占整行。
2. 卡片内可搜索/选择商品;选中后自动带出规格/单位(仍随 append 提交 `unit`)。
3. 销售比例是**手填输入框**:不从成本/售价自动填写;填了 < 100 或非数字 ⇒ 拦下、提示且恢复服务端值;未改时原值不被舍入改写;标签为「销售比例(%)」。
4. 成本价与销售价**始终同一行**(窄列也不换行):输入框随列宽伸缩,标签不被压缩。
5. 售价 ≤ 0 时保存被拦(沿用 `quotes.toast.invalidPrice` 提示);成功后卡片关闭、明细刷新。
6. 右上角 X 关闭卡片并清空草稿(下次打开是空态)。
7. 明细为空的报价单,打开卡片后仍能看到卡片(不再只显示空态)。
8. `npm run typecheck` 通过;`i18n.test.ts`(三语键对齐)与报价单相关用例全绿。
+1
View File
@@ -131,6 +131,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
**按品名兜底取 SKU 必须规格消歧、多义拒绝猜测**(2026-10-16,真库复现的静默扣错):订单行/拣货行**没有 `sku_code`** 时系统按**品名**去 `product_catalog` 反查 SKU,而原实现是普通 JOIN、**完全不看规格** ⇒ 同名不同规格是两行时取到哪行由执行计划决定,实测把「客户要 1箱24瓶」的单扣到了「1箱12瓶」那个 SKU 的批次(**静默扣错库存**,两规格成本价常不同 ⇒ 订单成本/毛利也跟着错;普通 JOIN 还会让外层行翻倍)。口径:**先按规格消歧**(`public.norm_spec`,与抵扣选批次同一份归一实现)、**仍多义就拒绝猜测**(返回 NULL)、**同名唯一时照旧**。实现收进唯一实现 `catalogSkuBySpecJoin` 并替换 5 处调用点(`inventoryOutboundService` 3 处、`pickingService` 2 处)。见 [20261016-按品名兜底取SKU必须规格消歧.md](./20261016-按品名兜底取SKU必须规格消歧.md)。
**录单员(`operator`)仅见自己录的订单**:开发者「录单员只能看到自己录的订单,看不到其他人的订单」—— 判定只认 `orders.created_by`(空 `created_by` 的历史单 operator **看不到**;**不做**"参与过就放行"的参与制,管理员转单/他人配送按 created_by 一刀切,参与制另立需求)。**只锁列表=漏**:Web 详情/改明细/导出/打印数据源走 `/api/data/query`(`supabase.from('orders')`),不经订单 workflow 路由 ⇒ 分三层收口:① `orderManagementQueryService` 在既有 `baseWhere` 追加 `o.created_by = $n`(stats/count/list 同一个 where)② `assertOrderAccess`(`assertOrderCodeAccess`/状态推进/删单/回收站共用同一实现)追加 `assertOperatorOwnOrder`,`admin`/`super_admin` 早退不受限 ③ `/api/data` 对 `orders`/`order_items` 注入 `created_by` 行级可信表达式。状态链/分配/财务/表结构**未动**,见 [20261019-录单员仅见自己录的订单.md](./20261019-录单员仅见自己录的订单.md)。
**小程序送货单图片增加「生产时间」列**:开发者「选中分享送货单的图片时 可以加一个时间列 也就是生产时间 送的这个商品使用的批次的生产时间 多个批次的就是多个生产时间就行」——生产日期只在**批次**(`inventory.production_date`),「这一单实际用掉哪几批」的唯一事实源是出库流水 `inventory_logs`(`related_order_code` + `sku_code` + `batch_no`,类型 `picking_out`/`delivery_loading_out`/`retail_out`);出库走 FIFO 可能跨多批 ⇒ 日期 1~N 个,单元格内**逐行堆叠**、行高随之变高(`deliveryNoteHeight` 支持传 items)。**未出库不猜批次(只要其它行有日期,该行就留空)**;**保险:后端未下发该字段或整单无日期 ⇒ 整列不渲染**,退回原 7 列版式(不让客户看到一整列空白);有数据时 7 列变 8 列(编号/产品/单位/总数量/单价/金额/备注/**生产时间**,生产时间放最后一列,列宽合计仍 920)。订单详情接口只**新增** `batch_production_dates: string[]` 字段;**免登录 H5 送货单本轮不同步**;成本价/FIFO/账本/状态链一行未动,见 [20261020-送货单图片增加生产时间列.md](./20261020-送货单图片增加生产时间列.md)。
**报价单「新增商品」卡片并入栅格**:开发者附截图「当前点击新增商品出现的输入卡片完全不像这种」—— 原来点「+ 新增商品」是在栅格**上方**插一整行独立面板(商品下拉 + 规格/单位行 + 成本/售价/比例 + 保存/取消),现改为与 `QuoteItemCard` 同宽同风格的**栅格第一格**:顶部商品搜索框 + 右上角 X(取消并清草稿)、成本/售价一行、销售比例一行(**手工填写**,2026-10-21 开发者纠正「不能智能填写」:不从成本/售价反算,保存按手填值落库)、右下角「保存报价单」;明细为空时也能看到该卡片。**提交口径不变**(同一条 `appendQuoteSheetItemsApi` + 售价 > 0 校验);仅新增一个 placeholder `quotes.detail.searchProductPh`(三语,取自截图原文);一次只开一张新增卡片,见 [20261021-报价单新增商品卡片并入栅格.md](./20261021-报价单新增商品卡片并入栅格.md)。
## 全量对齐与改造方案(2026-09-28)
+1
View File
@@ -75,6 +75,7 @@ export const quotes: MessageDict = {
'detail.showingCount': 'Showing {shown} / {total} products',
'detail.filterProductPh': 'Filter products (name/code/spec/brand)',
'detail.filterCategoryPh': 'Filter categories (name/code)',
'detail.searchProductPh': 'Search product name',
'detail.clearProductAria': 'Clear product filter',
'detail.clearCategoryAria': 'Clear category filter',
'detail.switchCustomerConfirm': 'Switch to customer "{customer}"? The current quote will be copied into a new one for this customer, then switched automatically.',
+1
View File
@@ -77,6 +77,7 @@ export const quotes: MessageDict = {
'detail.showingCount': 'Menampilkan {shown} / {total} produk',
'detail.filterProductPh': 'Filter produk (nama/kode/spek/merek)',
'detail.filterCategoryPh': 'Filter kategori (nama/kode)',
'detail.searchProductPh': 'Cari nama produk',
'detail.clearProductAria': 'Hapus filter produk',
'detail.clearCategoryAria': 'Hapus filter kategori',
'detail.switchCustomerConfirm': 'Beralih ke pelanggan "{customer}"? Penawaran ini akan disalin menjadi penawaran baru untuk pelanggan tersebut, lalu beralih otomatis.',
+1
View File
@@ -74,6 +74,7 @@ export const quotes: MessageDict = {
'detail.showingCount': '显示 {shown} / {total} 个商品',
'detail.filterProductPh': '筛选商品(名称/编码/规格/品牌)',
'detail.filterCategoryPh': '筛选分类(名称/编码)',
'detail.searchProductPh': '搜索商品名称',
'detail.clearProductAria': '清空商品筛选',
'detail.clearCategoryAria': '清空分类筛选',
'detail.switchCustomerConfirm': '确认切换到客户「{customer}」?将复制当前报价单为该客户新建一张,成功后自动切到新单。',
@@ -0,0 +1,126 @@
/**
* 报价单「新增商品」卡片并入栅格(2026-10-21 开发者附截图要求)。
*
* 改前:点「+ 新增商品」在栅格**上方**插一整行独立面板(商品下拉 + 规格/单位 + 成本/售价/比例 + 保存/取消)。
* 改后:与商品卡片同宽同风格的**栅格第一格**(搜索框 + 右上角 X、成本/售价、只读比例、右下角「保存报价单」)。
*
* 设计:docs/design/20261021-报价单新增商品卡片并入栅格.md
*/
import { readFileSync } from 'fs';
import { describe, expect, it } from 'vitest';
const src = readFileSync(new URL('./QuoteVersionManagement.tsx', import.meta.url), 'utf8');
const GRID_MARK = 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 overflow-visible';
const INLINE_MARK = '{inlineAddOpen && expandedEditable ? (';
const MAP_MARK = '{filteredExpandedItems.map((item) => {';
/** 新增卡片那段 JSX(从卡片开头到商品卡片 map 之前) */
function inlineCardBlock(): string {
const start = src.indexOf(INLINE_MARK);
const end = src.indexOf(MAP_MARK);
expect(start, '未找到新增卡片').toBeGreaterThan(-1);
expect(end, '未找到商品卡片列表').toBeGreaterThan(-1);
return src.slice(start, end);
}
describe('报价单「新增商品」卡片并入栅格', () => {
it('卡片渲染在栅格内、且排在商品卡片之前(不再单独占一整行)', () => {
const gridIdx = src.indexOf(GRID_MARK);
const inlineIdx = src.indexOf(INLINE_MARK);
const mapIdx = src.indexOf(MAP_MARK);
expect(gridIdx).toBeGreaterThan(-1);
expect(inlineIdx).toBeGreaterThan(gridIdx);
expect(mapIdx).toBeGreaterThan(inlineIdx);
});
it('明细为空时打开卡片也能看到(栅格条件含 inlineAddOpen)', () => {
expect(src).toContain('{inlineAddOpen || filteredExpandedItems.length > 0 ? (');
});
it('版式与商品卡片同款:同一套容器类 + 搜索框 + 取消 X', () => {
const block = inlineCardBlock();
expect(block).toContain('app-surface rounded-xl border');
expect(block).toContain('<SearchableSelect');
expect(block).toContain('onClick={cancelInlineAdd}');
expect(block).toContain('<X className="w-4 h-4" />');
expect(block).toContain("placeholder={t('quotes.detail.searchProductPh')}");
// 旧版「整行面板」的标志性尺寸类不再出现
expect(block).not.toContain('className="mb-3 app-surface rounded-xl border p-3 space-y-2 overflow-visible"');
});
it('保存按钮复用既有词条「保存报价单」,且仍在卡片末尾', () => {
const block = inlineCardBlock();
expect(block).toContain("t('quotes.form.saveCreate')");
expect(block.indexOf("t('quotes.form.saveCreate')")).toBeGreaterThan(block.indexOf('<SearchableSelect'));
});
it('销售比例是**手填**字段:两张卡片都是可编辑输入框,不从成本/售价反算', () => {
const block = inlineCardBlock();
// 新增卡片:比例输入框绑 draft.markup_ratio,带手填占位「如 120」
expect(block).toContain('value={inlineDraft.markup_ratio}');
expect(block).toContain("placeholder={t('quotes.form.saleRatioPh')}");
// 商品卡片:比例用独立的 ratioDraft(可编辑),不再是只读 div
expect(src).toContain('const [ratioDraft, setRatioDraft] = React.useState(quoteSaleRatioTextFromMarkup(item.markup_ratio));');
expect(src).toContain('value={ratioDraft}');
// 页面里不得再出现「按成本/售价反算比例」的智能填写(该 helper 已移出本页)
expect(src).not.toContain('inlineRatioText');
expect(src).not.toContain('quoteSaleRatio(');
});
it('保存时按手填值落库:不再由成本/售价反算 markup_ratio', () => {
// 行保存:override 直接给 markupRatio,而不是 quoteSaleRatio(cost, sale) 反算
const payloadIdx = src.indexOf('const buildSheetItemsPayload = (');
expect(payloadIdx).toBeGreaterThan(-1);
const payloadFn = src.slice(payloadIdx, payloadIdx + 900);
expect(payloadFn).toContain('markup_ratio: hit ? override!.markupRatio ?? null');
expect(payloadFn).not.toContain('quoteSaleRatio(');
// 新增卡片:手填比例 → markupRatioFromQuoteSaleRatio → append 请求
const appendIdx = src.indexOf('const saveInlineItem = async () => {');
const appendFn = src.slice(appendIdx, appendIdx + 1800);
expect(appendFn).toContain('markup_ratio: ratioValue == null ? null : markupRatioFromQuoteSaleRatio(ratioValue)');
// 比例 < 100 / 非数字 ⇒ 与弹窗同口径拦截
expect(appendFn).toContain("t('quotes.toast.invalidSaleRatio')");
});
it('保存仍走同一条 append 通道 + 售价 > 0 校验(口径未变)', () => {
const fnIdx = src.indexOf('const saveInlineItem = async () => {');
expect(fnIdx).toBeGreaterThan(-1);
const fn = src.slice(fnIdx, fnIdx + 1400);
expect(fn).toContain('appendQuoteSheetItemsApi(expandedCode, [');
expect(fn).toContain('if (!(sale > 0))');
expect(fn).toContain("t('quotes.toast.invalidPrice')");
});
it('成本价/销售价**同一行**且自适应:输入框 flex-1 + min-w-0,不换行', () => {
const block = inlineCardBlock();
// 价格行不再是 flex-wrap(窄列也强排一行)
expect(block).toContain('<div className="flex items-center gap-x-2">');
expect(block).not.toContain('flex flex-wrap items-center gap-x-3 gap-y-1.5');
// 两张卡片的价格输入框都是可伸缩的(w-full + min-w-0 + flex-1)
expect(block.match(/app-input app-focus-ring w-full min-w-0 flex-1[^"]*text-right/g) || []).toHaveLength(2);
expect(src.match(/app-input app-focus-ring w-full min-w-0 flex-1[^"]*text-right/g) || []).toHaveLength(4);
// 标签不参与压缩(shrink-0),否则会被挤成半个字
expect(block.match(/className="shrink-0 text-slate-400">¥/g) || []).toHaveLength(2);
});
it('输入框版式与商品卡片一致:比例框 w-24、标签保留「(%)」', () => {
const block = inlineCardBlock();
expect(block.match(/app-input app-focus-ring w-24[^"]*text-center/g) || []).toHaveLength(1);
// 标签直接用「销售比例(%)」全文,不再摘掉百分号(截图:标签带(%),框后另有 %)
expect(block).toContain("<span className=\"whitespace-nowrap\">{t('quotes.form.col.saleRatio')}</span>");
expect(src).not.toContain('replace(/(%)$/, \'\')');
// 商品卡片用同一套:比例标签全称 + 比例框 w-24 居中
expect(src).toContain("ratio: t('quotes.form.col.saleRatio'),");
expect(src.match(/app-input app-focus-ring w-24[^"]*text-center/g) || []).toHaveLength(2);
});
it('取消卡片会把草稿清空(下次打开是空态)', () => {
const fnIdx = src.indexOf('const cancelInlineAdd = () => {');
expect(fnIdx).toBeGreaterThan(-1);
const fn = src.slice(fnIdx, fnIdx + 400);
expect(fn).toContain('setInlineAddOpen(false)');
expect(fn).toContain('setInlineDraft({ ...EMPTY_INLINE_DRAFT })');
expect(src).toContain("const EMPTY_INLINE_DRAFT = { sku_code: '', spec: '', unit: '', cost_price: '', sale_price: '', markup_ratio: '' };");
});
});
+247 -179
View File
@@ -56,7 +56,6 @@ import { PageFilterToolbar } from '../../components/ui/PagePrimitives';
import { useT } from '../../i18n';
import {
markupRatioFromQuoteSaleRatio,
quoteSaleRatio,
quoteSaleRatioTextFromMarkup,
salePriceFromQuoteRatio,
} from '../../utils/quotePriceRatio';
@@ -297,6 +296,8 @@ const QuoteLineEditorRow = React.memo<QuoteLineEditorRowProps>(({
));
const moneyText = (value: unknown) => (Number(value) || 0).toFixed(2);
/** 新增商品卡片:清空草稿(比例是手填字段,必须一并清) */
const EMPTY_INLINE_DRAFT = { sku_code: '', spec: '', unit: '', cost_price: '', sale_price: '', markup_ratio: '' };
interface QuoteItemCardProps {
item: QuoteExpandedItem;
@@ -309,6 +310,7 @@ interface QuoteItemCardProps {
cost: string;
sale: string;
ratio: string;
ratioPh: string;
spec: string;
unit: string;
enabled: string;
@@ -316,7 +318,14 @@ interface QuoteItemCardProps {
delete: string;
emDash: string;
};
onSavePrice: (item: QuoteExpandedItem, index: number, costPrice: number, salePrice: number) => void;
onSavePrice: (
item: QuoteExpandedItem,
index: number,
costPrice: number,
salePrice: number,
markupRatio: number | null
) => void;
onInvalidRatio: () => void;
onDelete: (item: QuoteExpandedItem, index: number) => void;
}
@@ -333,43 +342,71 @@ const QuoteItemCard = React.memo<QuoteItemCardProps>(({
duplicateLabel,
labels,
onSavePrice,
onInvalidRatio,
onDelete,
}) => {
const [costDraft, setCostDraft] = React.useState(moneyText(item.cost_price));
const [saleDraft, setSaleDraft] = React.useState(moneyText(item.sale_price));
/** 销售比例:**手工填写**(不从售价/成本反算),存的是页面上的“销售比例”(如 166.67) */
const [ratioDraft, setRatioDraft] = React.useState(quoteSaleRatioTextFromMarkup(item.markup_ratio));
const wasSavingRef = React.useRef(saving);
React.useEffect(() => {
setCostDraft(moneyText(item.cost_price));
setSaleDraft(moneyText(item.sale_price));
}, [item.sku_code, item.cost_price, item.sale_price]);
setRatioDraft(quoteSaleRatioTextFromMarkup(item.markup_ratio));
}, [item.sku_code, item.cost_price, item.sale_price, item.markup_ratio]);
React.useEffect(() => {
// 保存结束(无论成功/失败)都以服务端最新值收口:失败时 item 没变 ⇒ 恢复原值,
// 不能把未落库的草稿继续显示成“已保存”。
if (wasSavingRef.current && !saving) {
setCostDraft(moneyText(item.cost_price));
setSaleDraft(moneyText(item.sale_price));
setRatioDraft(quoteSaleRatioTextFromMarkup(item.markup_ratio));
}
wasSavingRef.current = saving;
}, [saving, item.cost_price, item.sale_price]);
}, [saving, item.cost_price, item.sale_price, item.markup_ratio]);
const cost = parseDecimalText(costDraft, NaN);
const sale = parseDecimalText(saleDraft, NaN);
const ratio = quoteSaleRatio(cost, sale);
// 比例是否被改过:按**文本**对比服务端值(避开反算的舍入造成“一碰就脏”)
const ratioDirty = ratioDraft.trim() !== quoteSaleRatioTextFromMarkup(item.markup_ratio).trim();
const dirty =
Number.isFinite(cost) && Number.isFinite(sale)
ratioDirty ||
(Number.isFinite(cost) && Number.isFinite(sale)
? Math.abs(cost - Number(item.cost_price || 0)) > 1e-9 ||
Math.abs(sale - Number(item.sale_price || 0)) > 1e-9
: false;
: false);
const resetDrafts = () => {
setCostDraft(moneyText(item.cost_price));
setSaleDraft(moneyText(item.sale_price));
setRatioDraft(quoteSaleRatioTextFromMarkup(item.markup_ratio));
};
const commit = () => {
if (!editable || saving || !Number.isFinite(cost) || !Number.isFinite(sale)) {
if (!editable || saving) return;
// 销售比例可选;填了就必顶不低于 100(与弹窗保存同口径 quotes.toast.invalidSaleRatio)
const ratioText = ratioDraft.trim();
const ratioValue = ratioText === '' ? null : Number(ratioText);
if (ratioText !== '' && (!Number.isFinite(ratioValue) || (ratioValue as number) < 100)) {
onInvalidRatio();
setRatioDraft(quoteSaleRatioTextFromMarkup(item.markup_ratio));
return;
}
if (!Number.isFinite(cost) || !Number.isFinite(sale)) {
// 非法/空值不落库,恢复服务端值,避免卡片停在空态
setCostDraft(moneyText(item.cost_price));
setSaleDraft(moneyText(item.sale_price));
resetDrafts();
return;
}
if (!dirty) return;
onSavePrice(item, index, Math.max(0, cost), Math.max(0, sale));
onSavePrice(
item,
index,
Math.max(0, cost),
Math.max(0, sale),
// 比例未改就给服务端原值(不因舍入被改写);改了就按手填值存成 markup
ratioDirty ? (ratioValue == null ? null : markupRatioFromQuoteSaleRatio(ratioValue)) : item.markup_ratio ?? null
);
};
return (
@@ -415,10 +452,11 @@ const QuoteItemCard = React.memo<QuoteItemCardProps>(({
</div>
<div className="space-y-1.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
<label className="flex items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span>{labels.cost}</span>
<span className="text-slate-400">¥</span>
{/* 成本/售价**同一行**、输入框自适应伸缩(flex-1 + min-w-0):窄列也不换行 */}
<div className="flex items-center gap-x-2">
<label className="flex min-w-0 flex-1 items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span className="shrink-0">{labels.cost}</span>
<span className="shrink-0 text-slate-400">¥</span>
<DecimalTextInput
value={costDraft}
onChange={setCostDraft}
@@ -430,13 +468,13 @@ const QuoteItemCard = React.memo<QuoteItemCardProps>(({
}
}}
disabled={!editable || saving}
className="app-input app-focus-ring w-20 rounded-lg border px-2 py-1 text-sm tabular-nums disabled:opacity-60"
className="app-input app-focus-ring w-full min-w-0 flex-1 rounded-lg border px-1.5 py-1 text-sm tabular-nums text-right disabled:opacity-60"
placeholder="0.00"
/>
</label>
<label className="flex items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span>{labels.sale}</span>
<span className="text-slate-400">¥</span>
<label className="flex min-w-0 flex-1 items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span className="shrink-0">{labels.sale}</span>
<span className="shrink-0 text-slate-400">¥</span>
<DecimalTextInput
value={saleDraft}
onChange={setSaleDraft}
@@ -448,16 +486,27 @@ const QuoteItemCard = React.memo<QuoteItemCardProps>(({
}
}}
disabled={!editable || saving}
className="app-input app-focus-ring w-20 rounded-lg border px-2 py-1 text-sm tabular-nums disabled:opacity-60"
className="app-input app-focus-ring w-full min-w-0 flex-1 rounded-lg border px-1.5 py-1 text-sm tabular-nums text-right disabled:opacity-60"
placeholder="0.00"
/>
</label>
</div>
<div className="flex items-center gap-1 text-xs text-slate-500">
<span className="whitespace-nowrap">{labels.ratio}</span>
<div className="app-input w-20 rounded-lg border px-2 py-1 text-center text-sm tabular-nums">
{ratio == null ? labels.emDash : ratio.toFixed(2).replace(/\.?0+$/, '')}
</div>
<DecimalTextInput
value={ratioDraft}
onChange={setRatioDraft}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
event.currentTarget.blur();
}
}}
disabled={!editable || saving}
className="app-input app-focus-ring w-24 rounded-lg border px-2 py-1 text-sm tabular-nums text-center disabled:opacity-60"
placeholder={labels.ratioPh}
/>
<span>%</span>
</div>
</div>
@@ -659,12 +708,18 @@ export const QuoteVersionManagement: React.FC = () => {
const buildSheetItemsPayload = (
items: QuoteExpandedItem[],
override?: { index: number; costPrice: number; salePrice: number }
override?: {
index: number;
costPrice: number;
salePrice: number;
/** 本行销售比例(已换算为 markup);undefined = 不碰 | null = 清空 */
markupRatio?: number | null;
}
) =>
items.map((it, idx) => {
const cost = override && override.index === idx ? override.costPrice : Number(it.cost_price) || 0;
const sale = override && override.index === idx ? override.salePrice : Number(it.sale_price) || 0;
const saleRatio = quoteSaleRatio(cost, sale);
const hit = override != null && override.index === idx;
const cost = hit ? override!.costPrice : Number(it.cost_price) || 0;
const sale = hit ? override!.salePrice : Number(it.sale_price) || 0;
return {
sku_code: it.sku_code,
sku_name: it.sku_name,
@@ -672,12 +727,9 @@ export const QuoteVersionManagement: React.FC = () => {
cost_price: Math.max(0, cost),
sale_price: Math.max(0, sale),
price: Math.max(0, sale),
markup_ratio:
override && override.index === idx
? saleRatio == null
? null
: markupRatioFromQuoteSaleRatio(saleRatio)
: it.markup_ratio ?? null,
/** 2026-10-21 开发者:销售比例是**手填**字段,保存时按手填值原样落库,
* **不得**再由成本/售价反算覆盖(旧写法在这里把用户填的比例改掉)。 */
markup_ratio: hit ? override!.markupRatio ?? null : it.markup_ratio ?? null,
};
});
@@ -771,7 +823,8 @@ export const QuoteVersionManagement: React.FC = () => {
item: QuoteExpandedItem,
index: number,
costPrice: number,
salePrice: number
salePrice: number,
markupRatio?: number | null
) => {
if (!expandedCode || !expandedDetail || !expandedEditable) return;
const seq = ++priceSaveSeq.current;
@@ -783,6 +836,7 @@ export const QuoteVersionManagement: React.FC = () => {
index,
costPrice,
salePrice,
markupRatio,
});
const response = await updateQuoteSheetApi(expandedCode, { items });
if (seq !== priceSaveSeq.current) return;
@@ -803,6 +857,50 @@ export const QuoteVersionManagement: React.FC = () => {
}
};
/** 取消卡片视图里的「新增商品」卡片(弹窗/输入值一并清空) */
const cancelInlineAdd = () => {
setInlineAddOpen(false);
setInlineDraft({ ...EMPTY_INLINE_DRAFT });
};
/** 新增商品卡片「保存报价单」:直接追加一行并刷新明细(与改前同一条 append 通道) */
const saveInlineItem = async () => {
if (!expandedCode || inlineSaving || !inlineDraft.sku_code) return;
const sale = Number(inlineDraft.sale_price) || 0;
const cost = Number(inlineDraft.cost_price) || 0;
if (!(sale > 0)) {
notify.error(t('quotes.toast.invalidPrice'));
return;
}
// 销售比例:手填可选;填了必须 ≥ 100(与弹窗保存同口径)
const ratioText = inlineDraft.markup_ratio.trim();
const ratioValue = ratioText === '' ? null : Number(ratioText);
if (ratioText !== '' && (!Number.isFinite(ratioValue) || (ratioValue as number) < 100)) {
notify.error(t('quotes.toast.invalidSaleRatio'));
return;
}
setInlineSaving(true);
try {
await appendQuoteSheetItemsApi(expandedCode, [
{
sku_code: inlineDraft.sku_code,
price: sale,
sale_price: sale,
cost_price: cost,
markup_ratio: ratioValue == null ? null : markupRatioFromQuoteSaleRatio(ratioValue),
unit: inlineDraft.unit || undefined,
},
]);
notify.success(t('quotes.toast.saveItemOk'));
cancelInlineAdd();
await loadExpandedDetail(expandedCode, { silent: true });
} catch (err: any) {
notify.error(err?.message || t('quotes.toast.saveItemFail'));
} finally {
setInlineSaving(false);
}
};
const deleteExpandedItem = async (item: QuoteExpandedItem, index: number) => {
if (!expandedCode || !expandedDetail || !expandedEditable) return;
/**
@@ -1793,140 +1891,6 @@ export const QuoteVersionManagement: React.FC = () => {
</div>
</div>
{inlineAddOpen && expandedEditable ? (
<div className="mb-3 app-surface rounded-xl border p-3 space-y-2 overflow-visible">
<div className="flex items-start justify-between gap-2">
<div className="flex min-w-0 flex-1 items-center gap-1">
<span className="shrink-0 text-sm font-medium text-slate-700">{t('quotes.itemCol.sku')}</span>
<SearchableSelect
value={inlineDraft.sku_code}
onChange={(val) => {
const sku = skus.find((x) => x.sku_code === val);
setInlineDraft((d) => ({
...d,
sku_code: val,
// 选中商品后自动带出规格/单位(有则填,无则留空,不覆盖用户已填内容)
spec: (sku as any)?.spec || d.spec,
unit: (sku as any)?.unit || d.unit,
}));
}}
options={quoteSkuOptions}
compact
className="w-64 shrink-0"
maxListHeight="max-h-56"
allowCreateFromQuery
alwaysShowCreate
createEmptyLabel={t('quotes.form.newSku')}
createFromQueryLabel={(q) =>
q.trim() ? `${t('quotes.form.newSku')}「${q}」` : t('quotes.form.newSku')
}
createFromQueryHint={t('quotes.form.newSkuHint')}
onCreateFromQuery={(q) => {
setCreateProductInitialName(q);
setCreateProductError('');
setShowCreateProductModal(true);
}}
/>
{inlineDraft.sku_code ? (
<button type="button" onClick={() => setInlineDraft((d) => ({ ...d, sku_code: '', spec: '', unit: '' }))} className="shrink-0 px-1 text-slate-400" title="清除">
×
</button>
) : null}
</div>
<button
type="button"
onClick={() => { setInlineAddOpen(false); setInlineDraft({ sku_code: '', spec: '', unit: '', cost_price: '', sale_price: '', markup_ratio: '' }); }}
className="shrink-0 px-1 text-slate-400"
title={t('quotes.action.delete')}
>
🗑
</button>
<span className="shrink-0 rounded-full bg-emerald-50 px-1.5 py-0.5 text-[11px] text-emerald-700">
{t('quotes.detail.skuEnabled')}
</span>
</div>
<p className="text-xs text-slate-500">
{t('quotes.detail.specPrefix', { spec: '' }).replace(/[::]\s*$/, '')}: {inlineDraft.spec || '—'}
{t('quotes.itemCol.unit')}: {inlineDraft.unit || '—'}
</p>
<div className="flex flex-wrap items-center gap-3">
<label className="flex items-center gap-1 text-xs text-slate-500">
<span>{t('quotes.form.col.costYuan')}</span>
<span>¥</span>
<input
inputMode="decimal"
value={inlineDraft.cost_price}
onChange={(e) => setInlineDraft((d) => ({ ...d, cost_price: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input w-24 rounded-lg border px-2 py-1 text-sm text-right"
/>
</label>
<label className="flex items-center gap-1 text-xs text-slate-500">
<span>{t('quotes.form.col.saleYuan')}</span>
<span>¥</span>
<input
inputMode="decimal"
value={inlineDraft.sale_price}
onChange={(e) => setInlineDraft((d) => ({ ...d, sale_price: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input w-24 rounded-lg border px-2 py-1 text-sm text-right"
/>
</label>
<label className="flex items-center gap-1 text-xs text-slate-500">
<span>{t('quotes.form.col.saleRatio').replace(/(%)$/, '')} (%)</span>
<input
inputMode="decimal"
value={inlineDraft.markup_ratio}
onChange={(e) => setInlineDraft((d) => ({ ...d, markup_ratio: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input w-20 rounded-lg border px-2 py-1 text-sm text-right"
/>
</label>
</div>
<div className="flex items-center gap-2">
<button
type="button"
disabled={inlineSaving || !inlineDraft.sku_code}
onClick={async () => {
if (!inlineDraft.sku_code || inlineSaving) return;
const sale = Number(inlineDraft.sale_price) || 0;
const cost = Number(inlineDraft.cost_price) || 0;
if (!(sale > 0)) {
notify.error(t('quotes.toast.invalidPrice'));
return;
}
setInlineSaving(true);
try {
await appendQuoteSheetItemsApi(expandedCode!, [
{
sku_code: inlineDraft.sku_code,
price: sale,
sale_price: sale,
cost_price: cost,
unit: inlineDraft.unit || undefined,
},
]);
notify.success(t('quotes.toast.saveItemOk'));
setInlineAddOpen(false);
setInlineDraft({ sku_code: '', spec: '', unit: '', cost_price: '', sale_price: '', markup_ratio: '' });
await loadExpandedDetail(expandedCode!, { silent: true });
} catch (err: any) {
notify.error(err?.message || t('quotes.toast.saveItemFail'));
} finally {
setInlineSaving(false);
}
}}
className="rounded-lg bg-emerald-600 px-3 py-1.5 text-sm text-white disabled:opacity-50"
>
{inlineSaving ? t('common.saving') : t('common.save')}
</button>
<button
type="button"
onClick={() => setInlineAddOpen(false)}
className="rounded-lg border px-3 py-1.5 text-sm"
>
{t('common.cancel')}
</button>
</div>
</div>
) : null}
<QuickCreateProductModal
show={showCreateProductModal}
isCreating={creatingProduct}
@@ -1976,16 +1940,108 @@ export const QuoteVersionManagement: React.FC = () => {
})();
}}
/>
{(expandedDetail.enrichedItems || []).length === 0 ? (
<div className="app-surface rounded-2xl border px-4 py-8 text-center text-sm text-slate-500">
{t('quotes.detail.emptyItems')}
</div>
) : filteredExpandedItems.length === 0 ? (
<div className="app-surface rounded-2xl border px-4 py-8 text-center text-sm text-slate-500">
{t('quotes.detail.noMatch')}
</div>
) : (
{inlineAddOpen || filteredExpandedItems.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 overflow-visible">
{/*
新增商品卡片(2026-10-20 开发者:与商品卡片同栅格、同版式,
不再单独占一整行;点「+ 新增商品」时作为第一格出现)
*/}
{inlineAddOpen && expandedEditable ? (
<div className="app-surface rounded-xl border border-slate-200 p-3 space-y-2 min-w-0 overflow-visible dark:border-slate-700">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<SearchableSelect
value={inlineDraft.sku_code}
onChange={(val) => {
const sku = skus.find((x) => x.sku_code === val);
setInlineDraft((d) => ({
...d,
sku_code: val,
// 选中商品后自动带出规格/单位(有则填,无则留空,不覆盖用户已填内容)
spec: (sku as any)?.spec || d.spec,
unit: (sku as any)?.unit || d.unit,
}));
}}
options={quoteSkuOptions}
compact
placeholder={t('quotes.detail.searchProductPh')}
maxListHeight="max-h-56"
allowCreateFromQuery
alwaysShowCreate
createEmptyLabel={t('quotes.form.newSku')}
createFromQueryLabel={(q) =>
q.trim() ? `${t('quotes.form.newSku')}「${q}」` : t('quotes.form.newSku')
}
createFromQueryHint={t('quotes.form.newSkuHint')}
onCreateFromQuery={(q) => {
setCreateProductInitialName(q);
setCreateProductError('');
setShowCreateProductModal(true);
}}
/>
</div>
<button
type="button"
onClick={cancelInlineAdd}
className="shrink-0 rounded-md p-1 text-slate-400 hover:text-red-600"
title={t('quotes.action.delete')}
aria-label={t('quotes.action.delete')}
>
<X className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
{/* 成本/售价**同一行**、输入框自适应伸缩(flex-1 + min-w-0):窄列也不换行 */}
<div className="flex items-center gap-x-2">
<label className="flex min-w-0 flex-1 items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span className="shrink-0">{t('quotes.form.col.costYuan')}</span>
<span className="shrink-0 text-slate-400">¥</span>
<input
inputMode="decimal"
value={inlineDraft.cost_price}
onChange={(e) => setInlineDraft((d) => ({ ...d, cost_price: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input app-focus-ring w-full min-w-0 flex-1 rounded-lg border px-1.5 py-1 text-sm tabular-nums text-right"
placeholder="0.00"
/>
</label>
<label className="flex min-w-0 flex-1 items-center gap-1 text-xs text-slate-500 whitespace-nowrap">
<span className="shrink-0">{t('quotes.form.col.saleYuan')}</span>
<span className="shrink-0 text-slate-400">¥</span>
<input
inputMode="decimal"
value={inlineDraft.sale_price}
onChange={(e) => setInlineDraft((d) => ({ ...d, sale_price: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input app-focus-ring w-full min-w-0 flex-1 rounded-lg border px-1.5 py-1 text-sm tabular-nums text-right"
placeholder="0.00"
/>
</label>
</div>
<div className="flex items-center gap-1 text-xs text-slate-500">
<span className="whitespace-nowrap">{t('quotes.form.col.saleRatio')}</span>
<input
inputMode="decimal"
value={inlineDraft.markup_ratio}
onChange={(e) => setInlineDraft((d) => ({ ...d, markup_ratio: e.target.value.replace(/[^0-9.]/g, '') }))}
className="app-input app-focus-ring w-24 rounded-lg border px-2 py-1 text-sm tabular-nums text-center"
placeholder={t('quotes.form.saleRatioPh')}
/>
<span>%</span>
</div>
</div>
<div className="flex justify-end pt-0.5">
<button
type="button"
disabled={inlineSaving || !inlineDraft.sku_code}
onClick={() => void saveInlineItem()}
className="rounded-lg bg-emerald-600 px-3 py-1 text-sm text-white disabled:opacity-50"
>
{inlineSaving ? t('common.saving') : t('quotes.form.saveCreate')}
</button>
</div>
</div>
) : null}
{filteredExpandedItems.map((item) => {
const originalIndex = (expandedDetail.enrichedItems || []).findIndex((rowItem) => rowItem === item);
const cardIndex = originalIndex >= 0 ? originalIndex : 0;
@@ -2001,7 +2057,8 @@ export const QuoteVersionManagement: React.FC = () => {
labels={{
cost: t('quotes.form.col.costYuan'),
sale: t('quotes.form.col.saleYuan'),
ratio: t('quotes.form.col.saleRatio').replace(/(%)$/, ''),
ratio: t('quotes.form.col.saleRatio'),
ratioPh: t('quotes.form.saleRatioPh'),
spec: t('quotes.detail.specPrefix', { spec: '' }).replace(/[::]\s*$/, ''),
unit: t('quotes.itemCol.unit'),
enabled: t('quotes.detail.skuEnabled'),
@@ -2009,12 +2066,23 @@ export const QuoteVersionManagement: React.FC = () => {
delete: t('quotes.action.delete'),
emDash: t('quotes.emDash'),
}}
onSavePrice={(rowItem, index, costPrice, salePrice) => void saveItemPrice(rowItem, index, costPrice, salePrice)}
onSavePrice={(rowItem, index, costPrice, salePrice, markupRatio) =>
void saveItemPrice(rowItem, index, costPrice, salePrice, markupRatio)
}
onInvalidRatio={() => notify.error(t('quotes.toast.invalidSaleRatio'))}
onDelete={(rowItem, index) => void deleteExpandedItem(rowItem, index)}
/>
);
})}
</div>
) : (expandedDetail.enrichedItems || []).length === 0 ? (
<div className="app-surface rounded-2xl border px-4 py-8 text-center text-sm text-slate-500">
{t('quotes.detail.emptyItems')}
</div>
) : (
<div className="app-surface rounded-2xl border px-4 py-8 text-center text-sm text-slate-500">
{t('quotes.detail.noMatch')}
</div>
)}
</div>
)}