Add currency auto transform (#83)

Co-authored-by: AceDataCloud <office@acedata.cloud>
This commit is contained in:
GermeyandAceDataCloud authored and GitHub committed 2024-07-14 15:35:04 +08:00
1 parent 3f16b60071
commit c83b4fcc9f
21 files changed
+245 -22

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ export * from './highlight';
export * from './is';
export * from './login';
export * from './site';
export * from './price';
+26
View File
@@ -5,6 +5,7 @@ import store from '@/store';
import { log } from './log';
import { IToken } from '@/models';
import psl from 'psl';
import { LOCALE_CURRENCY_MAPPING } from '@/constants';
export const getDomain = (host: string = window.location.hostname) => {
const parsed = psl.parse(host);
@@ -174,3 +175,28 @@ export const initializeUser = async () => {
const user = await store.dispatch('getUser');
console.debug('get user', user);
};
export const initializeCurrency = async () => {
const locale = getCookie('LOCALE');
console.log('initialize currency', locale);
const mapping = LOCALE_CURRENCY_MAPPING;
let currency = 'usd';
if (locale && mapping[locale]) {
currency = mapping[locale];
}
console.log('set currency', currency);
await store.dispatch('setCurrency', currency);
};
export const initializeExchangeRate = async () => {
const locale = getCookie('LOCALE');
const mapping = LOCALE_CURRENCY_MAPPING;
if (!locale || !mapping[locale]) {
return;
}
const target = mapping[locale];
const source = 'usd';
const payload = { source, target };
console.log('initialize exchange rate', payload);
await store.dispatch('getExchangeRate', payload);
};
+43
View File
@@ -0,0 +1,43 @@
import { CURRENCY_LABEL_MAPPING } from '@/constants/mapping';
import store from '@/store';
/**
* Input a value and target currency (e.g. cny), return the price which the current locale
*/
export const getPrice = (payload: { value: number; currency?: string }) => {
const exchange = store.state.exchange;
let { value, currency = store.state.currency || 'usd' } = payload;
const label = CURRENCY_LABEL_MAPPING[currency];
if (!exchange) {
return {
value: value,
currency: currency,
label: label
};
}
const key = `usd-${currency}`;
const rate = exchange[key];
if (rate) {
value = value * rate;
}
console.log('new price', { value, currency });
return {
value,
currency,
label
};
};
export const getPriceString = (payload: { value: number | undefined; defaultValue?: number | undefined }) => {
let { value, defaultValue } = payload;
if (value === undefined) {
value = defaultValue;
}
if (value === undefined) {
return '';
}
const price = getPrice({
value
});
return `${price.label}${price.value?.toFixed(2)}`;
};