-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathSignPDF.vue
More file actions
386 lines (359 loc) · 10.8 KB
/
SignPDF.vue
File metadata and controls
386 lines (359 loc) · 10.8 KB
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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<!--
- SPDX-FileCopyrightText: 2024 LibreCode coop and LibreCode contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<div class="main-view">
<TopBar
v-if="!isMobile"
:sidebar-toggle="true" />
<PdfEditor v-if="mounted && !signStore.errors.length && pdfBlobs.length > 0"
ref="pdfEditor"
width="100%"
height="100%"
:files="pdfBlobs"
:file-names="fileNames.length > 0 ? fileNames : [pdfFileName]"
:read-only="true"
:emit-object-click="true"
@pdf-editor:object-click="dispatchPrimaryAction"
@pdf-editor:end-init="updateSigners" />
<div class="button-wrapper">
<NcButton
v-if="isMobile"
:wide="true"
variant="primary"
@click.prevent="toggleSidebar">
{{ t('libresign', 'Sign') }}
</NcButton>
</div>
<NcNoteCard v-for="(error, index) in signStore.errors"
:key="index"
:heading="error.title || ''"
type="error">
{{ error.message }}
</NcNoteCard>
</div>
</template>
<script>
import { t } from '@nextcloud/l10n'
import NcNoteCard from '@nextcloud/vue/components/NcNoteCard'
import NcButton from '@nextcloud/vue/components/NcButton'
import PdfEditor from '../../components/PdfEditor/PdfEditor.vue'
import TopBar from '../../components/TopBar/TopBar.vue'
import { loadState } from '@nextcloud/initial-state'
import { useFilesStore } from '../../store/files.js'
import { useSidebarStore } from '../../store/sidebar.js'
import { useSignStore } from '../../store/sign.js'
import { generateOcsUrl, generateUrl } from '@nextcloud/router'
import axios from '@nextcloud/axios'
import { FILE_STATUS } from '../../constants.js'
import {
aggregateVisibleElementsByFiles,
findFileById,
getFileSigners,
getFileUrl,
getVisibleElementsFromDocument,
idsMatch,
} from '../../services/visibleElementsService'
export default {
name: 'SignPDF',
components: {
NcNoteCard,
NcButton,
TopBar,
PdfEditor,
},
setup() {
const signStore = useSignStore()
const filesStore = useFilesStore()
const sidebarStore = useSidebarStore()
const isMobile = window.innerWidth <= 512
return { signStore, filesStore, sidebarStore, isMobile }
},
data() {
return {
mounted: false,
pdfBlobs: [],
fileNames: [],
envelopeFiles: [],
}
},
computed: {
pdfFileName() {
const doc = this.signStore.document
const extension = doc.metadata?.extension || 'pdf'
return `${doc.name}.${extension}`
},
},
async created() {
if (await this.redirectIfSigningInProgress()) {
return
}
if (this.$route?.name === 'SignPDFExternal') {
await this.initSignExternal()
} else if (this.$route?.name === 'SignPDF') {
await this.initSignInternal()
} else if (this.$route?.name === 'IdDocsApprove') {
await this.initIdDocsApprove()
}
if (this.isMobile && this.$route?.name !== 'SignPDFExternal') {
this.toggleSidebar();
}
const pdfs = loadState('libresign', 'pdfs', [])
if (pdfs.length > 0) {
await this.handleInitialStatePdfs(pdfs)
} else {
await this.loadPdfsFromStore()
}
this.mounted = true
},
mounted() {
this.setupElementClickListener()
},
beforeUnmount() {
this.removeElementClickListener()
},
beforeRouteLeave(to, from, next) {
this.sidebarStore.hideSidebar()
next()
},
methods: {
t,
isIdDocApproval() {
return this.$route.query.idDocApproval === 'true'
},
addIdDocApprovalParam(url) {
if (!this.isIdDocApproval() || !url) {
return url
}
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}idDocApproval=true`
},
async initSignExternal() {
await this.signStore.initFromState()
if (!this.signStore.document.uuid) {
this.signStore.document.uuid = this.$route.params.uuid
}
},
async initSignInternal() {
const files = await this.filesStore.getAllFiles({
signer_uuid: this.$route.params.uuid,
})
for (const key in files) {
const signer = files[key].signers.find(row => row.me) || {}
if (Object.keys(signer).length > 0) {
this.signStore.setFileToSign(files[key])
this.filesStore.selectFile(parseInt(key))
return
}
}
},
async initIdDocsApprove() {
const url = generateOcsUrl('/apps/libresign/api/v1/file/validate/uuid/{uuid}', { uuid: this.$route.params.uuid })
const response = await axios.get(this.addIdDocApprovalParam(url))
this.signStore.setFileToSign(response.data.ocs.data)
this.filesStore.selectFile(response.data.ocs.data.id)
},
async handleInitialStatePdfs(urls) {
if (!Array.isArray(urls) || urls.length === 0) {
return
}
const blobs = []
for (const url of urls) {
const response = await fetch(url)
const contentType = response.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
const data = await response.json()
this.sidebarStore.hideSidebar()
if (data?.errors?.[0]?.message.length > 0) {
this.signStore.errors = data.errors
} else {
this.signStore.errors = [{ message: t('libresign', 'File not found') }]
}
return
}
const blob = await response.blob()
blobs.push(new File([blob], 'arquivo.pdf', { type: 'application/pdf' }))
}
this.pdfBlobs = blobs
},
async loadPdfsFromStore() {
const doc = this.signStore.document
if (!doc || !doc.nodeId) {
this.signStore.errors = [{ message: t('libresign', 'Document not found') }]
return
}
if (doc.nodeType === 'envelope') {
await this.loadEnvelopePdfs(doc.id)
} else {
const baseFileUrl = doc.url
|| doc.files?.[0]?.file
|| (doc.uuid ? generateUrl('/apps/libresign/p/pdf/{uuid}', { uuid: doc.uuid }) : null)
const fileUrl = this.addIdDocApprovalParam(baseFileUrl)
if (fileUrl) {
await this.handleInitialStatePdfs([fileUrl])
} else {
this.signStore.errors = [{ message: t('libresign', 'Document URL not found') }]
}
}
},
async loadEnvelopePdfs(parentFileId) {
try {
const envelopeFiles = await this.fetchEnvelopeFiles(parentFileId)
this.envelopeFiles = envelopeFiles
if (this.signStore.document) {
this.signStore.document.files = envelopeFiles
}
if (!envelopeFiles.length) {
this.signStore.errors = [{ message: t('libresign', 'Failed to load envelope files') }]
return
}
const fileWithMe = envelopeFiles.find(file => file.signers?.some(row => row.me))
if (fileWithMe) {
this.filesStore.addFile(fileWithMe)
}
const urls = envelopeFiles
.map(file => getFileUrl(file))
.filter(Boolean)
if (!urls.length) {
this.signStore.errors = [{ message: t('libresign', 'Failed to load envelope files') }]
return
}
this.fileNames = envelopeFiles.map(file => `${file.name}.${file.metadata?.extension || 'pdf'}`)
await this.handleInitialStatePdfs(urls)
} catch (error) {
this.signStore.errors = [{ message: t('libresign', 'Failed to load envelope files') }]
}
},
async fetchEnvelopeFiles(parentFileId) {
const cachedEnvelopeFiles = loadState('libresign', 'envelopeFiles', [])
if (Array.isArray(cachedEnvelopeFiles) && cachedEnvelopeFiles.length > 0) {
return cachedEnvelopeFiles
}
const url = generateOcsUrl('/apps/libresign/api/v1/file/list')
const params = new URLSearchParams({
page: '1',
length: '100',
parentFileId: parentFileId.toString(),
signer_uuid: this.$route.params.uuid,
})
const finalUrl = this.addIdDocApprovalParam(`${url}?${params.toString()}`)
const response = await axios.get(finalUrl)
return response.data?.ocs?.data?.data ?? []
},
updateSigners(data) {
if (this.signStore.document.nodeType === 'envelope' && this.envelopeFiles.length > 0) {
const fileIndexById = new Map(
this.envelopeFiles.map((file, index) => [String(file.id), index]),
)
const elements = aggregateVisibleElementsByFiles(this.envelopeFiles)
elements.forEach(element => {
const fileInfo = findFileById(this.envelopeFiles, element.fileId)
const signers = getFileSigners(fileInfo)
const signer = signers.find(row => idsMatch(row.signRequestId, element.signRequestId))
|| signers.find(row => row.me)
if (!signer) {
return
}
const object = structuredClone(signer)
object.readOnly = true
object.element = {
...element,
documentIndex: fileIndexById.get(String(element.fileId)) ?? 0,
}
this.$refs.pdfEditor.addSigner(object)
})
this.signStore.mounted = true
return
}
const currentSigner = this.signStore.document.signers.find(signer => signer.me)
const visibleElements = getVisibleElementsFromDocument(this.signStore.document)
const elementsForSigner = currentSigner
? visibleElements.filter(element => idsMatch(element.signRequestId, currentSigner.signRequestId))
: []
if (currentSigner && elementsForSigner.length > 0) {
elementsForSigner.forEach(element => {
const object = structuredClone(currentSigner)
object.readOnly = true
object.element = element
this.$refs.pdfEditor.addSigner(object)
})
}
this.signStore.mounted = true
},
toggleSidebar() {
this.sidebarStore.toggleSidebar()
},
setupElementClickListener() {
this.$nextTick(() => {
const pdfEditor = this.$refs.pdfEditor?.$el
if (!pdfEditor) {
return
}
this.elementClickHandler = this.dispatchPrimaryAction.bind(this)
pdfEditor.addEventListener('click', this.elementClickHandler, true)
})
},
removeElementClickListener() {
if (this.elementClickHandler) {
const pdfEditor = this.$refs.pdfEditor?.$el
if (pdfEditor) {
pdfEditor.removeEventListener('click', this.elementClickHandler, true)
}
this.elementClickHandler = null
}
},
dispatchPrimaryAction(event) {
if (!this.sidebarStore.show || this.sidebarStore.activeTab !== 'sign-tab') {
this.sidebarStore.activeSignTab()
}
this.signStore.queueAction('sign')
},
async redirectIfSigningInProgress() {
const targetRoute = this.$route?.path?.startsWith('/p/') ? 'ValidationFileExternal' : 'ValidationFile'
let targetUuid = null
const file = this.filesStore.getFile()
if (file && file?.status === FILE_STATUS.SIGNING_IN_PROGRESS) {
targetUuid = loadState('libresign', 'sign_request_uuid', null)
}
if (!targetUuid) {
const initialStatus = loadState('libresign', 'status', null)
if (initialStatus === FILE_STATUS.SIGNING_IN_PROGRESS) {
targetUuid = loadState('libresign', 'sign_request_uuid', null)
}
}
if (targetUuid) {
this.$router.push({
name: targetRoute,
params: { uuid: targetUuid },
state: { isAfterSigned: false, isAsync: true },
})
return true
}
return false
},
},
}
</script>
<style lang="scss">
.bg-gray-100 {
all: unset;
}
</style>
<style lang="scss" scoped>
.main-view {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
align-content: space-between;
position: relative;
:deep(.notecard) {
max-width: 600px;
margin: 0 auto;
}
}
.button-wrapper {
padding: 5px 16px;
}
</style>