Files
SupplierSystem/server/src/services/userBindingService.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库: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 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

626 lines
22 KiB
TypeScript

import type { PoolClient } from 'pg';
import { pool } from '../db';
import { getTenantDbStore, runWithTenantDbContext } from './tenantDbContext';
import { findAcrossActiveTenants, listActiveTenantBranches } from './tenantSchemaFallback';
export type UserBindingsInput = {
purchaser?: {
enabled: boolean;
purchaser_code?: string | null;
create_new?: boolean;
is_primary?: boolean;
};
supplier?: { enabled: boolean; supplier_code?: string | null; create_new?: boolean };
delivery?: { enabled: boolean; person_code?: string | null; create_new?: boolean };
};
export type UserBindingsState = {
purchaser: {
enabled: boolean;
purchaser_code: string | null;
purchaser_name: string | null;
is_primary: boolean;
};
supplier: { enabled: boolean; supplier_code: string | null; supplier_name: string | null };
delivery: { enabled: boolean; person_code: string | null; person_name: string | null };
};
function emptyBindings(): UserBindingsState {
return {
purchaser: { enabled: false, purchaser_code: null, purchaser_name: null, is_primary: false },
supplier: { enabled: false, supplier_code: null, supplier_name: null },
delivery: { enabled: false, person_code: null, person_name: null },
};
}
async function nextPurchaserCode(client: PoolClient) {
const result = await client.query(
`SELECT purchaser_code FROM purchaser_users
WHERE purchaser_code ~ '^PUR[0-9]+$'
ORDER BY purchaser_code DESC
LIMIT 1`
);
const last = result.rows[0]?.purchaser_code as string | undefined;
const num = last ? Number(last.replace(/^PUR/, '')) + 1 : 1;
return `PUR${String(num).padStart(3, '0')}`;
}
async function nextSupplierCode(client: PoolClient) {
const result = await client.query(
`SELECT supplier_code FROM suppliers
WHERE supplier_code ~ '^SUP[0-9]+$'
ORDER BY supplier_code DESC
LIMIT 1`
);
const last = result.rows[0]?.supplier_code as string | undefined;
const num = last ? Number(last.replace(/^SUP/, '')) + 1 : 1;
return `SUP${String(num).padStart(3, '0')}`;
}
async function nextDeliveryPersonCode(client: PoolClient) {
const result = await client.query(
`SELECT person_code FROM delivery_persons
WHERE person_code ~ '^DP[0-9]+$'
ORDER BY person_code DESC
LIMIT 1`
);
const last = result.rows[0]?.person_code as string | undefined;
const num = last ? Number(last.replace(/^DP/, '')) + 1 : 1;
return `DP${String(num).padStart(3, '0')}`;
}
async function nextCustomerCode(client: PoolClient) {
const result = await client.query(
`SELECT customer_code FROM customers
WHERE customer_code ~ '^CUST[0-9]+$'
ORDER BY customer_code DESC
LIMIT 1`
);
const last = result.rows[0]?.customer_code as string | undefined;
const num = last ? Number(last.replace(/^CUST/, '')) + 1 : 1;
return `CUST${String(num).padStart(3, '0')}`;
}
function displayName(profile: { username: string; full_name: string; phone: string | null }) {
return profile.full_name || profile.username;
}
async function assertEntityBranch(
client: PoolClient,
table: 'suppliers' | 'delivery_persons' | 'customers',
codeColumn: string,
code: string,
branchCode: string | null,
label: string
) {
const result = await client.query(
`SELECT branch_code FROM ${table} WHERE ${codeColumn} = $1 LIMIT 1`,
[code]
);
if (!result.rowCount) {
throw Object.assign(new Error(`${label}不存在`), { code: 'not_found' });
}
const entityBranch = result.rows[0]?.branch_code as string | null;
if (branchCode && entityBranch && entityBranch !== branchCode) {
throw Object.assign(new Error(`${label}不属于当前分公司`), { code: 'invalid_branch' });
}
}
async function assertNotBoundToOtherUser(
client: PoolClient,
sql: string,
params: unknown[],
userId: string,
label: string
) {
const result = await client.query(sql, params);
const boundUserId = result.rows[0]?.user_id as string | undefined;
if (boundUserId && boundUserId !== userId) {
throw Object.assign(new Error(`${label}已绑定其他登录账号`), { code: 'already_bound' });
}
}
async function loadUserBindingsInCurrentSchema(userId: string): Promise<UserBindingsState> {
const empty = emptyBindings();
const [purchaser, supplier, delivery] = await Promise.all([
pool.query(
`SELECT purchaser_code, purchaser_name, is_primary FROM purchaser_users WHERE user_id = $1 LIMIT 1`,
[userId]
),
pool.query(
`SELECT su.supplier_code, s.company_name
FROM supplier_users su
LEFT JOIN suppliers s ON s.supplier_code = su.supplier_code
WHERE su.user_id = $1 LIMIT 1`,
[userId]
),
pool.query(
`SELECT dpu.person_code, dp.person_name
FROM delivery_person_users dpu
LEFT JOIN delivery_persons dp ON dp.person_code = dpu.person_code
WHERE dpu.user_id = $1 LIMIT 1`,
[userId]
),
]);
if (purchaser.rows[0]) {
empty.purchaser = {
enabled: true,
purchaser_code: purchaser.rows[0].purchaser_code,
purchaser_name: purchaser.rows[0].purchaser_name,
is_primary: Boolean(purchaser.rows[0].is_primary),
};
}
if (supplier.rows[0]) {
empty.supplier = {
enabled: true,
supplier_code: supplier.rows[0].supplier_code,
supplier_name: supplier.rows[0].company_name,
};
}
if (delivery.rows[0]) {
empty.delivery = {
enabled: true,
person_code: delivery.rows[0].person_code,
person_name: delivery.rows[0].person_name,
};
}
return empty;
}
function mergeBindings(into: UserBindingsState, from: UserBindingsState): UserBindingsState {
if (!into.purchaser.enabled && from.purchaser.enabled) into.purchaser = from.purchaser;
if (!into.supplier.enabled && from.supplier.enabled) into.supplier = from.supplier;
if (!into.delivery.enabled && from.delivery.enabled) into.delivery = from.delivery;
return into;
}
export async function loadUserBindings(userId: string): Promise<UserBindingsState> {
if (getTenantDbStore()?.branchCode) {
return loadUserBindingsInCurrentSchema(userId);
}
const merged = emptyBindings();
const tenants = await listActiveTenantBranches();
for (const t of tenants) {
const partial = await runWithTenantDbContext(t.branch_code, () =>
loadUserBindingsInCurrentSchema(userId)
);
mergeBindings(merged, partial);
if (
merged.purchaser.enabled &&
merged.supplier.enabled &&
merged.delivery.enabled
) {
break;
}
}
return merged;
}
async function getBindingOptionsInCurrentSchema(branchCode: string | null, isSuperAdmin: boolean) {
const branchFilter = isSuperAdmin || !branchCode ? '' : 'WHERE branch_code = $1';
const params = isSuperAdmin || !branchCode ? [] : [branchCode];
const [purchasers, suppliers, deliveryPersons, customers] = await Promise.all([
pool.query(
`SELECT pu.purchaser_code, pu.purchaser_name, pu.user_id, p.username AS bound_login
FROM purchaser_users pu
LEFT JOIN public.profiles p ON p.id = pu.user_id
ORDER BY pu.purchaser_code`
),
pool.query(
`SELECT s.supplier_code, s.company_name, su.user_id, p.username AS bound_login
FROM suppliers s
LEFT JOIN supplier_users su ON su.supplier_code = s.supplier_code
LEFT JOIN public.profiles p ON p.id = su.user_id
${branchFilter.replace('branch_code', 's.branch_code')}
ORDER BY s.company_name`,
params
),
pool.query(
`SELECT dp.person_code, dp.person_name, dpu.user_id, p.username AS bound_login
FROM delivery_persons dp
LEFT JOIN delivery_person_users dpu ON dpu.person_code = dp.person_code
LEFT JOIN public.profiles p ON p.id = dpu.user_id
${branchFilter.replace('branch_code', 'dp.branch_code')}
ORDER BY dp.person_name`,
params
),
pool.query(
`SELECT c.customer_code, c.company_name, cpu.user_id, p.username AS bound_login
FROM customers c
LEFT JOIN customer_portal_users cpu ON cpu.customer_code = c.customer_code
LEFT JOIN public.profiles p ON p.id = cpu.user_id
${branchFilter.replace('branch_code', 'c.branch_code')}
ORDER BY c.company_name`,
params
),
]);
return {
purchasers: purchasers.rows,
suppliers: suppliers.rows,
delivery_persons: deliveryPersons.rows,
customers: customers.rows,
};
}
function dedupeByCode<T extends Record<string, unknown>>(rows: T[], codeKey: string): T[] {
const seen = new Set<string>();
const out: T[] = [];
for (const row of rows) {
const code = String(row[codeKey] || '');
if (!code || seen.has(code)) continue;
seen.add(code);
out.push(row);
}
return out;
}
export async function getBindingOptions(branchCode: string | null, isSuperAdmin: boolean) {
const branch = String(branchCode || '').trim();
if (branch) {
return runWithTenantDbContext(branch, () => getBindingOptionsInCurrentSchema(branch, isSuperAdmin));
}
if (!isSuperAdmin) {
return getBindingOptionsInCurrentSchema(null, false);
}
const tenants = await listActiveTenantBranches();
const merged = {
purchasers: [] as Record<string, unknown>[],
suppliers: [] as Record<string, unknown>[],
delivery_persons: [] as Record<string, unknown>[],
customers: [] as Record<string, unknown>[],
};
for (const t of tenants) {
const part = await runWithTenantDbContext(t.branch_code, () =>
getBindingOptionsInCurrentSchema(t.branch_code, true)
);
merged.purchasers.push(...part.purchasers);
merged.suppliers.push(...part.suppliers);
merged.delivery_persons.push(...part.delivery_persons);
merged.customers.push(...part.customers);
}
return {
purchasers: dedupeByCode(merged.purchasers, 'purchaser_code'),
suppliers: dedupeByCode(merged.suppliers, 'supplier_code'),
delivery_persons: dedupeByCode(merged.delivery_persons, 'person_code'),
customers: dedupeByCode(merged.customers, 'customer_code'),
};
}
export async function syncUserBindings(
client: PoolClient,
userId: string,
profile: { username: string; full_name: string; phone: string | null; branch_code: string | null },
bindings?: UserBindingsInput
) {
if (!bindings) return;
if (bindings.purchaser?.enabled) {
const existingForUser = await client.query(
`SELECT purchaser_code FROM purchaser_users WHERE user_id = $1 LIMIT 1`,
[userId]
);
let purchaserCode = String(bindings.purchaser.purchaser_code || '').trim();
if (existingForUser.rowCount) {
purchaserCode = existingForUser.rows[0].purchaser_code;
} else if (bindings.purchaser.create_new !== false || !purchaserCode) {
purchaserCode = await nextPurchaserCode(client);
}
if (!purchaserCode) {
throw Object.assign(new Error('请指定采购员档案'), { code: 'invalid_binding' });
}
await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [userId]);
const existing = await client.query(`SELECT user_id FROM purchaser_users WHERE purchaser_code = $1`, [
purchaserCode,
]);
if (existing.rowCount && existing.rows[0].user_id !== userId) {
throw Object.assign(new Error('该采购员档案已绑定其他登录账号'), { code: 'already_bound' });
}
const purchaserName = profile.full_name || profile.username;
if (existing.rowCount) {
await client.query(
`UPDATE purchaser_users
SET user_id = $1, purchaser_name = $2, username = $3, phone = $4, is_primary = $5, status = 1
WHERE purchaser_code = $6`,
[
userId,
purchaserName,
profile.username,
profile.phone,
Boolean(bindings.purchaser.is_primary),
purchaserCode,
]
);
} else {
await client.query(
`INSERT INTO purchaser_users (user_id, purchaser_code, purchaser_name, username, phone, is_primary, status)
VALUES ($1, $2, $3, $4, $5, $6, 1)`,
[
userId,
purchaserCode,
purchaserName,
profile.username,
profile.phone,
Boolean(bindings.purchaser.is_primary),
]
);
}
if (bindings.purchaser.is_primary && profile.branch_code) {
await client.query(
`UPDATE purchaser_users pu
SET is_primary = false
FROM public.profiles p
WHERE p.id = pu.user_id AND p.branch_code = $1 AND pu.user_id <> $2 AND pu.is_primary = true`,
[profile.branch_code, userId]
);
}
} else {
await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [userId]);
}
if (bindings.supplier?.enabled) {
const existingForUser = await client.query(
`SELECT supplier_code FROM supplier_users WHERE user_id = $1 LIMIT 1`,
[userId]
);
let supplierCode = String(bindings.supplier.supplier_code || '').trim();
if (existingForUser.rowCount) {
supplierCode = existingForUser.rows[0].supplier_code;
} else if (bindings.supplier.create_new !== false || !supplierCode) {
supplierCode = await nextSupplierCode(client);
const name = displayName(profile);
await client.query(
`INSERT INTO suppliers (supplier_code, company_name, contact_name, contact_phone, branch_code, status)
VALUES ($1, $2, $3, $4, $5, 10)
ON CONFLICT (supplier_code) DO NOTHING`,
[supplierCode, `${name}(供应商)`, name, profile.phone, profile.branch_code]
);
}
if (!supplierCode) {
throw Object.assign(new Error('请指定供应商档案'), { code: 'invalid_binding' });
}
await assertEntityBranch(client, 'suppliers', 'supplier_code', supplierCode, profile.branch_code, '供应商');
await assertNotBoundToOtherUser(
client,
`SELECT user_id FROM supplier_users WHERE supplier_code = $1 LIMIT 1`,
[supplierCode],
userId,
'该供应商'
);
await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [userId]);
await client.query(
`INSERT INTO supplier_users (user_id, supplier_code, username, is_primary, status)
VALUES ($1, $2, $3, true, 1)`,
[userId, supplierCode, profile.username]
);
await client.query(
`UPDATE suppliers SET status = 10 WHERE supplier_code = $1 AND status = 0`,
[supplierCode]
);
} else {
const prev = await client.query(
`SELECT supplier_code FROM supplier_users WHERE user_id = $1`,
[userId]
);
await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [userId]);
for (const row of prev.rows) {
await releaseSupplierIfOrphan(client, String(row.supplier_code));
}
}
if (bindings.delivery?.enabled) {
const existingForUser = await client.query(
`SELECT person_code FROM delivery_person_users WHERE user_id = $1 LIMIT 1`,
[userId]
);
let personCode = String(bindings.delivery.person_code || '').trim();
if (existingForUser.rowCount) {
personCode = existingForUser.rows[0].person_code;
} else if (bindings.delivery.create_new !== false || !personCode) {
personCode = await nextDeliveryPersonCode(client);
const name = displayName(profile);
await client.query(
`INSERT INTO delivery_persons (person_code, person_name, phone, branch_code, status)
VALUES ($1, $2, $3, $4, 10)
ON CONFLICT (person_code) DO NOTHING`,
[personCode, `${name}(配送员)`, profile.phone, profile.branch_code]
);
}
if (!personCode) {
throw Object.assign(new Error('请指定配送员档案'), { code: 'invalid_binding' });
}
await assertEntityBranch(client, 'delivery_persons', 'person_code', personCode, profile.branch_code, '配送员');
await assertNotBoundToOtherUser(
client,
`SELECT user_id FROM delivery_person_users WHERE person_code = $1 LIMIT 1`,
[personCode],
userId,
'该配送员'
);
await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [userId]);
await client.query(
`INSERT INTO delivery_person_users (user_id, person_code, username, is_primary, status)
VALUES ($1, $2, $3, true, 1)`,
[userId, personCode, profile.username]
);
await client.query(
`UPDATE delivery_persons
SET status = 10,
phone = COALESCE($2, phone),
person_name = COALESCE(NULLIF($3, ''), person_name)
WHERE person_code = $1`,
[personCode, profile.phone, `${displayName(profile)}(配送员)`]
);
} else {
const prev = await client.query(
`SELECT person_code FROM delivery_person_users WHERE user_id = $1`,
[userId]
);
await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [userId]);
for (const row of prev.rows) {
await releaseDeliveryPersonIfOrphan(client, String(row.person_code));
}
}
}
/**
* 账号解绑后:若配送员档案不再被任何登录账号引用,则停用并从排班中移除,
* 避免「删账号 / 去角色」后配送员列表仍残留孤儿档案。
*/
export async function releaseDeliveryPersonIfOrphan(
client: PoolClient,
personCode: string
): Promise<{ released: boolean }> {
const code = String(personCode || '').trim();
if (!code) return { released: false };
const stillBound = await client.query(
`SELECT 1 FROM delivery_person_users WHERE person_code = $1 LIMIT 1`,
[code]
);
if (stillBound.rowCount) return { released: false };
await client.query(
`UPDATE delivery_persons
SET status = 0, online_status = 'offline'
WHERE person_code = $1 AND status IN (1, 10)`,
[code]
);
await client.query(`DELETE FROM delivery_schedules WHERE person_code = $1`, [code]);
return { released: true };
}
/** 仅停用「账号自动创建」的供应商主档(名称含(供应商)) */
export async function releaseSupplierIfOrphan(
client: PoolClient,
supplierCode: string
): Promise<{ released: boolean }> {
const code = String(supplierCode || '').trim();
if (!code) return { released: false };
const stillBound = await client.query(
`SELECT 1 FROM supplier_users WHERE supplier_code = $1 LIMIT 1`,
[code]
);
if (stillBound.rowCount) return { released: false };
const master = await client.query(
`SELECT company_name FROM suppliers WHERE supplier_code = $1 LIMIT 1`,
[code]
);
const name = String(master.rows[0]?.company_name || '');
if (!name.includes('(供应商)')) return { released: false };
await client.query(
`UPDATE suppliers SET status = 0 WHERE supplier_code = $1 AND status IN (1, 10, 20)`,
[code]
);
return { released: true };
}
/** 仅停用「账号自动创建」的客户主档(名称含(客户)) */
export async function releaseCustomerIfOrphan(
client: PoolClient,
customerCode: string
): Promise<{ released: boolean }> {
const code = String(customerCode || '').trim();
if (!code) return { released: false };
const stillBound = await client.query(
`SELECT 1 FROM customer_portal_users WHERE customer_code = $1 LIMIT 1`,
[code]
);
if (stillBound.rowCount) return { released: false };
const master = await client.query(
`SELECT company_name FROM customers WHERE customer_code = $1 LIMIT 1`,
[code]
);
const name = String(master.rows[0]?.company_name || '');
if (!name.includes('(客户)')) return { released: false };
await client.query(
`UPDATE customers SET status = 0 WHERE customer_code = $1 AND status IN (1, 10)`,
[code]
);
return { released: true };
}
/**
* 删除登录账号前:在各租户内解绑并释放孤儿业务档案。
* 须在 DELETE auth.users 之前调用(以便读到绑定行)。
*/
export async function releaseBindingsBeforeUserDelete(userId: string): Promise<void> {
const id = String(userId || '').trim();
if (!id) return;
const tenants = await listActiveTenantBranches();
for (const t of tenants) {
await runWithTenantDbContext(t.branch_code, async () => {
const client = await pool.connect();
try {
await client.query('BEGIN');
const dpu = await client.query(
`SELECT person_code FROM delivery_person_users WHERE user_id = $1`,
[id]
);
const suppliers = await client.query(
`SELECT supplier_code FROM supplier_users WHERE user_id = $1`,
[id]
);
const customers = await client.query(
`SELECT customer_code FROM customer_portal_users WHERE user_id = $1`,
[id]
);
await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [id]);
await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [id]);
await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [id]);
await client.query(`DELETE FROM customer_portal_users WHERE user_id = $1`, [id]);
for (const row of dpu.rows) {
await releaseDeliveryPersonIfOrphan(client, String(row.person_code));
}
for (const row of suppliers.rows) {
await releaseSupplierIfOrphan(client, String(row.supplier_code));
}
for (const row of customers.rows) {
await releaseCustomerIfOrphan(client, String(row.customer_code));
}
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
});
}
}
/** 供外部定位实体所属分公司(扫 tenant) */
export async function findBindingEntityBranch(
table: 'delivery_persons' | 'customers',
codeColumn: string,
code: string
): Promise<{ exists: boolean; branchCode: string | null }> {
const hit = await findAcrossActiveTenants(
`SELECT branch_code FROM ${table} WHERE ${codeColumn} = $1 LIMIT 1`,
[code]
);
if (!hit) return { exists: false, branchCode: null };
return {
exists: true,
branchCode: (hit.row.branch_code as string | null) ?? hit.branch_code,
};
}