刘光辉
4 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
/* @vitest-environment happy-dom */
 
import { flushPromises, mount } from '@vue/test-utils';
 
import { beforeEach, describe, expect, it, vi } from 'vitest';
 
import RecordView from '../index.vue';
import { ElnRecordOpenParamError, resolveElnRecordOpenParams, toElnRecordOfficeConfigQuery, unwrapElnRecordEditorConfig } from '../recordView';
 
const apiMocks = vi.hoisted(() => ({
  getOnlyOfficeConfig: vi.fn(),
  getOnlyOfficeSaveStatus: vi.fn(),
}));
const messageMocks = vi.hoisted(() => ({
  confirmOptions: undefined as any,
  createConfirm: vi.fn((options: any) => {
    messageMocks.confirmOptions = options;
    return { destroy: vi.fn() };
  }),
  error: vi.fn(),
}));
const editorMocks = vi.hoisted(() => ({ requestClose: vi.fn() }));
const viewParams = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
 
vi.mock('#/api/x/onlyoffice', () => ({
  getOnlyOfficeConfig: apiMocks.getOnlyOfficeConfig,
  getOnlyOfficeSaveStatus: apiMocks.getOnlyOfficeSaveStatus,
}));
vi.mock('@jnpf/hooks', () => ({
  useMessage: () => ({ createConfirm: messageMocks.createConfirm, createMessage: { error: messageMocks.error } }),
}));
vi.mock('#/utils/jnpf', () => ({
  onlineUtils: {
    getViewParam: (name: string) => viewParams.current[name],
  },
}));
vi.mock('#/components/OnlyOfficeEditor/src/Editor.vue', async () => {
  const { defineComponent, h } = await import('vue');
  return {
    default: defineComponent({
      name: 'OnlyOfficeEditor',
      emits: ['close', 'modified'],
      props: { config: { required: true, type: Object } },
      setup(_props, { expose }) {
        expose({ requestClose: editorMocks.requestClose });
        return () => h('div', { 'data-test': 'onlyoffice-editor' });
      },
    }),
  };
});
 
const DOCUMENT = { fileExtension: 'docx', fileId: 'file-1', fileSize: 12, name: 'ELN-001.docx' };
const EDITOR_CONFIG = {
  data: {
    document: { key: 'record-1-r1', title: 'ELN-001.docx', url: 'https://example.test/ELN-001.docx' },
    documentType: 'word',
    editorConfig: { mode: 'edit' },
    token: 'signed-token',
  },
};
 
describe('eLN record view', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    messageMocks.confirmOptions = undefined;
    editorMocks.requestClose.mockReset();
    viewParams.current = { document: DOCUMENT, recordId: 'record-1', revisionId: 'revision-1' };
    apiMocks.getOnlyOfficeConfig.mockResolvedValue(EDITOR_CONFIG);
    apiMocks.getOnlyOfficeSaveStatus.mockResolvedValue({ data: { lastSaveTime: 1000, sessionStatus: 'IDLE', version: 2 } });
  });
 
  it('rejects incomplete custom-view parameters before requesting an editor config', () => {
    expect(() => resolveElnRecordOpenParams(() => undefined)).toThrow(ElnRecordOpenParamError);
  });
 
  it('shows the parameter error without requesting an editor config', async () => {
    viewParams.current = { recordId: 'record-1', revisionId: 'revision-1' };
    const wrapper = mount(RecordView);
    await flushPromises();
 
    expect(wrapper.find('[data-test="record-error"]').text()).toContain('缺少 ELN 记录文档');
    expect(apiMocks.getOnlyOfficeConfig).not.toHaveBeenCalled();
  });
 
  it('requests the fixed record fill context while leaving the final mode to the backend', () => {
    const source: Record<string, unknown> = { document: DOCUMENT, recordId: 'record-1', revisionId: 'revision-1' };
    const params = resolveElnRecordOpenParams((name) => source[name]);
 
    expect(toElnRecordOfficeConfigQuery(params)).toEqual({
      bizDataId: 'record-1',
      bizModule: 'eln.record',
      bizScene: 'eln.record.fill',
      fileId: 'file-1',
      fileName: 'ELN-001.docx',
      fileType: 'annex',
      mode: 'edit',
    });
  });
 
  it('keeps an explicitly requested readonly record view readonly', () => {
    const source: Record<string, unknown> = {
      document: DOCUMENT,
      mode: 'view',
      recordId: 'record-1',
      revisionId: 'revision-1',
    };
    const params = resolveElnRecordOpenParams((name) => source[name]);
 
    expect(params.mode).toBe('view');
    expect(toElnRecordOfficeConfigQuery(params).mode).toBe('view');
  });
 
  it('shows a loading state, then renders the editor after the backend returns an editable config', async () => {
    let resolveConfig: (value: typeof EDITOR_CONFIG) => void = () => {};
    apiMocks.getOnlyOfficeConfig.mockReturnValue(
      new Promise((resolve) => {
        resolveConfig = resolve;
      }),
    );
    const wrapper = mount(RecordView);
 
    expect(wrapper.find('[data-test="record-loading"]').exists()).toBe(true);
    expect(apiMocks.getOnlyOfficeConfig).toHaveBeenCalledWith({
      bizDataId: 'record-1',
      bizModule: 'eln.record',
      bizScene: 'eln.record.fill',
      fileId: 'file-1',
      fileName: 'ELN-001.docx',
      fileType: 'annex',
      mode: 'edit',
    });
 
    resolveConfig(EDITOR_CONFIG);
    await flushPromises();
 
    expect(wrapper.find('[data-test="record-editor"]').exists()).toBe(true);
  });
 
  it('accepts a backend downgrade to readonly mode', () => {
    expect(
      unwrapElnRecordEditorConfig({
        data: {
          document: { key: 'record-1-r1' },
          editorConfig: { mode: 'view' },
          token: 'signed-token',
        },
      }).editorConfig.mode,
    ).toBe('view');
  });
 
  it('leaves source synchronization to the record fill plugin', async () => {
    const wrapper = mount(RecordView);
    await flushPromises();
 
    expect(wrapper.find('[data-test="source-sync-button"]').exists()).toBe(false);
    expect(wrapper.find('.eln-record-view__toolbar').exists()).toBe(false);
  });
 
  it('blocks close for unapplied plugin drafts, then waits for the server session to become idle', async () => {
    const wrapper = mount(RecordView);
    await flushPromises();
 
    window.dispatchEvent(
      new MessageEvent('message', {
        data: {
          bizDataId: 'record-1',
          documentId: 'file-1',
          pendingCount: 2,
          type: 'jnpf:eln-record-fill-state',
          version: 1,
        },
      }),
    );
 
    const cancelledClose = (wrapper.vm as any).requestClose();
    await flushPromises();
    expect(messageMocks.createConfirm).toHaveBeenCalledTimes(1);
    expect(messageMocks.confirmOptions.content).toContain('2 个字段尚未应用');
    messageMocks.confirmOptions.onCancel();
    await expect(cancelledClose).resolves.toBe(false);
    expect(apiMocks.getOnlyOfficeSaveStatus).not.toHaveBeenCalled();
 
    wrapper.getComponent({ name: 'OnlyOfficeEditor' }).vm.$emit('modified', true);
    const confirmedClose = (wrapper.vm as any).requestClose();
    await flushPromises();
    await messageMocks.confirmOptions.onOk();
    await expect(confirmedClose).resolves.toBe('pending');
 
    expect(editorMocks.requestClose).toHaveBeenCalledTimes(1);
    expect(apiMocks.getOnlyOfficeSaveStatus).not.toHaveBeenCalled();
    wrapper.getComponent({ name: 'OnlyOfficeEditor' }).vm.$emit('close');
    await flushPromises();
 
    expect(apiMocks.getOnlyOfficeSaveStatus).toHaveBeenCalledWith('file-1', 'annex');
    expect(wrapper.find('[data-test="record-editor"]').exists()).toBe(false);
    expect(wrapper.emitted('closeStarted')).toHaveLength(1);
    expect(wrapper.emitted('closeCancelled')).toBeUndefined();
    expect(wrapper.emitted('closeReady')).toHaveLength(1);
    wrapper.unmount();
  });
 
  it('closes an unmodified editor without starting a save confirmation flow', async () => {
    const wrapper = mount(RecordView);
    await flushPromises();
 
    await expect((wrapper.vm as any).requestClose()).resolves.toBe(true);
 
    expect(editorMocks.requestClose).not.toHaveBeenCalled();
    expect(apiMocks.getOnlyOfficeSaveStatus).not.toHaveBeenCalled();
    wrapper.unmount();
  });
 
  it('closes directly when an unmodified editor requests close', async () => {
    const wrapper = mount(RecordView);
    await flushPromises();
 
    wrapper.getComponent({ name: 'OnlyOfficeEditor' }).vm.$emit('close');
    await flushPromises();
 
    expect(apiMocks.getOnlyOfficeSaveStatus).not.toHaveBeenCalled();
    expect(wrapper.emitted('closeStarted')).toBeUndefined();
    expect(wrapper.emitted('closeReady')).toHaveLength(1);
    wrapper.unmount();
  });
 
  it('reopens through the backend and stays on the record view when saving fails', async () => {
    apiMocks.getOnlyOfficeSaveStatus.mockResolvedValue({ data: { lastSaveTime: 1000, sessionStatus: 'SAVE_FAILED', version: 1 } });
    const wrapper = mount(RecordView);
    await flushPromises();
    wrapper.getComponent({ name: 'OnlyOfficeEditor' }).vm.$emit('modified', true);
 
    await expect((wrapper.vm as any).requestClose()).resolves.toBe('pending');
    wrapper.getComponent({ name: 'OnlyOfficeEditor' }).vm.$emit('close');
    await flushPromises();
 
    expect(apiMocks.getOnlyOfficeConfig).toHaveBeenCalledTimes(2);
    await vi.waitFor(() => expect(wrapper.find('[data-test="record-editor"]').exists()).toBe(true));
    expect(wrapper.emitted('closeStarted')).toHaveLength(1);
    expect(wrapper.emitted('closeCancelled')).toHaveLength(1);
    expect(wrapper.emitted('closeReady')).toBeUndefined();
    expect(messageMocks.error).toHaveBeenCalledWith('电子记录保存失败,请联系管理员处理后重试');
    wrapper.unmount();
  });
 
  it('shows a clear error instead of mounting the editor when the config request fails', async () => {
    apiMocks.getOnlyOfficeConfig.mockRejectedValue(new Error('无权打开该 ELN 记录'));
    const wrapper = mount(RecordView);
    await flushPromises();
 
    expect(wrapper.find('[data-test="record-error"]').text()).toContain('无权打开该 ELN 记录');
    expect(wrapper.find('[data-test="record-editor"]').exists()).toBe(false);
  });
});