From 5bb66fec3f13ac937a25022518673780638eda83 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 12 Jan 2023 15:16:38 +0100 Subject: [PATCH] test(docuware): back tests --- back/methods/docuware/basic.js | 6 + back/methods/docuware/checkFile.js | 2 +- back/methods/docuware/deliveryNoteEmail.js | 2 +- back/methods/docuware/download.js | 7 +- back/methods/docuware/specs/checkFile.spec.js | 104 ++++++++++-------- back/methods/docuware/specs/download.spec.js | 55 +++++---- back/methods/docuware/specs/upload.spec.js | 35 ++++++ back/methods/docuware/upload.js | 22 +++- loopback/locale/es.json | 6 +- modules/ticket/front/descriptor-menu/index.js | 12 +- package-lock.json | 28 +++-- package.json | 2 +- 12 files changed, 181 insertions(+), 100 deletions(-) create mode 100644 back/methods/docuware/specs/upload.spec.js diff --git a/back/methods/docuware/basic.js b/back/methods/docuware/basic.js index 1f00e67e4..5c1d7bfa9 100644 --- a/back/methods/docuware/basic.js +++ b/back/methods/docuware/basic.js @@ -20,6 +20,9 @@ module.exports = Self => { const options = await Self.getOptions(); + // if (!process.env.NODE_ENV) + // return Math.round(); + const response = await axios.get(`${options.url}/FileCabinets/${fileCabinetId}/dialogs`, options.headers); const dialogs = response.data.Dialog; const dialogId = dialogs.find(dialogs => dialogs.DisplayName === docuwareInfo.dialogName).Id; @@ -41,6 +44,9 @@ module.exports = Self => { } }); + // if (!process.env.NODE_ENV) + // return Math.round(); + const fileCabinetResponse = await axios.get(`${options.url}/FileCabinets`, options.headers); const fileCabinets = fileCabinetResponse.data.FileCabinet; const fileCabinetId = fileCabinets.find(fileCabinet => fileCabinet.Name === docuwareInfo.fileCabinetName).Id; diff --git a/back/methods/docuware/checkFile.js b/back/methods/docuware/checkFile.js index c0fbbff8b..c5c4abec0 100644 --- a/back/methods/docuware/checkFile.js +++ b/back/methods/docuware/checkFile.js @@ -70,7 +70,7 @@ module.exports = Self => { if (!documents) return false; const state = documents.Fields.find(field => field.FieldName == 'ESTADO'); - if (state != 'Firmado') return false; + if (state.Item != 'Firmado') return false; return {id: documents.Id}; } catch (error) { diff --git a/back/methods/docuware/deliveryNoteEmail.js b/back/methods/docuware/deliveryNoteEmail.js index afb8bf980..1f9d7556f 100644 --- a/back/methods/docuware/deliveryNoteEmail.js +++ b/back/methods/docuware/deliveryNoteEmail.js @@ -59,7 +59,7 @@ module.exports = Self => { const email = new Email('delivery-note', params); - const docuwareFile = await Self.app.models.Docuware.download(ctx, id, 'deliveryClient', 'findTicket'); + const docuwareFile = await Self.app.models.Docuware.download(ctx, id, 'deliveryNote'); return email.send({ overrideAttachments: true, diff --git a/back/methods/docuware/download.js b/back/methods/docuware/download.js index 7f5b71ffb..880b51b34 100644 --- a/back/methods/docuware/download.js +++ b/back/methods/docuware/download.js @@ -1,5 +1,5 @@ /* eslint max-len: ["error", { "code": 180 }]*/ -const got = require('got'); +const axios = require('axios'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -48,13 +48,14 @@ module.exports = Self => { const fileCabinetId = await Self.getFileCabinet(fileCabinet); const options = await Self.getOptions(); + options.headers.responseType = 'stream'; const fileName = `filename="${id}.pdf"`; const contentType = 'application/pdf'; const downloadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/FileDownload?targetFileType=Auto&keepAnnotations=false`; - const stream = got.stream(downloadUri, options.headers); + const stream = await axios.get(downloadUri, options.headers); - return [stream, contentType, fileName]; + return [stream.data, contentType, fileName]; }; }; diff --git a/back/methods/docuware/specs/checkFile.spec.js b/back/methods/docuware/specs/checkFile.spec.js index 1f4308190..3cb1a4074 100644 --- a/back/methods/docuware/specs/checkFile.spec.js +++ b/back/methods/docuware/specs/checkFile.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; -const got = require('got'); +const axios = require('axios'); -xdescribe('docuware download()', () => { +fdescribe('docuware download()', () => { const ticketId = 1; const userId = 9; const ctx = { @@ -12,53 +12,71 @@ xdescribe('docuware download()', () => { } }; - const fileCabinetName = 'deliveryClient'; - const dialogDisplayName = 'find'; - const dialogName = 'findTicket'; + const docuwareModel = models.Docuware; + const fileCabinetName = 'deliveryNote'; - const gotGetResponse = { - body: JSON.stringify( - { - FileCabinet: [ - {Id: 12, Name: fileCabinetName} - ], - Dialog: [ - {Id: 34, DisplayName: dialogDisplayName} - ] - }) - }; - - it('should return exist file in docuware', async() => { - const gotPostResponse = { - body: JSON.stringify( - { - Items: [ - {Id: 56} - ], - }) - }; - - spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse))); - spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse))); - - const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName, dialogName); - - expect(result).toEqual(true); + beforeAll(() => { + spyOn(docuwareModel, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random())))); + spyOn(docuwareModel, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random())))); }); - it('should return not exist file in docuware', async() => { - const gotPostResponse = { - body: JSON.stringify( - { - Items: [], - }) + it('should return false if there are no documents', async() => { + const response = { + data: { + Items: [] + } }; + spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(response))); - spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse))); - spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse))); - - const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName, dialogName); + const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName); expect(result).toEqual(false); }); + + it('should return false if the document is unsigned', async() => { + const response = { + data: { + Items: [ + { + Id: 1, + Fields: [ + { + FieldName: 'ESTADO', + Item: 'Unsigned' + } + ] + } + ] + } + }; + spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(response))); + + const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName); + + expect(result).toEqual(false); + }); + + it('should return the document data', async() => { + const docuwareId = 1; + const response = { + data: { + Items: [ + { + Id: docuwareId, + Fields: [ + { + FieldName: 'ESTADO', + Item: 'Firmado' + } + ] + } + ] + } + }; + spyOn(axios, 'post').and.returnValue(new Promise(resolve => resolve(response))); + + const result = await models.Docuware.checkFile(ctx, ticketId, fileCabinetName); + + expect(result.id).toEqual(docuwareId); + }); }); diff --git a/back/methods/docuware/specs/download.spec.js b/back/methods/docuware/specs/download.spec.js index f373b34a1..b1eff2c0d 100644 --- a/back/methods/docuware/specs/download.spec.js +++ b/back/methods/docuware/specs/download.spec.js @@ -1,8 +1,8 @@ const models = require('vn-loopback/server/server').models; -const got = require('got'); +const axios = require('axios'); const stream = require('stream'); -xdescribe('docuware download()', () => { +fdescribe('docuware download()', () => { const userId = 9; const ticketId = 1; const ctx = { @@ -13,36 +13,33 @@ xdescribe('docuware download()', () => { } }; - it('should return the downloaded file name', async() => { - const fileCabinetName = 'deliveryClient'; - const dialogDisplayName = 'find'; - const dialogName = 'findTicket'; - const gotGetResponse = { - body: JSON.stringify( - { - FileCabinet: [ - {Id: 12, Name: fileCabinetName} - ], - Dialog: [ - {Id: 34, DisplayName: dialogDisplayName} - ] - }) - }; + const docuwareModel = models.Docuware; + const fileCabinetName = 'deliveryNote'; - const gotPostResponse = { - body: JSON.stringify( - { - Items: [ - {Id: 56} - ], - }) - }; + beforeAll(() => { + spyOn(docuwareModel, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random())))); + spyOn(docuwareModel, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random())))); + }); - spyOn(got, 'get').and.returnValue(new Promise(resolve => resolve(gotGetResponse))); - spyOn(got, 'post').and.returnValue(new Promise(resolve => resolve(gotPostResponse))); - spyOn(got, 'stream').and.returnValue(new stream.PassThrough({objectMode: true})); + it('should return error if file not exist', async() => { + spyOn(docuwareModel, 'checkFile').and.returnValue(false); + spyOn(axios, 'get').and.returnValue(new stream.PassThrough({objectMode: true})); - const result = await models.Docuware.download(ctx, ticketId, fileCabinetName, dialogName); + let error; + try { + await models.Docuware.download(ctx, ticketId, fileCabinetName); + } catch (e) { + error = e.message; + } + + expect(error).toEqual('The DOCUWARE PDF document does not exists'); + }); + + it('should return the downloaded file if exist file ', async() => { + spyOn(docuwareModel, 'checkFile').and.returnValue({}); + spyOn(axios, 'get').and.returnValue(new stream.PassThrough({objectMode: true})); + + const result = await models.Docuware.download(ctx, ticketId, fileCabinetName); expect(result[1]).toEqual('application/pdf'); expect(result[2]).toEqual(`filename="${ticketId}.pdf"`); diff --git a/back/methods/docuware/specs/upload.spec.js b/back/methods/docuware/specs/upload.spec.js new file mode 100644 index 000000000..c46dc01fd --- /dev/null +++ b/back/methods/docuware/specs/upload.spec.js @@ -0,0 +1,35 @@ +const models = require('vn-loopback/server/server').models; + +fdescribe('docuware download()', () => { + const userId = 9; + const ticketId = 1; + const ctx = { + req: { + + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + } + }; + + const docuwareModel = models.Docuware; + const fileCabinetName = 'deliveryNote'; + + beforeAll(() => { + spyOn(docuwareModel, 'getFileCabinet').and.returnValue((new Promise(resolve => resolve(Math.random())))); + spyOn(docuwareModel, 'getDialog').and.returnValue((new Promise(resolve => resolve(Math.random())))); + }); + + it('should try upload file', async() => { + spyOn(docuwareModel, 'checkFile').and.returnValue(false); + spyOn(axios, 'get').and.returnValue(new stream.PassThrough({objectMode: true})); + + let error; + try { + await models.Docuware.download(ctx, ticketId, fileCabinetName); + } catch (e) { + error = e.message; + } + + expect(error).toEqual('The DOCUWARE PDF document does not exists'); + }); +}); diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index 49dcc2489..23aa2d8d0 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -1,4 +1,3 @@ -const got = require('got'); const UserError = require('vn-loopback/util/user-error'); const axios = require('axios'); @@ -381,7 +380,26 @@ module.exports = Self => { ] }; - const uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; + // if (process.env.NODE_ENV != 'production') + // throw new UserError('Action not allowed on the test environment'); + const docuwareFile = await models.Docuware.checkFile(ctx, id, fileCabinet); + + console.log(docuwareFile, id, fileCabinet); + // replace + if (docuwareFile) { + console.log(docuwareFile); + const uri = `${options.url}/FileCabinets/${fileCabinetId}/Sections?DocId=${docuwareFile.id}`; + console.log(uri); + return await axios.post(uri, deliveryNote[0], {headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': 'file; filename="10.pdf"', + 'X-File-ModifiedDate': '2020-08-26T00:00:00.000Z' + } + + }); + } + + let uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; const FormData = require('form-data'); const data = new FormData(); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index ea83b36c4..ad845cb38 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -135,7 +135,7 @@ "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", - "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", + "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", "Claim state has changed to incomplete": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *incompleta*", "Claim state has changed to canceled": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *anulado*", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", @@ -252,5 +252,5 @@ "Receipt's bank was not found": "No se encontró el banco del recibo", "This receipt was not compensated": "Este recibo no ha sido compensado", "Client's email was not found": "No se encontró el email del cliente", - "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9" -} \ No newline at end of file + "Failed to upload file": "Error al subir archivo" +} diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index c87d7f7d0..14d884ba7 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -141,7 +141,10 @@ class Controller extends Section { } sendPdfDeliveryNote($data) { - return this.vnEmail.send(`tickets/${this.id}/delivery-note-email`, { + let query = `tickets/${this.id}/delivery-note-email`; + if (this.hasDocuwareFile) query = `docuwares/${this.id}/delivery-note-email`; + + return this.vnEmail.send(query, { recipientId: this.ticket.client.id, recipient: $data.email }); @@ -317,13 +320,6 @@ class Controller extends Section { this.$.balanceCreate.show(); }); } - - sendDocuwarePdfDeliveryNote($data) { - return this.vnEmail.send(`Docuwares/${this.id}/delivery-note-email`, { - recipientId: this.ticket.client.id, - recipient: $data.email - }); - } } Controller.$inject = ['$element', '$scope', 'vnReport', 'vnEmail']; diff --git a/package-lock.json b/package-lock.json index 550a1ec76..31820196f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "9.0.0", "license": "GPL-3.0", "dependencies": { - "axios": "^0.25.0", + "axios": "^1.2.2", "bcrypt": "^5.0.1", "bmp-js": "^0.1.0", "compression": "^1.7.3", @@ -3893,10 +3893,13 @@ "license": "MIT" }, "node_modules/axios": { - "version": "0.25.0", - "license": "MIT", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.2.tgz", + "integrity": "sha512-bz/J4gS2S3I7mpN/YZfGFTqhXTYzRho8Ay38w2otuuDR322KzFIWm/4W2K6gIwvWaws5n+mnb7D1lN9uD+QH6Q==", "dependencies": { - "follow-redirects": "^1.14.7" + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" } }, "node_modules/babel-jest": { @@ -8401,14 +8404,15 @@ } }, "node_modules/follow-redirects": { - "version": "1.14.9", + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], - "license": "MIT", "engines": { "node": ">=4.0" }, @@ -28842,9 +28846,13 @@ "version": "1.11.0" }, "axios": { - "version": "0.25.0", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.2.tgz", + "integrity": "sha512-bz/J4gS2S3I7mpN/YZfGFTqhXTYzRho8Ay38w2otuuDR322KzFIWm/4W2K6gIwvWaws5n+mnb7D1lN9uD+QH6Q==", "requires": { - "follow-redirects": "^1.14.7" + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" } }, "babel-jest": { @@ -31964,7 +31972,9 @@ } }, "follow-redirects": { - "version": "1.14.9" + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==" }, "for-in": { "version": "1.0.2", diff --git a/package.json b/package.json index 8cc33526d..9633751a0 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "node": ">=14" }, "dependencies": { - "axios": "^0.25.0", + "axios": "^1.2.2", "bcrypt": "^5.0.1", "bmp-js": "^0.1.0", "compression": "^1.7.3",