oss-upload.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * 登记材料(营业执照影像)直传——平台 `seoh-unified-oss` 两段式上传。
  3. *
  4. * 口径(`U-97` 2026-11-03 定案/客户§3.5 第八分区,**本仓唯一上传链路**):
  5. * 1. 浏览器持**自己的账号票**向平台取直传凭证:`POST /api/system/seoh-unified-oss/object/presign_post@v1`
  6. * (body:`tenant_id`/`project_id`/`logical_key`/`content_type`);
  7. * 2. 浏览器按回件的 `action_url` + `form_fields` 以 `multipart/form-data` **直传平台桶**,
  8. * 再把 `{object_key, file_name}` 随建案/改档案载荷交给 klt-bos 落库。
  9. *
  10. * ⛔ 三条边界:
  11. * · **字节流⛔ 经 klt-bos**(本册不开上传接口,凭证口归平台——客户§6.1);
  12. * · ⛔ 前端自拼桶物理名/⛔ 自建签名:`action_url` 与 `form_fields` 一律按平台回件原样使用;
  13. * · ⛔ 把签名 URL 落库/存 state 持久化:只把**对象键**交给后端,查看地址每次由后端现签。
  14. */
  15. import { GATEWAY_BASE, newRequestId } from "./gateway";
  16. import { getToken } from "./http";
  17. import { SEO_CTX } from "./platform";
  18. const OSS = `${GATEWAY_BASE}/api/system/seoh-unified-oss`;
  19. /** 对象键业务前缀——与后端 `LICENSE_KEY_PREFIX`(`customer.rs`)**必须一致**:
  20. * 服务端按此前缀校验入库键,放错前缀整笔建档会被 `11103` 拒。 */
  21. export const LICENSE_KEY_PREFIX = "klt/customer/license/";
  22. /** 合同附件对象键前缀——与后端 `bos_invariant::CONTRACT_ATTACHMENT_KEY_PREFIX`
  23. * **必须一致**(两处字面量同步改):合同写口按此前缀放行对象键形态。 */
  24. export const CONTRACT_ATTACHMENT_KEY_PREFIX = "klt/contract/attachment/";
  25. /** 直传成功后交给后端的落库载荷(客户§2.1 成对纪律:两键同生同灭)。 */
  26. export type UploadedObject = { object_key: string; file_name: string };
  27. type PresignPost = {
  28. action_url: string;
  29. bucket?: string;
  30. object_key: string;
  31. file_field_name: string;
  32. form_fields: Record<string, string>;
  33. expires_at?: string;
  34. upload_mode?: string;
  35. content_type?: string;
  36. };
  37. /** 平台回件统一信封拆包(`code !== 10000` 一律抛错,⛔ 拿空凭证去直传)。 */
  38. async function platformPost<T>(path: string, data: unknown): Promise<T> {
  39. const token = getToken();
  40. const r = await fetch(`${OSS}${path}`, {
  41. method: "POST",
  42. headers: {
  43. "Content-Type": "application/json",
  44. "X-Request-Id": newRequestId(),
  45. ...(token ? { Authorization: `Bearer ${token}` } : {}),
  46. },
  47. body: JSON.stringify({ data }),
  48. });
  49. const body = (await r.json().catch(() => null)) as
  50. | { code?: number; message?: string; data?: T }
  51. | null;
  52. if (!body || body.code !== 10000) {
  53. throw new Error(
  54. body?.message ||
  55. `平台对象存储未返回成功信封(HTTP ${r.status})——请确认账号已获授 uos.object.presign_post@v1`,
  56. );
  57. }
  58. return body.data as T;
  59. }
  60. /** 浏览器只认 `file.type`;部分系统对 .pdf/.ofd 会给空串 ⇒ 按后缀兜底(桶策略按 Content-Type 签名)。 */
  61. function contentTypeOf(file: File): string {
  62. const declared = (file.type || "").trim();
  63. if (declared) return declared;
  64. const name = file.name.toLowerCase();
  65. if (name.endsWith(".pdf")) return "application/pdf";
  66. if (name.endsWith(".png")) return "image/png";
  67. if (name.endsWith(".jpg") || name.endsWith(".jpeg")) return "image/jpeg";
  68. if (name.endsWith(".ofd")) return "application/ofd";
  69. return "application/octet-stream";
  70. }
  71. /** 对象键=前缀 + 当日段 + 随机段 + 原后缀(⛔ 带原文件名:中文/空格会做成难排障的键,展示名另存)。 */
  72. function objectKeyFor(prefix: string, fileName: string): string {
  73. const dot = fileName.lastIndexOf(".");
  74. const ext = dot > 0 && dot < fileName.length - 1 ? fileName.slice(dot).toLowerCase() : "";
  75. const rand = globalThis.crypto?.randomUUID?.().replace(/-/g, "") ?? `${Date.now()}${Math.random().toString(16).slice(2)}`;
  76. const day = new Date().toISOString().slice(0, 10).replace(/-/g, "");
  77. return `${prefix}${day}/${rand}${ext}`;
  78. }
  79. /**
  80. * 两段式直传一个文件到平台桶,返回可交给后端的 `{object_key, file_name}`。
  81. *
  82. * 失败一律抛出人话错误:凭证取不到(无权限/空间标识缺失)、桶拒收(`4xx`:多半是
  83. * `Content-Type` 与签名不符或超出桶策略上限)、网络不可达。
  84. */
  85. async function uploadObject(file: File, prefix: string, what: string): Promise<UploadedObject> {
  86. if (!SEO_CTX.tenant_id || !SEO_CTX.project_id) {
  87. throw new Error("缺少项目空间标识(tenant_id/project_id)⇒ 无法向平台对象存储取直传凭证");
  88. }
  89. const contentType = contentTypeOf(file);
  90. const logicalKey = objectKeyFor(prefix, file.name);
  91. const presigned = await platformPost<PresignPost>("/object/presign_post@v1", {
  92. tenant_id: SEO_CTX.tenant_id,
  93. project_id: SEO_CTX.project_id,
  94. logical_key: logicalKey,
  95. content_type: contentType,
  96. });
  97. const form = new FormData();
  98. for (const [k, v] of Object.entries(presigned.form_fields ?? {})) form.append(k, v);
  99. // ⚠️ 平台 POST 策略把 `Content-Type` 写进了条件(`["eq","$Content-Type",…]`)⇒ 该表单字段
  100. // **必须**与签名时声明的一致,缺了就是 `403 Policy Condition failed`(实测踩过)。
  101. form.append("Content-Type", contentType);
  102. form.append(presigned.file_field_name || "file", file, file.name);
  103. let r: Response;
  104. try {
  105. r = await fetch(presigned.action_url, { method: "POST", body: form });
  106. } catch (e) {
  107. throw new Error(`${what}直传失败:对象存储不可达(${(e as Error).message})`);
  108. }
  109. if (!r.ok) {
  110. // S3/MinIO 的 POST 失败回 XML;只取首行给人看,⛔ 把整段 XML 糊到页面上。
  111. const text = await r.text().catch(() => "");
  112. const code = (text.match(/<Code>([^<]+)<\/Code>/) ?? [])[1];
  113. const message = (text.match(/<Message>([^<]+)<\/Message>/) ?? [])[1];
  114. throw new Error(
  115. `${what}直传被对象存储拒绝(HTTP ${r.status}${code ? ` ${code}` : ""}${message ? `:${message}` : ""})` +
  116. "——格式/大小上限随平台桶策略,请换个文件或压缩后重试",
  117. );
  118. }
  119. return { object_key: presigned.object_key || logicalKey, file_name: file.name };
  120. }
  121. /**
  122. * 上传一份营业执照影像,返回可交给后端的 `{object_key, file_name}`。
  123. */
  124. export async function uploadCustomerLicense(file: File): Promise<UploadedObject> {
  125. return uploadObject(file, LICENSE_KEY_PREFIX, "影像");
  126. }
  127. /**
  128. * 上传一份**合同附件**,返回可交给后端的 `{object_key, file_name}`。
  129. *
  130. * 合同附件是**单值**(`contract.attachment_url`)⇒ 调用方只把 `object_key` 交给后端,
  131. * `file_name` 仅用于上传完成后的界面回显;查看地址由后端读口现签,⛔ 前端缓存签名。
  132. */
  133. export async function uploadContractAttachment(file: File): Promise<UploadedObject> {
  134. return uploadObject(file, CONTRACT_ATTACHMENT_KEY_PREFIX, "合同附件");
  135. }