diff --git a/back/methods/collection/exchangeRateUpdate.js b/back/methods/collection/exchangeRateUpdate.js new file mode 100644 index 000000000..8525fa980 --- /dev/null +++ b/back/methods/collection/exchangeRateUpdate.js @@ -0,0 +1,66 @@ +const axios = require('axios'); +const {DOMParser} = require('xmldom'); +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('exchangeRateUpdate', { + description: 'Updates the exchange rates from an XML feed', + accessType: 'WRITE', + accepts: [], + http: { + path: '/exchangeRateUpdate', + verb: 'post' + }, + returns: { + arg: 'result', + type: 'object', + root: true + } + }); + + Self.exchangeRateUpdate = async() => { + const response = await axios.get('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml'); + const xmlData = response.data; + + const doc = new DOMParser().parseFromString(xmlData, 'text/xml'); + const cubes = doc.getElementsByTagName('Cube'); + + const models = Self.app.models; + + const maxDateRecord = await models.ReferenceRate.findOne({order: 'dated DESC'}); + let maxDate = maxDateRecord ? new Date(maxDateRecord.dated) : null; + + for (const cube of cubes) { + if (cube.attributes.getNamedItem('time')) { + const xmlDate = new Date(cube.getAttribute('time')); + if (!maxDate || maxDate < xmlDate) { + for (const rateCube of cube.childNodes) { + if (rateCube.nodeType === Node.ELEMENT_NODE) { + const currencyCode = rateCube.getAttribute('currency'); + const rate = rateCube.getAttribute('rate'); + if (['USD', 'CNY', 'GBP'].includes(currencyCode)) { + const currency = await models.Currency.findOne({where: {code: currencyCode}}); + if (!currency) throw new UserError(`Currency not found for code: ${currencyCode}`); + + try { + await models.ReferenceRate.upsertWithWhere( + {currencyFk: currency.id, dated: xmlDate}, + { + currencyFk: currency.id, + dated: xmlDate, + value: rate + } + ); + } catch (error) { + console.error(`Failed to upsert rate for ${currencyCode} on ${xmlDate}: ${error}`); + // Handle or throw the error accordingly + throw error; + } + } + } + } + } + } + } + }; +}; diff --git a/back/model-config.json b/back/model-config.json index f48ec11e6..10e606f3c 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -124,6 +124,9 @@ "Postcode": { "dataSource": "vn" }, + "ReferenceRate": { + "dataSource": "vn" + }, "SageWithholding": { "dataSource": "vn" }, @@ -175,4 +178,4 @@ "WorkerActivityType": { "dataSource": "vn" } -} \ No newline at end of file +} diff --git a/back/models/collection.js b/back/models/collection.js index f2c2f1566..68c0bd13e 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -5,4 +5,5 @@ module.exports = Self => { require('../methods/collection/getTickets')(Self); require('../methods/collection/assign')(Self); require('../methods/collection/getSales')(Self); + require('../methods/collection/exchangeRateUpdate')(Self); }; diff --git a/back/models/reference-rate.json b/back/models/reference-rate.json new file mode 100644 index 000000000..3553df5c5 --- /dev/null +++ b/back/models/reference-rate.json @@ -0,0 +1,40 @@ +{ + "name": "ReferenceRate", + "base": "PersistedModel", + "idInjection": false, + "options": { + "mysql": { + "table": "referenceRate" + } + }, + "properties": { + "currencyFk": { + "type": "number", + "required": true, + "id": 1, + "mysql": { + "dataType": "tinyint", + "dataLength": 3, + "unsigned": true, + "primaryKey": true + } + }, + "dated": { + "type": "date", + "required": true, + "id": 2 + }, + "value": { + "type": "number", + "required": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 6fb70cb58..c84a08f87 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -160,7 +160,8 @@ INSERT INTO `vn`.`currency`(`id`, `code`, `name`, `ratio`) (1, 'EUR', 'Euro', 1), (2, 'USD', 'Dollar USA', 1.4), (3, 'GBP', 'Libra', 1), - (4, 'JPY', 'Yen Japones', 1); + (4, 'JPY', 'Yen Japones', 1), + (5, 'CNY', 'Yuan Chino', 1.2); INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`, `ibanLength`, `continentFk`, `hasDailyInvoice`, `CEE`) VALUES diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 8b02f3048..50cd305fa 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -352,5 +352,14 @@ "The line could not be marked": "La linea no puede ser marcada", "This password can only be changed by the user themselves": "Esta contraseƱa solo puede ser modificada por el propio usuario", "They're not your subordinate": "No es tu subordinado/a.", - "No results found": "No se han encontrado resultados" + "No results found": "No se han encontrado resultados", + "ReferenceError: app is not defined": "ReferenceError: app is not defined", + "TypeError: Cannot read properties of undefined (reading 'ReferenceRate')": "TypeError: Cannot read properties of undefined (reading 'ReferenceRate')", + "Error: ER_BAD_FIELD_ERROR: Unknown column 'date' in 'order clause'": "Error: ER_BAD_FIELD_ERROR: Unknown column 'date' in 'order clause'", + "ReferenceError: ReferenceRate is not defined": "ReferenceError: ReferenceRate is not defined", + "ValidationError: The `ReferenceRate` instance is not valid. Details: `currencyFk` can't be blank (value: NaN).": "ValidationError: The `ReferenceRate` instance is not valid. Details: `currencyFk` can't be blank (value: NaN).", + "ReferenceError: Currency is not defined": "ReferenceError: Currency is not defined", + "UserError: Currency not found for code: CNY": "UserError: Currency not found for code: CNY", + "Error: ER_DUP_ENTRY: Duplicate entry '2-2024-04-03' for key 'PRIMARY'": "Error: ER_DUP_ENTRY: Duplicate entry '2-2024-04-03' for key 'PRIMARY'", + "Error: ER_DUP_ENTRY: Duplicate entry '2-2024-04-08' for key 'PRIMARY'": "Error: ER_DUP_ENTRY: Duplicate entry '2-2024-04-08' for key 'PRIMARY'" } \ No newline at end of file