Update storage.js via upload script - 2026-11-04 10:50:39

This commit is contained in:
mike 2026-11-04 10:50:44 +08:00
parent ca7596e2da
commit 237eed472c
1 changed files with 72 additions and 1 deletions

View File

@ -79,7 +79,7 @@ async function pump(key) {
const failed = {};
let uploadsInFlight = 0; // 正在上传的文件(图片、附件)
export function hasUnsavedChanges() {
return uploadsInFlight > 0 || Object.values(saveState).some((st) => st.running || st.next) || Object.keys(failed).length > 0;
return uploadsInFlight > 0 || Object.values(saveState).some((st) => st.running || st.next) || Object.values(tplQueue).some((q) => q.running || q.next) || Object.keys(failed).length > 0;
}
export function storageSet(key, value) {
@ -91,6 +91,77 @@ export function storageSet(key, value) {
});
}
// ===== 网站详情模板:一个一个保存,并且先存在本机 =====
// 每次改动:① 立刻写进浏览器本地数据库(IndexedDB),关掉页面也不会丢;② 只把改动的那个模板发给服务器。
// 服务器存成功后,本地这条记录才删掉;下次打开 CRM 时如果本地还有没发出去的,会自动补发(页面上的数据也以本地为准)。
const IDB_NAME = 'crm-local', IDB_STORE = 'tplPending';
let idbP = null;
function idb() {
if (!idbP) idbP = new Promise((ok, bad) => {
const r = indexedDB.open(IDB_NAME, 1);
r.onupgradeneeded = () => r.result.createObjectStore(IDB_STORE, { keyPath: 'id' });
r.onsuccess = () => ok(r.result);
r.onerror = () => bad(r.error);
});
return idbP;
}
async function idbDo(mode, fn) {
const db = await idb();
return new Promise((ok, bad) => {
const tx = db.transaction(IDB_STORE, mode);
const req = fn(tx.objectStore(IDB_STORE));
tx.oncomplete = () => ok(req && req.result);
tx.onerror = () => bad(tx.error);
});
}
// 本地还没同步到服务器的模板:[{ id, t(模板,删除时为 null), index, at }]
export async function localPendingTemplates() {
try { return (await idbDo('readonly', (st) => st.getAll())) || []; } catch (e) { return []; }
}
const tplQueue = {}; // id → { running, next }
async function tplSend(job) {
const res = job.t
? await fetch(`/api/templates/${encodeURIComponent(job.id)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: job.t, index: job.index }) })
: await fetch(`/api/templates/${encodeURIComponent(job.id)}`, { method: 'DELETE' });
if (!res.ok) {
const body = await res.json().catch(() => null);
const kb = job.t ? Math.round(JSON.stringify(job.t).length / 1024) : 0;
const e = new Error(res.status === 413 ? `这个模板太大(约 ${kb.toLocaleString()} KB),被服务器拒收(HTTP 413)。请点"嵌入图片转成文件",或调大 Nginx 的 client_max_body_size` : ((body && body.error) || `模板保存失败(HTTP ${res.status})`));
e.key = 'crm:webDetailTemplates';
throw e;
}
}
async function tplPump(id) {
const q = tplQueue[id];
if (q.running || !q.next) return;
q.running = true;
const job = q.next; q.next = null;
try {
await tplSend(job);
// 发送期间没有新的改动:本地这条可以删了
if (!q.next) { try { await idbDo('readwrite', (st) => { const g = st.get(id); g.onsuccess = () => { if (g.result && g.result.at <= job.at) st.delete(id); }; return g; }); } catch (e) {} }
delete failed['tpl:' + id];
job.waiters.forEach((w) => w.resolve());
} catch (e) {
failed['tpl:' + id] = true;
job.waiters.forEach((w) => w.reject(e));
} finally {
q.running = false;
tplPump(id);
}
}
// t = 模板对象;删除时 t = null。index = 新模板在列表里的位置
export async function saveTemplate(id, t, index) {
const at = Date.now();
try { await idbDo('readwrite', (st) => st.put({ id, t, index, at })); } catch (e) { console.warn('[storage] 本地保存模板失败', e); }
return new Promise((resolve, reject) => {
const q = tplQueue[id] || (tplQueue[id] = { running: false, next: null });
if (q.next) { Object.assign(q.next, { t, index, at }); q.next.waiters.push({ resolve, reject }); }
else q.next = { id, t, index, at, waiters: [{ resolve, reject }] };
tplPump(id);
});
}
// 上传一个与客户相关的沟通附件(文件本身存到磁盘,元数据由调用方存进客户记录)
export async function uploadFile(customerId, file) {
uploadsInFlight++;