You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import type { DisplayUnit, UnitDim, UnitWeight } from "@/lib/frontend/types";
import {
cmToIn,
inToCm,
kgToLb,
lbToKg,
toAxelWholeInches,
toAxelWholePounds,
} from "@/modules/quote/unit-converter";
export function formatCargoInputNumber(value: number): string {
if (!Number.isFinite(value)) {
return "";
}
const rounded = Math.round(value * 100) / 100;
return String(rounded);
}
export function parseCargoInputNumber(raw: string): number | null {
const trimmed = raw.trim();
if (!trimmed) {
return null;
}
const value = Number(trimmed);
return Number.isFinite(value) ? value : null;
}
/** 表单内单值重量换算(保持物理量不变) */
export function convertWeightInputValue(
value: number,
from: UnitWeight,
to: UnitWeight,
): number {
if (from === to) {
return value;
}
const lb = from === "kg" ? kgToLb(value) : value;
return to === "kg" ? lbToKg(lb) : lb;
}
/** 表单内尺寸换算(保持物理量不变) */
export function convertDimInputValue(
value: number,
from: UnitDim,
to: UnitDim,
): number {
if (from === to) {
return value;
}
const inches = from === "cm" ? cmToIn(value) : value;
return to === "cm" ? inToCm(inches) : inches;
}
export function displayUnitToCargoUnits(
display: DisplayUnit,
): { weight: UnitWeight; dim: UnitDim } {
return display === "metric"
? { weight: "kg", dim: "cm" }
: { weight: "lb", dim: "in" };
}
/** 展示「询价将按 xxx lb」类提示界面保留用户输入单位后端向上取整 */
export function describeWeightEquivalent(
value: number,
unit: UnitWeight,
): string | null {
if (!Number.isFinite(value) || value <= 0) {
return null;
}
const rawLb = unit === "kg" ? kgToLb(value) : value;
const queryLb = toAxelWholePounds(rawLb);
if (unit === "kg") {
return `询价将按 ${queryLb} lb${formatCargoInputNumber(value)} kg 换算,小数进一)`;
}
if (queryLb !== rawLb) {
return `询价将按 ${queryLb} lb小数进一`;
}
return null;
}
export function describeDimEquivalent(
length: number,
width: number,
height: number,
unit: UnitDim,
): string | null {
if (
!Number.isFinite(length) ||
!Number.isFinite(width) ||
!Number.isFinite(height) ||
length <= 0 ||
width <= 0 ||
height <= 0
) {
return null;
}
const toQueryIn = (v: number) =>
toAxelWholeInches(unit === "cm" ? cmToIn(v) : v);
const ql = toQueryIn(length);
const qw = toQueryIn(width);
const qh = toQueryIn(height);
if (unit === "cm") {
return `询价将按 ${ql} × ${qw} × ${qh} in厘米换算小数进一`;
}
const rawL = length;
const rawW = width;
const rawH = height;
if (ql !== rawL || qw !== rawW || qh !== rawH) {
return `询价将按 ${ql} × ${qw} × ${qh} in小数进一`;
}
return null;
}