-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfill_in_exchange_rates.js
More file actions
205 lines (168 loc) · 4.97 KB
/
fill_in_exchange_rates.js
File metadata and controls
205 lines (168 loc) · 4.97 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
import { netsuite } from '@sil-org/pipedream-utils@^0.2.0'
import assert from "node:assert/strict";
// In-memory caches
let exchangeRateCache = {}
let currencyIdCache = {}
let currencyDataStore
let netsuiteConfigJson
const cacheAllKnownExchangeRates = (records) => {
for (const record of records) {
if (record.ExchangeRate) {
const key = getCacheKey(record.Currency, record.TransactionDate)
exchangeRateCache[key] = record.ExchangeRate
}
}
}
// Helpers
const getCacheKey = (currency, date) => `${currency}-${date}`
const toDateOnlyISO8601 = (dateString) => {
const date = new Date(dateString)
return date.toISOString().substring(0, 10)
}
// Currency ID (cached)
const getCurrencyId = async (currency) => {
assert.ok(currency, 'Missing currency')
if (currencyIdCache[currency]) {
return currencyIdCache[currency]
}
const data = await currencyDataStore.get(currency)
assert.ok(data?.ID, `No Currency ID for ${currency}`)
currencyIdCache[currency] = data.ID
return data.ID
}
// Batch fetch exchange rates
const fetchExchangeRates = async (requests) => {
const netsuiteConfig = JSON.parse(netsuiteConfigJson)
// Group by currency ID to reduce queries
const grouped = {}
for (const req of requests) {
const { currencyId, date } = req
if (!grouped[currencyId]) {
grouped[currencyId] = new Set()
}
grouped[currencyId].add(date)
}
// Execute one query per currency
for (const currencyId of Object.keys(grouped)) {
const dates = Array.from(grouped[currencyId])
// Get min/max date range
const minDate = dates.sort()[0]
const maxDate = dates.sort().reverse()[0]
const query = `
SELECT
exchangerate,
effectivedate
FROM
currencyrate
WHERE
basecurrency = 1
AND effectivedate <= TO_DATE('${maxDate}', 'YYYY-MM-DD')
AND transactioncurrency = ${currencyId}
ORDER BY
effectivedate DESC
`
const results = await netsuite.queryRecords(query, netsuiteConfig)
if (!results.length) continue
// Fill cache for all requested dates
for (const date of dates) {
const match = results.find(r =>
toDateOnlyISO8601(r.effectivedate) <= date
)
if (match) {
const key = getCacheKey(reqCurrencyFromId(currencyId), date)
exchangeRateCache[key] = Number(match.exchangerate)
}
}
}
}
// Reverse lookup helper (optional optimization)
const reqCurrencyFromId = (id) => {
for (const [currency, cachedId] of Object.entries(currencyIdCache)) {
if (cachedId == id) return currency
}
return null
}
export default {
name: "Fill In Exchange Rates (Optimized)",
description: "Fill in the ExchangeRate on each of the given records, looking it up in NetSuite when necessary",
key: "fill_in_exchange_rates",
version: "0.3.0",
type: "action",
props: {
netsuite_config_json: {
type: "string",
label: "NetSuite Config JSON",
description: "JSON-encoded configuration object needed for calls to NetSuite",
secret: true,
},
currency_data_store: {
type: "data_store",
label: "NetSuite Currency Data Store",
},
input_records: {
type: "any",
label: "Input Records",
description: "The list of records, some of which might lack an ExchangeRate",
},
},
methods: {
emptyCache() {
exchangeRateCache = {}
currencyIdCache = {}
},
},
async run({ $, steps }) {
netsuiteConfigJson = this.netsuite_config_json
currencyDataStore = this.currency_data_store
cacheAllKnownExchangeRates(this.input_records)
const failed = []
// Build request list
const requests = []
for (const record of this.input_records) {
try {
if (record.ExchangeRate) {
continue
}
const date = toDateOnlyISO8601(record.TransactionDate)
const currencyId = await getCurrencyId(record.Currency)
const key = getCacheKey(record.Currency, date)
if (!exchangeRateCache[key]) {
requests.push({
currency: record.Currency,
currencyId,
date,
})
}
} catch (err) {
record.error = err.message || err
failed.push(record)
}
}
if (requests.length > 0) {
// Batch fetch
await fetchExchangeRates(requests)
}
// Fill records
for (const index in this.input_records) {
const record = this.input_records[index]
try {
if (!record.ExchangeRate) {
const date = toDateOnlyISO8601(record.TransactionDate)
const key = getCacheKey(record.Currency, date)
const rate = exchangeRateCache[key]
assert.ok(rate, `No exchange rate for ${key}`)
this.input_records[index].ExchangeRate = rate
}
} catch (err) {
failed.push({
...record,
error: err.message || err
})
}
}
if (failed.length) {
$.export('errors', failed)
}
return this.input_records
},
}