#7108 - exchange-rate #2295

Merged
jgallego merged 11 commits from 7108-exchange-rate into dev 2024-04-26 05:00:07 +00:00
6 changed files with 123 additions and 3 deletions
Showing only changes of commit bc9149ec37 - Show all commits

View File

@ -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: {
jgallego marked this conversation as resolved Outdated
Outdated
Review

Si no retorna res, no cal ficar return (no estic segur)

Si no retorna res, no cal ficar return (no estic segur)
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;
jgallego marked this conversation as resolved Outdated
Outdated
Review

Se pot simplificar en const maxDate = maxDateRecord?.dated ? new Date(maxDateRecord.dated) : null;

Se pot simplificar en `const maxDate = maxDateRecord?.dated ? new Date(maxDateRecord.dated) : null;`

const maxDate = maxDateRecord?.dated ? new Date(maxDateRecord.dated) : null;

Unhandled error for request POST /api/Collections/exchangeRateUpdate?access_token=YQ8SPYxYrHrY4veSEyY5q9YJD3AtcjEqcGXxyA5rweDZO92PLp0FB2WhBxlbTvUO: TypeError: Cannot read properties of null (reading 'dated')

Ahir em va fallar..ací t'he posat la conversa amb chatGpt...ara sí va..ho canvie de nou

const maxDate = maxDateRecord?.dated ? new Date(maxDateRecord.dated) : null; Unhandled error for request POST /api/Collections/exchangeRateUpdate?access_token=YQ8SPYxYrHrY4veSEyY5q9YJD3AtcjEqcGXxyA5rweDZO92PLp0FB2WhBxlbTvUO: TypeError: Cannot read properties of null (reading 'dated') Ahir em va fallar..ací t'he posat la conversa amb chatGpt...ara sí va..ho canvie de nou
for (const cube of cubes) {
if (cube.attributes.getNamedItem('time')) {
jgallego marked this conversation as resolved Outdated
Outdated
Review

Si no cal la "i" i la "j", vec mes legible fer:

for (const/let cube of cubes) 

i lo mateix en el altre for

Si no cal la "i" i la "j", vec mes legible fer: ``` for (const/let cube of cubes) ``` i lo mateix en el altre for

no era iterable li he posat Array.from(

no era iterable li he posat Array.from(
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;
}
}
}
}
}
}
}
};
};

View File

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

View File

@ -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);
};

View File

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

esta propietat no la havia vist mai

esta propietat no la havia vist mai
"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"
}
]
}

View File

@ -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

View File

@ -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'",
jgallego marked this conversation as resolved Outdated
Outdated
Review

Hi han q se han colat, al fer proves

Hi han q se han colat, al fer proves
"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'"
}