来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
384 lines
12 KiB
TypeScript
384 lines
12 KiB
TypeScript
import { supabase } from '../supabase/client';
|
|
import { readOperatingBranchCode } from './operatingBranch';
|
|
import { parseCustomerDeliveryDeadline } from './customerDeliveryDeadline';
|
|
import {
|
|
BulkImportResult,
|
|
downloadExcelData,
|
|
downloadExcelTemplate,
|
|
getCell,
|
|
parseExcelFile,
|
|
parseNumberText,
|
|
parseStatusText,
|
|
} from './excelImportExport';
|
|
|
|
export const CUSTOMER_IMPORT_HEADERS = [
|
|
'企业名称*',
|
|
'联系电话*',
|
|
'联系人',
|
|
'地址',
|
|
'配送时间',
|
|
'开户银行',
|
|
'银行账号',
|
|
'统一社会信用代码',
|
|
'所属单位',
|
|
'备注',
|
|
'账期(天)',
|
|
'预算金额',
|
|
'信用额度',
|
|
'状态',
|
|
];
|
|
|
|
export const CUSTOMER_IMPORT_FIELD_DICT: import('./smartColumnMapping').ImportFieldDef[] = [
|
|
{
|
|
key: 'companyName',
|
|
label: '企业名称',
|
|
required: true,
|
|
templateHeader: '企业名称*',
|
|
aliases: ['企业名称', '客户名称', '公司名称', '单位名称', '名称', 'customer', 'company'],
|
|
patterns: [/企业|客户|公司|单位名/],
|
|
},
|
|
{
|
|
key: 'contactPhone',
|
|
label: '联系电话',
|
|
required: true,
|
|
templateHeader: '联系电话*',
|
|
aliases: ['联系电话', '手机号', '手机', '电话', '联系方式', 'phone', 'mobile'],
|
|
patterns: [/电话|手机|联系方式/],
|
|
},
|
|
{
|
|
key: 'contactName',
|
|
label: '联系人',
|
|
templateHeader: '联系人',
|
|
aliases: ['联系人', '联系人姓名', '负责人', 'contact'],
|
|
patterns: [/联系人|负责人/],
|
|
},
|
|
{
|
|
key: 'address',
|
|
label: '地址',
|
|
templateHeader: '地址',
|
|
aliases: ['地址', '收货地址', '详细地址', 'address'],
|
|
patterns: [/地址/],
|
|
},
|
|
{
|
|
key: 'deliveryTime',
|
|
label: '须送达时刻',
|
|
templateHeader: '配送时间',
|
|
aliases: ['配送时间', '须送达时刻', '送货时间', '到货时间', '配送时段', 'deliverytime'],
|
|
patterns: [/配送时间|送货时间|到货/],
|
|
},
|
|
{
|
|
key: 'bankName',
|
|
label: '开户银行',
|
|
templateHeader: '开户银行',
|
|
aliases: ['开户银行', '开户行', '银行', 'bank'],
|
|
patterns: [/开户行|银行/],
|
|
},
|
|
{
|
|
key: 'bankAccount',
|
|
label: '银行账号',
|
|
templateHeader: '银行账号',
|
|
aliases: ['银行账号', '账号', '对公账号', 'bankaccount'],
|
|
patterns: [/账号|账户/],
|
|
},
|
|
{
|
|
key: 'unifiedSocialCode',
|
|
label: '统一社会信用代码',
|
|
templateHeader: '统一社会信用代码',
|
|
aliases: ['统一社会信用代码', '信用代码', '税号', '社会信用代码'],
|
|
patterns: [/信用代码|税号/],
|
|
},
|
|
{
|
|
key: 'affiliatedUnit',
|
|
label: '所属单位',
|
|
templateHeader: '所属单位',
|
|
aliases: ['所属单位', '挂靠单位'],
|
|
patterns: [/所属单位|挂靠/],
|
|
},
|
|
{
|
|
key: 'remark',
|
|
label: '备注',
|
|
templateHeader: '备注',
|
|
aliases: ['备注', '说明', 'remark'],
|
|
patterns: [/备注|说明/],
|
|
},
|
|
{
|
|
key: 'settlementDays',
|
|
label: '账期(天)',
|
|
templateHeader: '账期(天)',
|
|
aliases: ['账期', '账期(天)', '结算账期', '结算天数'],
|
|
patterns: [/账期|结算天/],
|
|
},
|
|
{
|
|
key: 'budgetAmount',
|
|
label: '预算金额',
|
|
templateHeader: '预算金额',
|
|
aliases: ['预算金额', '预算'],
|
|
patterns: [/预算/],
|
|
},
|
|
{
|
|
key: 'creditLimit',
|
|
label: '信用额度',
|
|
templateHeader: '信用额度',
|
|
aliases: ['信用额度', '额度'],
|
|
patterns: [/信用|额度/],
|
|
},
|
|
{
|
|
key: 'status',
|
|
label: '状态',
|
|
templateHeader: '状态',
|
|
aliases: ['状态', 'status'],
|
|
patterns: [/状态/],
|
|
},
|
|
];
|
|
|
|
export const CUSTOMER_IMPORT_EXAMPLES: (string | number)[][] = [
|
|
[
|
|
'示例食堂有限公司',
|
|
'13800138000',
|
|
'张三',
|
|
'成都市高新区天府大道 100 号',
|
|
'06:00',
|
|
'中国工商银行成都高新支行',
|
|
'6222020000000000',
|
|
'',
|
|
'',
|
|
'',
|
|
30,
|
|
0,
|
|
0,
|
|
'启用',
|
|
],
|
|
];
|
|
|
|
async function generateCustomerCode(): Promise<string> {
|
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
const code = `CUS${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 90 + 10)}`;
|
|
const { data } = await supabase
|
|
.from('customers')
|
|
.select('customer_code')
|
|
.eq('customer_code', code)
|
|
.maybeSingle();
|
|
if (!data) return code;
|
|
}
|
|
return `CUS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
|
}
|
|
|
|
async function initializeCustomerSkuLibrary(customerCode: string, branchCode?: string | null) {
|
|
try {
|
|
const { data: skus } = await supabase
|
|
.from('skus')
|
|
.select('sku_code, sku_name, unit')
|
|
.eq('status', 1)
|
|
.limit(50);
|
|
if (!skus?.length) return;
|
|
const branch = branchCode ?? readOperatingBranchCode();
|
|
await supabase.from('customer_skus').insert(
|
|
skus.map((sku: { sku_code: string; sku_name?: string | null; unit?: string | null }) => ({
|
|
customer_code: customerCode,
|
|
sku_code: sku.sku_code,
|
|
customer_sku_name: sku.sku_name,
|
|
customer_unit: sku.unit,
|
|
usage_count: 0,
|
|
is_favorite: false,
|
|
branch_code: branch || null,
|
|
}))
|
|
);
|
|
} catch (error) {
|
|
console.error('初始化客户商品库失败:', error);
|
|
}
|
|
}
|
|
|
|
export async function downloadCustomerImportTemplate() {
|
|
await downloadExcelTemplate(
|
|
'客户导入模板.xlsx',
|
|
'客户导入',
|
|
CUSTOMER_IMPORT_HEADERS,
|
|
CUSTOMER_IMPORT_EXAMPLES,
|
|
[
|
|
{
|
|
name: '填写说明',
|
|
headers: ['字段', '说明'],
|
|
rows: [
|
|
['企业名称*', '必填'],
|
|
['联系电话*', '必填,11 位手机号;可与已有客户相同'],
|
|
['配送时间', '选填,须送达时刻,如 06:00(此时刻前送达)'],
|
|
['开户银行 / 银行账号', '对公信息,选填'],
|
|
['状态', '启用/停用,默认启用'],
|
|
],
|
|
},
|
|
]
|
|
);
|
|
}
|
|
|
|
function parseCustomerStatus(raw: string): number {
|
|
const t = String(raw || '').trim();
|
|
if (!t) return 10;
|
|
if (/冻结|逾期/.test(t)) return 30;
|
|
if (/超额|预警|停用|禁用|停/.test(t)) return 20;
|
|
if (/正常|启用|活/.test(t)) return 10;
|
|
const n = parseStatusText(t, 10);
|
|
return n === 1 ? 10 : n === 0 ? 20 : n;
|
|
}
|
|
|
|
export async function importCustomersFromExcel(
|
|
file: File,
|
|
preMappedRows?: Record<string, string>[]
|
|
): Promise<BulkImportResult> {
|
|
const rows =
|
|
preMappedRows ??
|
|
(await parseExcelFile(file, {
|
|
preferredSheetNames: ['客户导入'],
|
|
requiredHeaderHints: ['企业名称', '联系电话'],
|
|
}));
|
|
const result: BulkImportResult = { success: 0, skipped: 0, failed: 0, errors: [] };
|
|
const branchCode = readOperatingBranchCode();
|
|
|
|
if (rows.length === 0) {
|
|
result.errors.push('文件中没有可导入的数据,请使用「客户导入」工作表');
|
|
return result;
|
|
}
|
|
|
|
for (const row of rows) {
|
|
const rowNumber = row.__row || '?';
|
|
const companyName = getCell(row, '企业名称*', '企业名称', '客户名称', '公司名称');
|
|
const contactPhone = getCell(row, '联系电话*', '联系电话', '手机号', '手机');
|
|
const contactName = getCell(row, '联系人') || null;
|
|
const address = getCell(row, '地址', '收货地址') || null;
|
|
const deliveryTimeRaw = getCell(row, '配送时间', '送货时间');
|
|
let deliveryTime: string | null = null;
|
|
if (deliveryTimeRaw) {
|
|
deliveryTime = parseCustomerDeliveryDeadline(deliveryTimeRaw);
|
|
if (!deliveryTime) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:须送达时刻须为 HH:mm,如 06:00`);
|
|
continue;
|
|
}
|
|
}
|
|
const bankName = getCell(row, '开户银行', '开户行') || null;
|
|
const bankAccount = getCell(row, '银行账号', '对公账号') || null;
|
|
const unifiedSocialCode = getCell(row, '统一社会信用代码', '税号') || null;
|
|
const affiliatedUnit = getCell(row, '所属单位') || null;
|
|
const remark = getCell(row, '备注') || null;
|
|
const settlementDaysRaw = getCell(row, '账期(天)', '账期', '结算账期');
|
|
const budgetAmount = parseNumberText(getCell(row, '预算金额', '预算'), 0);
|
|
const creditLimit = parseNumberText(getCell(row, '信用额度', '额度'), 0);
|
|
const status = parseCustomerStatus(getCell(row, '状态'));
|
|
|
|
if (!companyName) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:企业名称不能为空`);
|
|
continue;
|
|
}
|
|
if (!contactPhone) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:联系电话不能为空`);
|
|
continue;
|
|
}
|
|
if (!/^1[3-9]\d{9}$/.test(contactPhone)) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:联系电话须为有效 11 位手机号`);
|
|
continue;
|
|
}
|
|
if (unifiedSocialCode && unifiedSocialCode.length !== 18) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:统一社会信用代码应为 18 位`);
|
|
continue;
|
|
}
|
|
|
|
let settlementDays = 30;
|
|
if (settlementDaysRaw) {
|
|
const n = parseInt(settlementDaysRaw, 10);
|
|
if (Number.isNaN(n) || n <= 0) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:账期须为正整数`);
|
|
continue;
|
|
}
|
|
settlementDays = n;
|
|
}
|
|
|
|
try {
|
|
const customerCode = await generateCustomerCode();
|
|
const { error } = await supabase.from('customers').insert([
|
|
{
|
|
customer_code: customerCode,
|
|
company_name: companyName,
|
|
unified_social_code: unifiedSocialCode || null,
|
|
contact_name: contactName,
|
|
contact_phone: contactPhone,
|
|
bank_name: bankName,
|
|
bank_account: bankAccount,
|
|
affiliated_unit: affiliatedUnit,
|
|
remark,
|
|
address,
|
|
delivery_time: deliveryTime,
|
|
budget_amount: budgetAmount,
|
|
cost_budget: budgetAmount,
|
|
credit_limit: creditLimit,
|
|
settlement_days: settlementDays,
|
|
status,
|
|
},
|
|
]);
|
|
if (error) throw error;
|
|
|
|
await initializeCustomerSkuLibrary(customerCode, branchCode);
|
|
|
|
result.success += 1;
|
|
} catch (error: any) {
|
|
result.failed += 1;
|
|
result.errors.push(`第 ${rowNumber} 行:${error?.message || '保存失败'}`);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
export type CustomerExportRow = {
|
|
customer_code?: string | null;
|
|
company_name?: string | null;
|
|
contact_phone?: string | null;
|
|
contact_name?: string | null;
|
|
address?: string | null;
|
|
delivery_time?: string | null;
|
|
bank_name?: string | null;
|
|
bank_account?: string | null;
|
|
unified_social_code?: string | null;
|
|
affiliated_unit?: string | null;
|
|
remark?: string | null;
|
|
settlement_days?: number | null;
|
|
budget_amount?: number | null;
|
|
credit_limit?: number | null;
|
|
status?: number | null;
|
|
};
|
|
|
|
const CUSTOMER_EXPORT_HEADERS = ['客户编码', ...CUSTOMER_IMPORT_HEADERS];
|
|
|
|
function customerStatusLabel(status: number | null | undefined): string {
|
|
const n = Number(status);
|
|
if (n === 30) return '逾期冻结';
|
|
if (n === 20) return '预算超额';
|
|
if (n === 10) return '启用';
|
|
return status == null ? '' : String(status);
|
|
}
|
|
|
|
/** 按当前列表导出(列对齐导入模板,并含客户编码) */
|
|
export async function exportCustomersToExcel(customers: CustomerExportRow[]) {
|
|
const rows = customers.map((c) => [
|
|
c.customer_code || '',
|
|
c.company_name || '',
|
|
c.contact_phone || '',
|
|
c.contact_name || '',
|
|
c.address || '',
|
|
c.delivery_time || '',
|
|
c.bank_name || '',
|
|
c.bank_account || '',
|
|
c.unified_social_code || '',
|
|
c.affiliated_unit || '',
|
|
c.remark || '',
|
|
c.settlement_days ?? '',
|
|
c.budget_amount ?? '',
|
|
c.credit_limit ?? '',
|
|
customerStatusLabel(c.status),
|
|
]);
|
|
await downloadExcelData('客户导出.xlsx', '客户导出', CUSTOMER_EXPORT_HEADERS, rows);
|
|
}
|