#7108 - exchange-rate #2295

Merged
jgallego merged 11 commits from 7108-exchange-rate into dev 2024-04-26 05:00:07 +00:00
9 changed files with 170 additions and 3 deletions

View File

@ -124,6 +124,9 @@
"Postcode": { "Postcode": {
"dataSource": "vn" "dataSource": "vn"
}, },
"ReferenceRate": {
"dataSource": "vn"
},
"SageWithholding": { "SageWithholding": {
"dataSource": "vn" "dataSource": "vn"
}, },

View File

@ -1,6 +1,11 @@
{ {
"name": "Collection", "name": "Collection",
"base": "VnModel", "base": "VnModel",
"options": {
"mysql": {
"table": "collection"
}
},
"acls": [{ "acls": [{
"property": "validations", "property": "validations",
"accessType": "EXECUTE", "accessType": "EXECUTE",
@ -9,4 +14,3 @@
"permission": "ALLOW" "permission": "ALLOW"
}] }]
} }

View File

@ -0,0 +1,36 @@
{
"name": "ReferenceRate",
"base": "PersistedModel",
"options": {
jgallego marked this conversation as resolved
Review

esta propietat no la havia vist mai

esta propietat no la havia vist mai
"mysql": {
"table": "referenceRate"
}
},
"properties": {
"id": {
"type": "number",
"id": true,
"description": "Identifier"
},
"currencyFk": {
"type": "number",
"required": true
},
"dated": {
"type": "date",
"required": true
},
"value": {
"type": "number",
"required": true
}
},
"acls": [
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]
}

View File

@ -160,7 +160,8 @@ INSERT INTO `vn`.`currency`(`id`, `code`, `name`, `ratio`)
(1, 'EUR', 'Euro', 1), (1, 'EUR', 'Euro', 1),
(2, 'USD', 'Dollar USA', 1.4), (2, 'USD', 'Dollar USA', 1.4),
(3, 'GBP', 'Libra', 1), (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`) INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`, `ibanLength`, `continentFk`, `hasDailyInvoice`, `CEE`)
VALUES VALUES

View File

@ -0,0 +1,2 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES ('InvoiceIn', 'exchangeRateUpdate', '*', 'ALLOW', 'ROLE', 'employee');
Outdated
Review

'invoiceIn' deuria ser en PascalCase ns si aixina fallaria.

'invoiceIn' deuria ser en PascalCase ns si aixina fallaria.

View File

@ -0,0 +1,4 @@
ALTER TABLE vn.referenceRate DROP INDEX `PRIMARY`;
ALTER TABLE vn.referenceRate ADD id INT auto_increment PRIMARY KEY;
ALTER TABLE vn.referenceRate CHANGE id id int(11) auto_increment NOT NULL FIRST;
CREATE UNIQUE INDEX referenceRate_currencyFk_IDX USING BTREE ON vn.referenceRate (currencyFk,dated);

View File

@ -0,0 +1,64 @@
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'
}
});
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({errorHandler: {warning: () => {}}})?.parseFromString(xmlData, 'text/xml');
const cubes = doc?.getElementsByTagName('Cube');
if (!cubes || cubes.length === 0)
throw new UserError('No cubes found. Exiting the method.');
const models = Self.app.models;
const maxDateRecord = await models.ReferenceRate.findOne({order: 'dated DESC'});
const maxDate = maxDateRecord?.dated ? new Date(maxDateRecord.dated) : null;
for (const cube of Array.from(cubes)) {
if (cube.nodeType === doc.ELEMENT_NODE && cube.attributes.getNamedItem('time')) {
const xmlDate = new Date(cube.getAttribute('time'));
const xmlDateWithoutTime = new Date(xmlDate.getFullYear(), xmlDate.getMonth(), xmlDate.getDate());
if (!maxDate || maxDate < xmlDateWithoutTime) {
for (const rateCube of Array.from(cube.childNodes)) {
if (rateCube.nodeType === doc.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}`);
const existingRate = await models.ReferenceRate.findOne({
where: {currencyFk: currency.id, dated: xmlDate}
});
if (existingRate) {
if (existingRate.value !== rate)
await existingRate.updateAttributes({value: rate});
} else {
await models.ReferenceRate.create({
currencyFk: currency.id,
dated: xmlDate,
value: rate
});
}
}
}
}
}
}
}
};
};

View File

@ -0,0 +1,52 @@
describe('exchangeRateUpdate functionality', function() {
const axios = require('axios');
const models = require('vn-loopback/server/server').models;
beforeEach(function() {
spyOn(axios, 'get').and.returnValue(Promise.resolve({
data: `<Cube>
<Cube time='2024-04-12'>
<Cube currency='USD' rate='1.1'/>
<Cube currency='CNY' rate='1.2'/>
</Cube>
</Cube>`
}));
});
it('should process XML data and update or create rates in the database', async function() {
spyOn(models.ReferenceRate, 'findOne').and.returnValue(Promise.resolve(null));
spyOn(models.ReferenceRate, 'create').and.returnValue(Promise.resolve());
await models.InvoiceIn.exchangeRateUpdate();
expect(models.ReferenceRate.create).toHaveBeenCalledTimes(2);
});
it('should not create or update rates when no XML data is available', async function() {
axios.get.and.returnValue(Promise.resolve({}));
spyOn(models.ReferenceRate, 'create');
let thrownError = null;
try {
await models.InvoiceIn.exchangeRateUpdate();
} catch (error) {
thrownError = error;
}
expect(thrownError.message).toBe('No cubes found. Exiting the method.');
});
it('should handle errors gracefully', async function() {
axios.get.and.returnValue(Promise.reject(new Error('Network error')));
let error;
try {
await models.InvoiceIn.exchangeRateUpdate();
} catch (e) {
error = e;
}
expect(error).toBeDefined();
expect(error.message).toBe('Network error');
});
});

View File

@ -10,6 +10,7 @@ module.exports = Self => {
require('../methods/invoice-in/invoiceInEmail')(Self); require('../methods/invoice-in/invoiceInEmail')(Self);
require('../methods/invoice-in/getSerial')(Self); require('../methods/invoice-in/getSerial')(Self);
require('../methods/invoice-in/corrective')(Self); require('../methods/invoice-in/corrective')(Self);
require('../methods/invoice-in/exchangeRateUpdate')(Self);
Self.rewriteDbError(function(err) { Self.rewriteDbError(function(err) {
if (err.code === 'ER_ROW_IS_REFERENCED_2' && err.sqlMessage.includes('vehicleInvoiceIn')) if (err.code === 'ER_ROW_IS_REFERENCED_2' && err.sqlMessage.includes('vehicleInvoiceIn'))