Blame view

美国版/Food Labeling Management App UniApp/src/utils/offlineSyncManager.ts 9.1 KB
699ea6e8   杨鑫   完善打印逻辑
1
2
3
  import { fetchLabelCategoryPage } from '../services/labelCategory'
  import { fetchProductCategoryPage } from '../services/productCategory'
  import { usAppFetchLocationDetail, usAppFetchMyLocations, usAppFetchMyProfile } from '../services/usAppAuth'
923d50c0   杨鑫   更新bug
4
5
6
7
8
  import {
    fetchUsAppLabelingTree,
    fetchUsAppPrintLogList,
    prefetchUsAppLabelPreviewsForLocation,
  } from '../services/usAppLabeling'
fdce24a6   杨鑫   修改bug
9
  import type { UsAppLabelCategoryTreeNodeDto } from '../types/usAppLabeling'
923d50c0   杨鑫   更新bug
10
11
12
13
14
15
16
  import { fetchGlobalSupportContact } from '../services/locationSupport'
  import {
    getAccessToken,
    getBoundLocations,
    isLoggedIn,
    setBoundLocations,
  } from './authSession'
699ea6e8   杨鑫   完善打印逻辑
17
18
19
20
21
22
23
24
25
26
27
28
  import { getCurrentStoreId } from './stores'
  import {
    clearFailedOfflineMutations,
    getOfflineMutationById,
    getOfflineSyncSummary,
    getPendingOfflineMutations,
    getPendingOfflineMutationsPreview,
    initOfflineSqlite,
    isNetworkOnline,
    markOfflineMutationDone,
    markOfflineMutationFailed,
    removeOfflineMutationById,
923d50c0   杨鑫   更新bug
29
    refreshOfflineAuthAccountSession,
699ea6e8   杨鑫   完善打印逻辑
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  } from './sqliteSync'
  import type { MutationRow } from './sqliteSync'
  import { usAppApiRequest } from './usAppApiRequest'
  
  export type OfflineSyncStats = {
    online: boolean
    lastSyncAt: number
    labels: { total: number; synced: number; pending: number }
    photos: { total: number; synced: number; pending: number }
    pendingMutations: number
  }
  
  export type OfflinePendingMutationPreview = {
    id: number
    method: 'POST' | 'PUT' | 'DELETE'
    endpoint: string
    createdAt: number
    lastError: string | null
  }
  
  export type OfflineSyncExecutionDetail = {
    total: number
    success: number
    failed: number
    at: number
  }
  
  const KEY_LAST_SYNC_AT = '__offline_last_sync_at__'
  const KEY_LAST_SYNC_EXECUTION = '__offline_last_sync_execution__'
  
  function getLastSyncAt(): number {
    return Number(uni.getStorageSync(KEY_LAST_SYNC_AT) || 0)
  }
  
  function setLastSyncAt(value: number): void {
    uni.setStorageSync(KEY_LAST_SYNC_AT, value)
  }
  
  function getLastSyncExecutionDetail(): OfflineSyncExecutionDetail {
    try {
      const raw = String(uni.getStorageSync(KEY_LAST_SYNC_EXECUTION) || '').trim()
      if (!raw) return { total: 0, success: 0, failed: 0, at: 0 }
      const p = JSON.parse(raw) as Partial<OfflineSyncExecutionDetail>
      return {
        total: Number(p.total || 0),
        success: Number(p.success || 0),
        failed: Number(p.failed || 0),
        at: Number(p.at || 0),
      }
    } catch {
      return { total: 0, success: 0, failed: 0, at: 0 }
    }
  }
  
  function setLastSyncExecutionDetail(detail: OfflineSyncExecutionDetail): void {
    uni.setStorageSync(KEY_LAST_SYNC_EXECUTION, JSON.stringify(detail))
  }
  
fdce24a6   杨鑫   修改bug
88
89
90
91
92
93
94
95
96
97
98
99
100
  /** 后台预拉标签 preview(不阻塞登录/同步 UI) */
  async function prefetchLabelPreviewsInBackground(
    tasks: Array<{ locId: string; tree: UsAppLabelCategoryTreeNodeDto[] }>,
  ): Promise<void> {
    for (const { locId, tree } of tasks) {
      try {
        await prefetchUsAppLabelPreviewsForLocation(locId, tree)
      } catch {
        // 单店失败不阻断其余门店
      }
    }
  }
  
699ea6e8   杨鑫   完善打印逻辑
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
  export async function performInitialOfflineSync(): Promise<void> {
    await initOfflineSqlite()
    const online = await isNetworkOnline()
    if (!online) return
  
    const profile = await usAppFetchMyProfile()
    if (profile.fullName?.trim()) {
      uni.setStorageSync('userName', profile.fullName.trim())
    }
  
    const locations = await usAppFetchMyLocations()
    setBoundLocations(locations)
    const currentStoreId = getCurrentStoreId() || locations?.[0]?.id || ''
    const targetLocationIds = Array.from(
      new Set(
        [currentStoreId, ...locations.map((x) => x.id).filter(Boolean)].filter((x) => !!String(x).trim())
      )
    )
fdce24a6   杨鑫   修改bug
119
    const previewPrefetchTasks: Array<{ locId: string; tree: UsAppLabelCategoryTreeNodeDto[] }> = []
699ea6e8   杨鑫   完善打印逻辑
120
121
    for (const locId of targetLocationIds) {
      // 每个门店一组缓存,确保离线切店后仍有可读数据
923d50c0   杨鑫   更新bug
122
      const [, treeResult] = await Promise.allSettled([
699ea6e8   杨鑫   完善打印逻辑
123
124
125
126
        usAppFetchLocationDetail(locId),
        fetchUsAppLabelingTree({ locationId: locId }),
        fetchUsAppPrintLogList({ locationId: locId, skipCount: 1, maxResultCount: 20 }),
      ])
923d50c0   杨鑫   更新bug
127
      if (treeResult.status === 'fulfilled' && Array.isArray(treeResult.value)) {
fdce24a6   杨鑫   修改bug
128
        previewPrefetchTasks.push({ locId, tree: treeResult.value })
923d50c0   杨鑫   更新bug
129
      }
699ea6e8   杨鑫   完善打印逻辑
130
131
132
133
    }
    await Promise.allSettled([
      fetchLabelCategoryPage({ skipCount: 1, maxResultCount: 100, state: true }),
      fetchProductCategoryPage({ skipCount: 1, maxResultCount: 100, state: true }),
923d50c0   杨鑫   更新bug
134
      fetchGlobalSupportContact(),
699ea6e8   杨鑫   完善打印逻辑
135
    ])
923d50c0   杨鑫   更新bug
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  
    if (isLoggedIn()) {
      const email = String(uni.getStorageSync('user_email') || '').trim()
      if (email) {
        await refreshOfflineAuthAccountSession({
          email,
          token: getAccessToken(),
          refreshToken: String(uni.getStorageSync('refresh_token') || ''),
          locations: getBoundLocations(),
          displayName: String(uni.getStorageSync('userName') || email),
        })
      }
    }
  
699ea6e8   杨鑫   完善打印逻辑
150
    setLastSyncAt(Date.now())
fdce24a6   杨鑫   修改bug
151
152
153
154
155
  
    // 预览接口仅用于离线缓存,逐条 POST 成本高;放后台预拉,避免阻塞登录/手动同步
    if (previewPrefetchTasks.length > 0) {
      void prefetchLabelPreviewsInBackground(previewPrefetchTasks)
    }
699ea6e8   杨鑫   完善打印逻辑
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
  }
  
  export async function flushPendingMutations(): Promise<number> {
    const online = await isNetworkOnline()
    if (!online) throw new Error('No network connection')
    await initOfflineSqlite()
    const list = await getPendingOfflineMutations()
    let ok = 0
    for (const row of list) {
      try {
        const payload = JSON.parse(row.payloadJson || 'null')
        await usAppApiRequest<unknown>({
          path: row.endpoint,
          method: row.method as 'POST' | 'PUT' | 'DELETE',
          auth: true,
          data: payload,
        })
        await markOfflineMutationDone(row.id)
        ok += 1
      } catch (e: unknown) {
        const msg = e instanceof Error ? e.message : String(e)
        await markOfflineMutationFailed(row.id, msg)
      }
    }
    return ok
  }
  
  async function flushPendingMutationsWithDetail(): Promise<OfflineSyncExecutionDetail> {
    const online = await isNetworkOnline()
    if (!online) throw new Error('No network connection')
    await initOfflineSqlite()
    const list = await getPendingOfflineMutations()
    let success = 0
    let failed = 0
    for (const row of list) {
      try {
        const payload = JSON.parse(row.payloadJson || 'null')
        await usAppApiRequest<unknown>({
          path: row.endpoint,
          method: row.method as 'POST' | 'PUT' | 'DELETE',
          auth: true,
          data: payload,
        })
        await markOfflineMutationDone(row.id)
        success += 1
      } catch (e: unknown) {
        const msg = e instanceof Error ? e.message : String(e)
        await markOfflineMutationFailed(row.id, msg)
        failed += 1
      }
    }
    const d: OfflineSyncExecutionDetail = {
      total: list.length,
      success,
      failed,
      at: Date.now(),
    }
    setLastSyncExecutionDetail(d)
    return d
  }
  
  export async function syncNowAndRefreshCaches(): Promise<OfflineSyncStats> {
    // 先回放本地待同步变更,再拉最新云端数据刷新本地缓存,避免“刚同步又被旧缓存覆盖”
    await flushPendingMutationsWithDetail()
    await performInitialOfflineSync()
    setLastSyncAt(Date.now())
    return getOfflineSyncStats()
  }
  
  export async function getOfflineSyncStats(): Promise<OfflineSyncStats> {
    const online = await isNetworkOnline()
    const summary = await getOfflineSyncSummary()
    const lastSyncAt = getLastSyncAt()
    return {
      online,
      lastSyncAt,
      labels: {
        total: summary.cacheCount,
        synced: summary.cacheCount,
        pending: summary.pendingMutationCount,
      },
      photos: {
        total: 0,
        synced: 0,
        pending: 0,
      },
      pendingMutations: summary.pendingMutationCount,
    }
  }
  
  function toPreviewRow(x: MutationRow): OfflinePendingMutationPreview {
    return {
      id: x.id,
      method: x.method,
      endpoint: x.endpoint,
      createdAt: x.createdAt,
      lastError: x.lastError ?? null,
    }
  }
  
  export async function getOfflinePendingMutationPreviewList(limit = 20): Promise<OfflinePendingMutationPreview[]> {
    const rows = await getPendingOfflineMutationsPreview(limit)
    return rows.map(toPreviewRow)
  }
  
  export function getOfflineLastSyncExecutionDetail(): OfflineSyncExecutionDetail {
    return getLastSyncExecutionDetail()
  }
  
  export async function retryOfflineMutationById(id: number): Promise<{ ok: boolean; message?: string }> {
    const online = await isNetworkOnline()
    if (!online) return { ok: false, message: 'No network connection' }
    await initOfflineSqlite()
    const row = await getOfflineMutationById(id)
    if (!row) return { ok: false, message: 'Queue item not found' }
    try {
      const payload = JSON.parse(row.payloadJson || 'null')
      await usAppApiRequest<unknown>({
        path: row.endpoint,
        method: row.method as 'POST' | 'PUT' | 'DELETE',
        auth: true,
        data: payload,
      })
      await markOfflineMutationDone(row.id)
      return { ok: true }
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e)
      await markOfflineMutationFailed(row.id, msg)
      return { ok: false, message: msg || 'Retry failed' }
    }
  }
  
  export async function removeOfflineMutation(id: number): Promise<void> {
    await removeOfflineMutationById(id)
  }
  
  export async function clearFailedOfflineMutationItems(): Promise<number> {
    return clearFailedOfflineMutations()
  }