barcodeFormat.ts 2.95 KB
/** 模板编辑器 / 预览 / 打印共用的条形码制式选项(与需求文档顺序一致) */

export const BARCODE_FORMAT_OPTIONS = [
  { label: "Codabar", value: "CODABAR" },
  { label: "Code39", value: "CODE39" },
  { label: "Code128", value: "CODE128" },
  { label: "EAN-2", value: "EAN2" },
  { label: "EAN-5", value: "EAN5" },
  { label: "EAN-8", value: "EAN8" },
  { label: "EAN-13", value: "EAN13" },
  { label: "ITF-14", value: "ITF14" },
  { label: "MSI", value: "MSI" },
  { label: "MSI10", value: "MSI10" },
  { label: "MSI11", value: "MSI11" },
  { label: "MSI1010", value: "MSI1010" },
  { label: "MSI1110", value: "MSI1110" },
  { label: "Pharmacode", value: "PHARMACODE" },
  { label: "UPC(A)", value: "UPCA" },
] as const;

export type BarcodeFormatValue = (typeof BARCODE_FORMAT_OPTIONS)[number]["value"];

export const DEFAULT_BARCODE_FORMAT: BarcodeFormatValue = BARCODE_FORMAT_OPTIONS[0].value;

/** 规范化模板 config.barcodeType(兼容旧值、带连字符写法) */
export function normalizeBarcodeType(raw: unknown): BarcodeFormatValue {
  const key = String(raw ?? "")
    .trim()
    .toUpperCase()
    .replace(/[^A-Z0-9]/g, "");
  const allowed = new Set(BARCODE_FORMAT_OPTIONS.map((o) => o.value));
  if (allowed.has(key as BarcodeFormatValue)) return key as BarcodeFormatValue;
  if (key === "UPC" || key === "UPCA") return "UPCA";
  if (key === "ITF") return "ITF14";
  return DEFAULT_BARCODE_FORMAT;
}

/** JsBarcode `format` 参数 */
export function toJsBarcodeFormat(barcodeType: unknown): string {
  const key = normalizeBarcodeType(barcodeType);
  const map: Record<BarcodeFormatValue, string> = {
    CODABAR: "codabar",
    CODE39: "CODE39",
    CODE128: "CODE128",
    EAN2: "ean2",
    EAN5: "ean5",
    EAN8: "EAN8",
    EAN13: "EAN13",
    ITF14: "ITF14",
    MSI: "MSI",
    MSI10: "MSI10",
    MSI11: "MSI11",
    MSI1010: "MSI1010",
    MSI1110: "MSI1110",
    PHARMACODE: "pharmacode",
    UPCA: "upc",
  };
  return map[key] ?? "codabar";
}

/** TSC 打印机 BARCODE 指令制式名 */
export function toTscBarcodeSymbology(barcodeType: unknown): string {
  const key = normalizeBarcodeType(barcodeType);
  const map: Record<BarcodeFormatValue, string> = {
    CODABAR: "CODA",
    CODE39: "39",
    CODE128: "128",
    EAN2: "128",
    EAN5: "128",
    EAN8: "EAN8",
    EAN13: "EAN13",
    ITF14: "ITF14",
    MSI: "MSI",
    MSI10: "MSI",
    MSI11: "MSI",
    MSI1010: "MSI",
    MSI1110: "MSI",
    PHARMACODE: "128",
    UPCA: "UPCA",
  };
  return map[key] ?? "CODA";
}

/** ESC/POS GS k 条码类型码 */
export function toEscBarcodeTypeCode(barcodeType: unknown): number {
  const key = normalizeBarcodeType(barcodeType);
  const map: Record<BarcodeFormatValue, number> = {
    CODABAR: 71,
    CODE39: 69,
    CODE128: 73,
    EAN2: 73,
    EAN5: 73,
    EAN8: 68,
    EAN13: 67,
    ITF14: 70,
    MSI: 73,
    MSI10: 73,
    MSI11: 73,
    MSI1010: 73,
    MSI1110: 73,
    PHARMACODE: 73,
    UPCA: 65,
  };
  return map[key] ?? 71;
}