type AuthListener = (event: string, session: Session | null) => void; export interface Session { access_token: string; token_type: string; expires_in: number; user: User; } export interface User { id: string; email?: string; app_metadata?: Record; user_metadata?: Record; } interface ApiError { message: string; code?: string; } 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 }; customer?: { enabled: boolean; customer_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 }; customer: { enabled: boolean; customer_code: string | null; customer_name: string | null }; }; export type UserBindingOptions = { purchasers: Array<{ purchaser_code: string; purchaser_name: string; user_id: string | null; bound_login: string | null; }>; suppliers: Array<{ supplier_code: string; company_name: string; user_id: string | null; bound_login: string | null; }>; delivery_persons: Array<{ person_code: string; person_name: string; user_id: string | null; bound_login: string | null; }>; customers: Array<{ customer_code: string; company_name: string; user_id: string | null; bound_login: string | null; }>; }; export type AdminUserDetail = { id: string; username: string; full_name: string | null; phone: string | null; branch_code: string | null; branch_name?: string | null; status: number; created_at: string; roles: string[]; bindings: UserBindingsState; }; import { buildApiUrl, getApiBase, getSupabaseApiUrl } from './apiConfig'; import { getOperatingBranchHeader } from '../utils/operatingBranch'; import { clearAuthSession, readAuthSessionRaw, touchAuthActivity, writeAuthSessionRaw, } from './authSession'; const authListeners = new Set(); function getStoredSession(): Session | null { try { const raw = readAuthSessionRaw(); return raw ? JSON.parse(raw) : null; } catch (err) { console.warn('解析本地认证会话失败:', err); return null; } } export function setStoredSession(session: Session | null) { if (session) { writeAuthSessionRaw(JSON.stringify(session)); } else { clearAuthSession(); } authListeners.forEach((listener) => listener(session ? 'SIGNED_IN' : 'SIGNED_OUT', session)); } function getAuthHeaders(): Record { touchAuthActivity(); const session = getStoredSession(); const headers: Record = { 'Content-Type': 'application/json', ...getOperatingBranchHeader(), }; if (session?.access_token) { headers.Authorization = `Bearer ${session.access_token}`; } return headers; } let authRedirecting = false; /** * 401 统一登出(FE-1):清 session + 跳 `/login?reason=expired`; * **无 session 不跳**(登录页输错密码等场景)。 * 导出给 `utils/workflowApi.ts` 共用,避免两套请求层行为漂移。 */ export function handleUnauthorized() { if (authRedirecting) return; if (!getStoredSession()) return; // 无会话(如登录页输错密码)不触发自动登出 authRedirecting = true; setStoredSession(null); window.location.href = '/login?reason=expired'; } async function apiFetch(path: string, options: RequestInit = {}): Promise { touchAuthActivity(); // 确保数据接口始终使用 POST,防止网络层(Nginx/CDN/浏览器扩展)将请求误转为 GET const isDataEndpoint = path === '/data/query' || path === '/data/batch'; const method = isDataEndpoint ? 'POST' : (options.method || 'GET'); const response = await fetch(buildApiUrl(path), { ...options, method, headers: { ...getAuthHeaders(), ...(options.headers || {}), }, }); const payload = await response.json().catch(() => ({})); if (!response.ok) { if (response.status === 401) { handleUnauthorized(); } throw payload; } return payload as T; } class QueryBuilder implements PromiseLike<{ data: any; error: ApiError | null; count?: number | null }> { private spec: Record = { action: 'select', filters: [], orders: [] }; constructor(private table: string) { this.spec.table = table; } select(columns = '*', options?: { count?: 'exact' }) { if (this.spec.action === 'insert' || this.spec.action === 'update' || this.spec.action === 'delete') { this.spec.returning = columns; if (options?.count) this.spec.count = options.count; return this; } this.spec.action = 'select'; this.spec.select = columns; if (options?.count) this.spec.count = options.count; return this; } insert(values: unknown) { this.spec.action = 'insert'; this.spec.insertData = values; return this; } update(values: unknown) { this.spec.action = 'update'; this.spec.updateData = values; return this; } delete() { this.spec.action = 'delete'; return this; } eq(column: string, value: unknown) { this.spec.filters.push({ op: 'eq', column, value }); return this; } neq(column: string, value: unknown) { this.spec.filters.push({ op: 'neq', column, value }); return this; } gt(column: string, value: unknown) { this.spec.filters.push({ op: 'gt', column, value }); return this; } gte(column: string, value: unknown) { this.spec.filters.push({ op: 'gte', column, value }); return this; } lt(column: string, value: unknown) { this.spec.filters.push({ op: 'lt', column, value }); return this; } lte(column: string, value: unknown) { this.spec.filters.push({ op: 'lte', column, value }); return this; } in(column: string, value: unknown[]) { this.spec.filters.push({ op: 'in', column, value }); return this; } ilike(column: string, value: string) { this.spec.filters.push({ op: 'ilike', column, value }); return this; } /** value=null → IS NULL;其它真值 → IS NOT NULL(与服务端 queryExecutor 一致) */ is(column: string, value: null | boolean) { this.spec.filters.push({ op: 'is', column, value }); return this; } /** * Supabase 兼容:`.not('col', 'is', null)` → `col IS NOT NULL` * 其它 operator 暂不支持。 */ not(column: string, operator: 'is', value: null) { if (operator === 'is' && value === null) { this.spec.filters.push({ op: 'is', column, value: true }); return this; } throw new Error(`localApiClient.not 暂不支持: ${operator}`); } /** 字段为 NULL / 空串 / 纯空白时匹配(如商品「未分类」) */ emptyOrNull(column: string) { this.spec.filters.push({ op: 'empty_or_null', column }); return this; } or(raw: string) { this.spec.filters.push({ op: 'or', raw }); return this; } order(column: string, options?: { ascending?: boolean }) { this.spec.orders.push({ column, ascending: options?.ascending !== false }); return this; } limit(count: number) { this.spec.limit = count; return this; } range(from: number, to: number) { this.spec.range = { from, to }; return this; } single() { this.spec.single = true; return this; } maybeSingle() { this.spec.single = true; return this; } then( onfulfilled?: ((value: { data: any; error: ApiError | null; count?: number | null }) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null ) { return this.execute().then(onfulfilled, onrejected); } private async execute() { try { const result = await apiFetch<{ data: any; error: ApiError | null; count?: number | null }>('/data/query', { method: 'POST', body: JSON.stringify(this.spec), }); return result; } catch (error: any) { const apiError = error?.error; const message = (typeof apiError === 'object' && apiError?.message) || error?.error_description || (typeof error?.error === 'string' ? error.error : null) || error?.message || '请求失败'; return { data: null, error: { message, code: typeof apiError === 'object' ? apiError?.code : error?.code, }, count: null, }; } } } class StorageBucket { constructor(private bucket: string) {} async upload(path: string, file: File | Blob) { try { const formData = new FormData(); formData.append('file', file); formData.append('path', path); const session = getStoredSession(); const response = await fetch(buildApiUrl(`/storage/${this.bucket}/upload`), { method: 'POST', headers: session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}, body: formData, }); const payload = await response.json(); if (!response.ok) { return { data: null, error: { message: payload.error || '上传失败' } }; } return { data: { path: payload.path }, error: null }; } catch (error: any) { return { data: null, error: { message: error?.message || '上传失败' } }; } } getPublicUrl(path: string) { const filename = path.split('/').pop() || path; const publicUrl = buildApiUrl(`/storage/${this.bucket}/public/${filename}`); return { data: { publicUrl } }; } } export const supabaseAnonKey = 'local-dev-key'; export { touchAuthActivity, getAuthIdleTimeoutMs, getAuthIdleTimeoutMinutes } from './authSession'; export interface BatchOperation { table: string; action: 'insert' | 'update' | 'delete'; insertData?: unknown; updateData?: unknown; filters?: Array<{ op: string; column?: string; value?: unknown; raw?: string }>; returning?: string; } /** 事务性批量写:所有操作在服务端单个事务中执行,任一失败全部回滚;返回各操作结果 */ export async function executeBatch( operations: BatchOperation[] ): Promise> { if (!operations.length) return []; try { const result = await apiFetch<{ data: any; error: ApiError | null }>('/data/batch', { method: 'POST', body: JSON.stringify({ operations }), }); if (result.error) { throw new Error(result.error.message || '批量操作失败'); } return result.data || []; } catch (error: any) { throw new Error(error?.error?.message || error?.message || '批量操作失败'); } } export function getSupabaseUrl(): string { return getSupabaseApiUrl(); } export const supabaseUrl = getApiBase(); export const supabase = { auth: { async getSession() { const session = getStoredSession(); if (!session) { return { data: { session: null }, error: null }; } try { const user = await apiFetch('/auth/user'); return { data: { session: { ...session, user: { ...session.user, ...user }, }, }, error: null, }; } catch (err) { console.warn('获取远程用户信息失败,清除本地会话:', err); setStoredSession(null); return { data: { session: null }, error: null }; } }, onAuthStateChange(callback: AuthListener) { authListeners.add(callback); return { data: { subscription: { unsubscribe: () => { authListeners.delete(callback); }, }, }, }; }, async signInWithPassword(credentials: { email: string; password: string }) { try { const payload = await apiFetch('/auth/token', { method: 'POST', body: JSON.stringify(credentials), }); if (payload?.need_branch || !payload?.access_token || !payload?.user) { return { data: { session: null, user: null }, error: { message: payload?.error_description || '登录失败', code: payload?.need_branch ? 'need_branch' : payload?.error, }, }; } const session: Session = { access_token: payload.access_token, token_type: payload.token_type, expires_in: payload.expires_in, user: payload.user, }; setStoredSession(session); return { data: { session, user: payload.user }, error: null }; } catch (error: any) { return { data: { session: null, user: null }, error: { message: error?.error_description || error?.message || '登录失败', code: error?.error, }, }; } }, async signOut() { setStoredSession(null); try { await apiFetch('/auth/logout', { method: 'POST' }); } catch (err) { console.warn('服务端登出通知失败:', err); } return { error: null }; }, admin: { async createUser(payload: { username: string; password?: string; full_name?: string; phone?: string; branch_code?: string; roles: string[]; bindings?: UserBindingsInput; }) { try { const result = await apiFetch<{ user: AdminUserDetail }>('/auth/admin/users', { method: 'POST', body: JSON.stringify(payload), }); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '创建用户失败' }, }; } }, async getUser(userId: string) { try { const result = await apiFetch<{ user: AdminUserDetail }>( `/auth/admin/users/${encodeURIComponent(userId)}` ); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '加载用户失败' }, }; } }, async getBindingOptions(branchCode?: string) { try { const query = branchCode ? `?branch_code=${encodeURIComponent(branchCode)}` : ''; const result = await apiFetch<{ data: UserBindingOptions; branch_code: string | null }>( `/auth/admin/users/binding-options${query}` ); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '加载绑定选项失败' }, }; } }, async createBranch(payload: { branch_code?: string; branch_name: string; contact_name?: string; contact_phone: string; address?: string; /** 绑定的主系统供应商编码(可选);填了 ⇒ 该分公司管理员回主系统校验密码 */ main_supplier_code?: string | null; }) { try { const result = await apiFetch<{ branch: { branch_code: string; branch_name: string; main_supplier_code?: string | null }; account: { username: string; default_password: string | null; must_change_password: boolean }; }>('/auth/admin/branches', { method: 'POST', body: JSON.stringify(payload), }); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '创建分公司失败' }, }; } }, async updateBranch( branchCode: string, payload: { branch_name: string; contact_name?: string; contact_phone: string; address?: string; /** 传了就更新绑定(`null` = 解绑);不传 = 保持原绑定 */ main_supplier_code?: string | null; supplier_categories?: string; } ) { try { const result = await apiFetch<{ branch: { branch_code: string; branch_name: string; contact_name: string | null; contact_phone: string | null; address: string | null; status: number; tax_level?: string | null; main_supplier_code?: string | null; supplier_categories?: string | null; }; }>(`/auth/admin/branches/${encodeURIComponent(branchCode)}`, { method: 'PUT', body: JSON.stringify(payload), }); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '更新分公司失败' }, }; } }, /** * 该分公司的**接入编码 + 绑定关系**(2026-10-27 接入编码设计)。 * 只读:真正的绑定由主系统在其 `(分公司 × 供应商)` 授权行上维护;`source='manual'` = 超管手工登记。 */ async getBranchBindings(branchCode: string) { try { const result = await apiFetch<{ branch_code: string; active_count: number; bindings: Array<{ branchCode: string; accessCode: string; mainBranchCode: string; mainSupplierCode: string; status: 'active' | 'unbound'; source: string; boundAt: string; unboundAt: string | null; }>; }>(`/auth/admin/branches/${encodeURIComponent(branchCode)}/bindings`); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '读取绑定关系失败' }, }; } }, /** * 当前账号可见的**接入编码**(Web「账号信息」浮层展示用)。 * 超管 = 全部分公司;分公司管理员 = 仅本分公司;其它角色后端 403。 */ async getAccessCodes() { try { const result = await apiFetch<{ access_codes: Array<{ branch_code: string; branch_name: string; access_code: string }>; }>(`/auth/access-codes`); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '读取接入编码失败' }, }; } }, async updateBranchStatus(branchCode: string, status: number) { try { const result = await apiFetch<{ branch: { branch_code: string; status: number } }>( `/auth/admin/branches/${encodeURIComponent(branchCode)}/status`, { method: 'PUT', body: JSON.stringify({ status }), } ); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '更新分公司状态失败' }, }; } }, async updateBranchTaxLevel( branchCode: string, payload: { tax_level: string; apply_to_products?: boolean } ) { try { const result = await apiFetch<{ branch_code: string; tax_level: string; products_updated: number; }>(`/auth/admin/branches/${encodeURIComponent(branchCode)}/tax-level`, { method: 'PUT', body: JSON.stringify(payload), }); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '更新纳税等级失败' }, }; } }, async deleteBranch(branchCode: string) { try { const result = await apiFetch<{ success: boolean }>( `/auth/admin/branches/${encodeURIComponent(branchCode)}`, { method: 'DELETE' } ); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '删除分公司失败' }, }; } }, async updateUser( userId: string, payload: { full_name?: string; phone?: string; /** 登录名可改(全局唯一);后端会同步 auth.users.email */ username?: string; branch_code?: string; password?: string; roles?: string[]; bindings?: UserBindingsInput; } ) { try { const result = await apiFetch<{ success: boolean; bindings?: UserBindingsState }>( `/auth/admin/users/${encodeURIComponent(userId)}`, { method: 'PUT', body: JSON.stringify(payload), } ); return { data: result, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || error?.message || '更新用户失败' }, }; } }, async deleteUser(userId: string) { try { await apiFetch(`/auth/users/${userId}`, { method: 'DELETE' }); return { data: {}, error: null }; } catch (error: any) { return { data: null, error: { message: error?.error_description || '删除用户失败' } }; } }, }, async signUp(payload: { email: string; password: string; options?: { data?: Record } }) { try { const metadata = payload.options?.data || {}; const username = (metadata.username as string) || payload.email.split('@')[0]; const result = await apiFetch<{ user: User }>('/auth/admin/users', { method: 'POST', body: JSON.stringify({ username, password: payload.password, full_name: metadata.full_name, phone: metadata.phone, roles: metadata.roles || ['operator'], }), }); return { data: { user: result.user, session: null }, error: null }; } catch (error: any) { return { data: { user: null, session: null }, error: { message: error?.error_description || error?.message || '注册失败' }, }; } }, }, from(table: string) { return new QueryBuilder(table); }, storage: { from(bucket: string) { return new StorageBucket(bucket); }, }, functions: { async invoke(name: string, options?: { body?: unknown }) { try { const payload = await apiFetch<{ data: any; error: ApiError | null }>(`/functions/${name}`, { method: 'POST', body: JSON.stringify(options?.body || {}), }); return { data: payload.data, error: payload.error }; } catch (error: any) { return { data: null, error: { message: error?.error?.message || error?.message || '函数调用失败', code: error?.error?.code || error?.code, }, }; } }, }, };