mirror of
https://github.com/tiennm99/exchange-rate-export.git
synced 2026-10-11 03:13:21 +00:00
Revert "Merge branch 'vercel/react-server-components-cve-vu-xejazm'"
This reverts commit09afad997c, reversing changes made to3cef2ee4f4.
This commit is contained in:
1 parent
09afad997c
commit
2f5df7bbec
20 files changed
+5961
-6851
No files matched your search
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,10 +1,10 @@
|
||||
# exchange-rate-export
|
||||
Fetch data from BIDV or Techcombank and export to Excel format.
|
||||
Fetch data from BIDV or Techcombank and export to Excel or CSV.
|
||||
|
||||
Features:
|
||||
- Choose BIDV or Techcombank.
|
||||
- Select time range.
|
||||
- View and export to Excel.
|
||||
- View and export to Excel or CSV.
|
||||
|
||||
Use data from :
|
||||
- https://bidv.com.vn/vn/ty-gia-ngoai-te
|
||||
@@ -16,21 +16,18 @@ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-
|
||||
|
||||
## Getting Started
|
||||
|
||||
Requires Node.js 24+ and pnpm 11+.
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm install
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
|
||||
You can start editing the page by modifying `src/app/page.js`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
|
||||
+11
-11
@@ -1,14 +1,14 @@
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
});
|
||||
|
||||
const eslintConfig = [...compat.extends("next/core-web-vitals")];
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
{
|
||||
rules: {
|
||||
"react-hooks/set-state-in-effect": "off",
|
||||
},
|
||||
},
|
||||
globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
Generated
-6390
File diff suppressed because it is too large.
Load diff
+17
-12
@@ -1,28 +1,33 @@
|
||||
{
|
||||
"name": "exchange-rate-export",
|
||||
"version": "0.1.0",
|
||||
"packageManager": "pnpm@11.1.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
"lint": "eslint src"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/analytics": "^1.5.0",
|
||||
"@vercel/speed-insights": "^1.2.0",
|
||||
"axios": "^1.10.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"next": "15.3.8",
|
||||
"react": "^19.0.0",
|
||||
"react-datepicker": "^8.4.0",
|
||||
"react-dom": "^19.0.0"
|
||||
"@vercel/analytics": "^2.0.1",
|
||||
"@vercel/speed-insights": "^2.0.0",
|
||||
"axios": "^1.18.1",
|
||||
"date-fns": "^4.4.0",
|
||||
"next": "16.2.11",
|
||||
"react": "^19.2.7",
|
||||
"react-datepicker": "^9.1.0",
|
||||
"react-dom": "^19.2.7",
|
||||
"recharts": "^3.9.2",
|
||||
"write-excel-file": "^4.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "15.3.4",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "16.2.11",
|
||||
"tailwindcss": "^4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
Generated
+4679
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
overrides:
|
||||
'@babel/core': 7.29.6
|
||||
form-data: 4.0.6
|
||||
js-yaml: 4.3.0
|
||||
postcss: 8.5.18
|
||||
# next 16.2.11 declares sharp ^0.34.5, which excludes the patched 0.35.0, so
|
||||
# no upstream bump can reach the fix -- force it here.
|
||||
sharp: 0.35.0
|
||||
# Two independent major branches reach this package: minimatch@3 pulls 1.x,
|
||||
# minimatch@10 pulls 5.x. Each branch needs its own patched version.
|
||||
'brace-expansion@1': 1.1.16
|
||||
'brace-expansion@5': 5.0.7
|
||||
|
||||
allowBuilds:
|
||||
sharp: true
|
||||
unrs-resolver: true
|
||||
+122
-123
@@ -1,192 +1,191 @@
|
||||
import { format } from "date-fns";
|
||||
import { format, addDays, subDays } from "date-fns";
|
||||
import axios from "axios";
|
||||
import https from "https";
|
||||
import crypto from "crypto";
|
||||
|
||||
// Configure axios with legacy SSL support
|
||||
const axiosInstance = axios.create({
|
||||
httpsAgent: new https.Agent({
|
||||
secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT,
|
||||
}),
|
||||
});
|
||||
|
||||
// Helper function to fetch BIDV exchange rates
|
||||
async function fetchBIDVRates(dateObj) {
|
||||
const DISPLAY_DATE_FORMAT = "yyyy-MM-dd";
|
||||
const PARALLEL_CHUNK_SIZE = 5;
|
||||
const MAX_RETRIES = 2;
|
||||
const INITIAL_BACKOFF_MS = 500;
|
||||
|
||||
// Retry a function with exponential backoff
|
||||
async function withRetry(fn, retries = MAX_RETRIES) {
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
if (attempt === retries) throw error;
|
||||
const delay = INITIAL_BACKOFF_MS * Math.pow(2, attempt);
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchBIDVRates(dateObj, currency) {
|
||||
const dateStr = format(dateObj, "dd/MM/yyyy");
|
||||
try {
|
||||
// First API call to get namerecord
|
||||
const timeUrl = `https://bidv.com.vn/ServicesBIDV/ExchangeDetailSearchTimeServlet?date=${dateStr}`;
|
||||
const timeRes = await axiosInstance.get(timeUrl);
|
||||
const timeRes = await withRetry(() => axiosInstance.get(timeUrl));
|
||||
const timeData = timeRes.data;
|
||||
if (timeData.status !== 1 || !timeData.data?.length) return null;
|
||||
// Get the latest record
|
||||
|
||||
const latest = timeData.data.reduce(
|
||||
(latest, current) => (current.time > latest.time ? current : latest),
|
||||
(best, current) => (current.time > best.time ? current : best),
|
||||
timeData.data[0]
|
||||
);
|
||||
// Second API call to get exchange rates
|
||||
|
||||
const rateUrl = `https://bidv.com.vn/ServicesBIDV/ExchangeDetailServlet?date=${dateStr}&time=${latest.namerecord}`;
|
||||
const rateRes = await axiosInstance.get(rateUrl);
|
||||
const rateRes = await withRetry(() => axiosInstance.get(rateUrl));
|
||||
const rateData = rateRes.data;
|
||||
if (rateData.status !== 1 || !rateData.data) return null;
|
||||
// Find USD data
|
||||
const usd = rateData.data.find((item) => item.currency === "USD");
|
||||
if (!usd) return null;
|
||||
return {
|
||||
date: dateStr,
|
||||
nameVI: usd.nameVI || "",
|
||||
muaTm: usd.muaTm || "",
|
||||
muaCk: usd.muaCk || "",
|
||||
currency: usd.currency || "USD",
|
||||
nameEN: usd.nameEN || "",
|
||||
ban: usd.ban || "",
|
||||
};
|
||||
|
||||
const displayDate = format(dateObj, DISPLAY_DATE_FORMAT);
|
||||
const items = currency === "ALL"
|
||||
? rateData.data
|
||||
: rateData.data.filter((item) => item.currency === currency);
|
||||
if (items.length === 0) return null;
|
||||
|
||||
return items.map((item) => ({
|
||||
date: displayDate,
|
||||
nameVI: item.nameVI || "",
|
||||
muaTm: item.muaTm || "",
|
||||
muaCk: item.muaCk || "",
|
||||
currency: item.currency || "",
|
||||
nameEN: item.nameEN || "",
|
||||
ban: item.ban || "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching BIDV rates:", error);
|
||||
console.error("Error fetching BIDV rates:", error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to fetch TCB exchange rates
|
||||
async function fetchTCBRates(dateObj) {
|
||||
async function fetchTCBRates(dateObj, currency) {
|
||||
const dateStr = format(dateObj, "yyyy-MM-dd");
|
||||
const url = `https://techcombank.com/content/techcombank/web/vn/vi/cong-cu-tien-ich/ty-gia/_jcr_content.exchange-rates.${dateStr}.integration.json`;
|
||||
try {
|
||||
const res = await axiosInstance.get(url);
|
||||
const res = await withRetry(() => axiosInstance.get(url));
|
||||
const data = res.data;
|
||||
if (!data.exchangeRate?.data) return null;
|
||||
// Find USD data
|
||||
const usd = data.exchangeRate.data.find(
|
||||
(item) => item.label === "USD (50,100)"
|
||||
);
|
||||
if (!usd) return null;
|
||||
return {
|
||||
|
||||
const items = currency === "ALL"
|
||||
? data.exchangeRate.data
|
||||
: data.exchangeRate.data.filter((item) => item.sourceCurrency === currency);
|
||||
if (items.length === 0) return null;
|
||||
|
||||
return items.map((item) => ({
|
||||
date: dateStr,
|
||||
label: usd.label || "",
|
||||
askRate: usd.askRate || "",
|
||||
bidRateCK: usd.bidRateCK || "",
|
||||
bidRateTM: usd.bidRateTM || "",
|
||||
sourceCurrency: usd.sourceCurrency || "",
|
||||
targetCurrency: usd.targetCurrency || "",
|
||||
askRateTM: usd.askRateTM || "",
|
||||
};
|
||||
label: item.label || "",
|
||||
askRate: item.askRate || "",
|
||||
bidRateCK: item.bidRateCK || "",
|
||||
bidRateTM: item.bidRateTM || "",
|
||||
sourceCurrency: item.sourceCurrency || "",
|
||||
targetCurrency: item.targetCurrency || "",
|
||||
askRateTM: item.askRateTM || "",
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching TCB rates:", error);
|
||||
console.error("Error fetching TCB rates:", error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Get date range between start and end dates
|
||||
function fetchRateForDate(dateObj, bank, currency) {
|
||||
return bank === "bidv" ? fetchBIDVRates(dateObj, currency) : fetchTCBRates(dateObj, currency);
|
||||
}
|
||||
|
||||
function getDateRange(start, end) {
|
||||
const dates = [];
|
||||
let current = new Date(start);
|
||||
const last = new Date(end);
|
||||
while (current <= last) {
|
||||
dates.push(new Date(current));
|
||||
current.setDate(current.getDate() + 1);
|
||||
current = addDays(current, 1);
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
// Helper function to get previous business day rate with recursive search
|
||||
async function getPreviousDayRate(date, bank, rateCache, maxAttempts = 30) {
|
||||
// Search backwards for the most recent available rate
|
||||
async function getPreviousDayRate(date, bank, currency, rateCache, maxAttempts = 30) {
|
||||
let currentDate = new Date(date);
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
currentDate.setDate(currentDate.getDate() - 1);
|
||||
const dateStr = format(currentDate, 'yyyy-MM-dd');
|
||||
|
||||
|
||||
// Try to find in cache first
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
currentDate = subDays(currentDate, 1);
|
||||
const dateStr = format(currentDate, "yyyy-MM-dd");
|
||||
|
||||
if (rateCache.has(dateStr)) {
|
||||
return rateCache.get(dateStr);
|
||||
}
|
||||
|
||||
// Fetch from API
|
||||
let rate = null;
|
||||
try {
|
||||
if (bank === "bidv") {
|
||||
rate = await fetchBIDVRates(currentDate);
|
||||
} else if (bank === "tcb") {
|
||||
rate = await fetchTCBRates(currentDate);
|
||||
}
|
||||
|
||||
if (rate) {
|
||||
rateCache.set(dateStr, rate);
|
||||
return rate;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error fetching rates for ${dateStr}:`, error);
|
||||
|
||||
const rates = await fetchRateForDate(currentDate, bank, currency);
|
||||
if (rates) {
|
||||
rateCache.set(dateStr, rates);
|
||||
return rates;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fetch a chunk of dates in parallel, filling gaps with previous day data
|
||||
async function fetchChunk(dates, bank, currency, rateCache) {
|
||||
const settled = await Promise.allSettled(
|
||||
dates.map((date) => fetchRateForDate(date, bank, currency))
|
||||
);
|
||||
|
||||
const results = [];
|
||||
for (let i = 0; i < dates.length; i++) {
|
||||
const date = dates[i];
|
||||
const dateStr = format(date, "yyyy-MM-dd");
|
||||
const outcome = settled[i];
|
||||
let rates = outcome.status === "fulfilled" ? outcome.value : null;
|
||||
|
||||
if (rates) {
|
||||
rateCache.set(dateStr, rates);
|
||||
results.push(...rates);
|
||||
} else {
|
||||
// Weekend/holiday/error — fill with most recent available rate
|
||||
const prevRates = await getPreviousDayRate(date, bank, currency, rateCache);
|
||||
if (prevRates) {
|
||||
const displayDate = format(date, DISPLAY_DATE_FORMAT);
|
||||
results.push(...prevRates.map((r) => ({ ...r, date: displayDate })));
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { startDate, endDate, bank } = body;
|
||||
const { startDate, endDate, bank, currency = "USD" } = body;
|
||||
if (!startDate || !endDate || !bank) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Missing required parameters" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
return Response.json(
|
||||
{ error: "Missing required parameters" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const dates = getDateRange(startDate, endDate);
|
||||
const rateCache = new Map();
|
||||
const results = [];
|
||||
const rateCache = new Map(); // Cache to store rates we've fetched
|
||||
|
||||
for (const date of dates) {
|
||||
let rate = null;
|
||||
const dateStr = format(date, 'yyyy-MM-dd');
|
||||
|
||||
|
||||
try {
|
||||
if (bank === "bidv") {
|
||||
rate = await fetchBIDVRates(date);
|
||||
} else if (bank === "tcb") {
|
||||
rate = await fetchTCBRates(date);
|
||||
}
|
||||
|
||||
if (rate) {
|
||||
results.push(rate);
|
||||
rateCache.set(dateStr, rate);
|
||||
} else {
|
||||
// No data for this date (likely weekend), try to get previous day's data
|
||||
const prevRate = await getPreviousDayRate(date, bank, rateCache);
|
||||
if (prevRate) {
|
||||
// Create a new rate object with current date but previous day's data
|
||||
const filledRate = {
|
||||
...prevRate,
|
||||
date: bank === "bidv" ? format(date, 'dd/MM/yyyy') : dateStr
|
||||
};
|
||||
results.push(filledRate);
|
||||
} else {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error fetching rates for ${date}:`, error);
|
||||
// Try to fill with previous day's data even on error
|
||||
const prevRate = await getPreviousDayRate(date, bank, rateCache);
|
||||
if (prevRate) {
|
||||
const filledRate = {
|
||||
...prevRate,
|
||||
date: bank === "bidv" ? format(date, 'dd/MM/yyyy') : dateStr
|
||||
};
|
||||
results.push(filledRate);
|
||||
}
|
||||
}
|
||||
|
||||
// Process dates in parallel chunks to avoid overwhelming upstream APIs
|
||||
for (let i = 0; i < dates.length; i += PARALLEL_CHUNK_SIZE) {
|
||||
const chunk = dates.slice(i, i + PARALLEL_CHUNK_SIZE);
|
||||
const chunkResults = await fetchChunk(chunk, bank, currency, rateCache);
|
||||
results.push(...chunkResults);
|
||||
}
|
||||
return new Response(JSON.stringify({ data: results }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
return Response.json({ data: results, total: dates.length, chunks: Math.ceil(dates.length / PARALLEL_CHUNK_SIZE) });
|
||||
} catch (error) {
|
||||
console.error("Server error:", error);
|
||||
return new Response(JSON.stringify({ error: "Internal server error" }), {
|
||||
status: 500,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
return Response.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import { parse, isDate, format } from "date-fns";
|
||||
|
||||
export default function ExchangeRateViewer({
|
||||
defaultStartDate,
|
||||
defaultEndDate,
|
||||
}) {
|
||||
const [startDate, setStartDate] = useState(
|
||||
defaultStartDate
|
||||
? isDate(defaultStartDate)
|
||||
? defaultStartDate
|
||||
: parse(defaultStartDate, "yyyy-MM-dd", new Date())
|
||||
: null
|
||||
);
|
||||
const [endDate, setEndDate] = useState(
|
||||
defaultEndDate
|
||||
? isDate(defaultEndDate)
|
||||
? defaultEndDate
|
||||
: parse(defaultEndDate, "yyyy-MM-dd", new Date())
|
||||
: null
|
||||
);
|
||||
const [selectedBank, setSelectedBank] = useState("bidv");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [results, setResults] = useState([]);
|
||||
const [showTable, setShowTable] = useState(false);
|
||||
|
||||
const handleFetch = async () => {
|
||||
if (!startDate || !endDate) {
|
||||
setError("Please select both start and end dates");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
setResults([]);
|
||||
setShowTable(false);
|
||||
try {
|
||||
const start = startDate;
|
||||
const end = endDate;
|
||||
if (start > end) {
|
||||
setError("Start date cannot be after end date");
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
const response = await fetch("/api/exchange-rates", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
startDate: format(start, 'yyyy-MM-dd'),
|
||||
endDate: format(end, 'yyyy-MM-dd'),
|
||||
bank: selectedBank,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to fetch exchange rates");
|
||||
}
|
||||
const data = await response.json();
|
||||
setResults(data.data || []);
|
||||
setShowTable(true);
|
||||
} catch (err) {
|
||||
setError(
|
||||
`An error occurred while fetching exchange rates: ${err.message}`
|
||||
);
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
if (results.length === 0) return;
|
||||
let csvContent = "";
|
||||
let headers = [];
|
||||
if (selectedBank === "bidv") {
|
||||
headers = [
|
||||
"Date",
|
||||
"NameVI",
|
||||
"MuaTm",
|
||||
"MuaCk",
|
||||
"Currency",
|
||||
"NameEN",
|
||||
"Ban",
|
||||
];
|
||||
csvContent = headers.join(",") + "\n";
|
||||
csvContent += results
|
||||
.map(
|
||||
(row) =>
|
||||
`"${row.date}","${row.nameVI}","${row.muaTm}","${row.muaCk}","${row.currency}","${row.nameEN}","${row.ban}"`
|
||||
)
|
||||
.join("\n");
|
||||
} else {
|
||||
headers = [
|
||||
"Date",
|
||||
"Label",
|
||||
"AskRate",
|
||||
"BidRateCK",
|
||||
"BidRateTM",
|
||||
"SourceCurrency",
|
||||
"TargetCurrency",
|
||||
"AskRateTM",
|
||||
];
|
||||
csvContent = headers.join(",") + "\n";
|
||||
csvContent += results
|
||||
.map(
|
||||
(row) =>
|
||||
`"${row.date}","${row.label}","${row.askRate}","${row.bidRateCK}","${row.bidRateTM}","${row.sourceCurrency}","${row.targetCurrency}","${row.askRateTM}"`
|
||||
)
|
||||
.join("\n");
|
||||
}
|
||||
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `exchange_rates_${selectedBank}_${
|
||||
new Date().toISOString().split("T")[0]
|
||||
}.csv`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 max-w-5xl w-full">
|
||||
<h1 className="text-2xl font-bold mb-4">Exchange Rate Export</h1>
|
||||
<div className="flex flex-col gap-4 mb-4">
|
||||
{/* Row 1: Start & End Date Pickers and Bank Select */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="form-group flex flex-col w-full sm:w-1/3">
|
||||
<label htmlFor="bank" className="mb-1">
|
||||
Bank:
|
||||
</label>
|
||||
<select
|
||||
id="bank"
|
||||
value={selectedBank}
|
||||
onChange={(e) => setSelectedBank(e.target.value)}
|
||||
className="border rounded p-2 w-full theme-select"
|
||||
style={{
|
||||
background: "var(--background)",
|
||||
color: "var(--foreground)",
|
||||
}}
|
||||
>
|
||||
<option value="bidv">BIDV</option>
|
||||
<option value="tcb">Techcombank</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group flex flex-col w-full sm:w-1/3">
|
||||
<label htmlFor="start-date" className="mb-1">
|
||||
Start Date:
|
||||
</label>
|
||||
<DatePicker
|
||||
id="start-date"
|
||||
selected={startDate}
|
||||
onChange={(date) => setStartDate(date)}
|
||||
maxDate={endDate || new Date()}
|
||||
dateFormat="yyyy-MM-dd"
|
||||
className="border rounded p-2 w-full"
|
||||
placeholderText="Select start date"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group flex flex-col w-full sm:w-1/3">
|
||||
<label htmlFor="end-date" className="mb-1">
|
||||
End Date:
|
||||
</label>
|
||||
<DatePicker
|
||||
id="end-date"
|
||||
selected={endDate}
|
||||
onChange={(date) => setEndDate(date)}
|
||||
minDate={startDate}
|
||||
maxDate={new Date()}
|
||||
dateFormat="yyyy-MM-dd"
|
||||
className="border rounded p-2 w-full"
|
||||
placeholderText="Select end date"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* Row 2: Fetch & Export Buttons aligned with End Date */}
|
||||
<div className="flex flex-row gap-2 justify-end items-end">
|
||||
<button
|
||||
className="fetch-btn bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
|
||||
onClick={handleFetch}
|
||||
disabled={isLoading}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
{isLoading ? "Fetching..." : "Fetch Rates"}
|
||||
</button>
|
||||
<button
|
||||
className="export-btn bg-green-600 text-white px-4 py-2 rounded disabled:opacity-50"
|
||||
onClick={handleExport}
|
||||
disabled={results.length === 0 || isLoading}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
Export CSV
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <div className="error text-red-600 mb-2">{error}</div>}
|
||||
{isLoading && (
|
||||
<div className="loading mb-2">Loading data, please wait...</div>
|
||||
)}
|
||||
{showTable && (
|
||||
<div className="table-container overflow-x-auto mt-4">
|
||||
{selectedBank === "bidv" ? (
|
||||
<table className="min-w-full border border-gray-300">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="border px-2 py-1">Date</th>
|
||||
<th className="border px-2 py-1">NameVI</th>
|
||||
<th className="border px-2 py-1">MuaTm</th>
|
||||
<th className="border px-2 py-1">MuaCk</th>
|
||||
<th className="border px-2 py-1">Currency</th>
|
||||
<th className="border px-2 py-1">NameEN</th>
|
||||
<th className="border px-2 py-1">Ban</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map((result, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="border px-2 py-1">{result.date}</td>
|
||||
<td className="border px-2 py-1">{result.nameVI}</td>
|
||||
<td className="border px-2 py-1">{result.muaTm}</td>
|
||||
<td className="border px-2 py-1">{result.muaCk}</td>
|
||||
<td className="border px-2 py-1">{result.currency}</td>
|
||||
<td className="border px-2 py-1">{result.nameEN}</td>
|
||||
<td className="border px-2 py-1">{result.ban}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<table className="min-w-full border border-gray-300">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="border px-2 py-1">Date</th>
|
||||
<th className="border px-2 py-1">Label</th>
|
||||
<th className="border px-2 py-1">AskRate</th>
|
||||
<th className="border px-2 py-1">BidRateCK</th>
|
||||
<th className="border px-2 py-1">BidRateTM</th>
|
||||
<th className="border px-2 py-1">SourceCurrency</th>
|
||||
<th className="border px-2 py-1">TargetCurrency</th>
|
||||
<th className="border px-2 py-1">AskRateTM</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map((result, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="border px-2 py-1">{result.date}</td>
|
||||
<td className="border px-2 py-1">{result.label}</td>
|
||||
<td className="border px-2 py-1">{result.askRate}</td>
|
||||
<td className="border px-2 py-1">{result.bidRateCK}</td>
|
||||
<td className="border px-2 py-1">{result.bidRateTM}</td>
|
||||
<td className="border px-2 py-1">
|
||||
{result.sourceCurrency}
|
||||
</td>
|
||||
<td className="border px-2 py-1">
|
||||
{result.targetCurrency}
|
||||
</td>
|
||||
<td className="border px-2 py-1">{result.askRateTM}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
|
||||
|
||||
const CHART_COLORS = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#ec4899", "#06b6d4", "#84cc16"];
|
||||
const MAX_DOTS_DAYS = 31;
|
||||
const MAX_LEGEND_LINES = 8;
|
||||
|
||||
// Parse rate string to number (handles comma-separated values like "25,880")
|
||||
function parseRate(val) {
|
||||
if (!val) return null;
|
||||
const num = parseFloat(String(val).replace(/,/g, ""));
|
||||
return isNaN(num) ? null : num;
|
||||
}
|
||||
|
||||
export function RateTrendChart({ results, selectedBank, compareMode }) {
|
||||
const chartData = [];
|
||||
|
||||
if (compareMode) {
|
||||
const byDate = new Map();
|
||||
for (const row of results) {
|
||||
if (!byDate.has(row.date)) byDate.set(row.date, {});
|
||||
const entry = byDate.get(row.date);
|
||||
entry.date = row.date;
|
||||
if (row.bidvSell) entry["BIDV Sell"] = parseRate(row.bidvSell);
|
||||
if (row.tcbAsk) entry["TCB Ask"] = parseRate(row.tcbAsk);
|
||||
}
|
||||
chartData.push(...byDate.values());
|
||||
} else if (selectedBank === "bidv") {
|
||||
const byDate = new Map();
|
||||
for (const row of results) {
|
||||
if (!byDate.has(row.date)) byDate.set(row.date, { date: row.date });
|
||||
const entry = byDate.get(row.date);
|
||||
const label = row.currency || "USD";
|
||||
entry[`${label} Buy`] = parseRate(row.muaTm);
|
||||
entry[`${label} Sell`] = parseRate(row.ban);
|
||||
}
|
||||
chartData.push(...byDate.values());
|
||||
} else {
|
||||
const byDate = new Map();
|
||||
for (const row of results) {
|
||||
if (!byDate.has(row.date)) byDate.set(row.date, { date: row.date });
|
||||
const entry = byDate.get(row.date);
|
||||
const label = row.sourceCurrency || "USD";
|
||||
entry[`${label} Bid`] = parseRate(row.bidRateTM);
|
||||
entry[`${label} Ask`] = parseRate(row.askRate);
|
||||
}
|
||||
chartData.push(...byDate.values());
|
||||
}
|
||||
|
||||
if (chartData.length === 0) return null;
|
||||
|
||||
const lineKeys = new Set();
|
||||
for (const row of chartData) {
|
||||
for (const key of Object.keys(row)) {
|
||||
if (key !== "date" && typeof row[key] === "number") lineKeys.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg p-4 mb-4 bg-[var(--card-bg)] border border-[var(--card-border)]">
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<LineChart data={chartData} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--card-border)" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tick={{ fontSize: 11, fill: "var(--muted)" }}
|
||||
tickLine={false}
|
||||
/>
|
||||
<YAxis
|
||||
tick={{ fontSize: 11, fill: "var(--muted)" }}
|
||||
tickLine={false}
|
||||
domain={["auto", "auto"]}
|
||||
label={{ value: "VND", angle: -90, position: "insideLeft", style: { fontSize: 11, fill: "var(--muted)" } }}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
background: "var(--card-bg)",
|
||||
border: "1px solid var(--card-border)",
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
{lineKeys.size <= MAX_LEGEND_LINES && <Legend wrapperStyle={{ fontSize: 12 }} />}
|
||||
{Array.from(lineKeys).map((key, i) => (
|
||||
<Line
|
||||
key={key}
|
||||
type="monotone"
|
||||
dataKey={key}
|
||||
stroke={CHART_COLORS[i % CHART_COLORS.length]}
|
||||
strokeWidth={2}
|
||||
dot={chartData.length <= MAX_DOTS_DAYS}
|
||||
connectNulls
|
||||
/>
|
||||
))}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { subDays, startOfMonth, isSameDay } from "date-fns";
|
||||
|
||||
export const CURRENCY_OPTIONS = [
|
||||
"ALL", "USD", "EUR", "GBP", "JPY", "AUD",
|
||||
"CAD", "CHF", "SGD", "THB", "HKD", "CNY", "KRW",
|
||||
];
|
||||
|
||||
export const DATE_PRESETS = [
|
||||
{ label: "Today", start: () => new Date(), end: () => new Date() },
|
||||
{ label: "Last 7 days", start: () => subDays(new Date(), 7), end: () => new Date() },
|
||||
{ label: "Last 30 days", start: () => subDays(new Date(), 30), end: () => new Date() },
|
||||
{ label: "This month", start: () => startOfMonth(new Date()), end: () => new Date() },
|
||||
];
|
||||
|
||||
export function getActivePreset(startDate, endDate) {
|
||||
if (!startDate || !endDate) return null;
|
||||
for (const preset of DATE_PRESETS) {
|
||||
if (isSameDay(startDate, preset.start()) && isSameDay(endDate, preset.end())) {
|
||||
return preset.label;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const THEME_CYCLE = ["system", "light", "dark"];
|
||||
export const THEME_LABELS = { system: "System", light: "Light", dark: "Dark" };
|
||||
@@ -0,0 +1,20 @@
|
||||
export function rowsToCsv(rows) {
|
||||
return `${rows.map((row) => row.map(formatCsvCell).join(",")).join("\r\n")}\r\n`;
|
||||
}
|
||||
|
||||
export function downloadTextFile(text, filename, type) {
|
||||
const blob = new Blob([text], { type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function formatCsvCell(value) {
|
||||
const text = value == null ? "" : String(value);
|
||||
return /[",\r\n]/.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
export function SunIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function MoonIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function SystemIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M9 17.25v1.007a3 3 0 0 1-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0 1 15 18.257V17.25m6-12V15a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 15V5.25A2.25 2.25 0 0 1 5.25 3h13.5A2.25 2.25 0 0 1 21 5.25Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function FetchIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExcelIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M3.375 19.5h17.25m-17.25 0a1.125 1.125 0 0 1-1.125-1.125M3.375 19.5h7.5c.621 0 1.125-.504 1.125-1.125m-9.75 0V5.625m0 12.75v-1.5c0-.621.504-1.125 1.125-1.125m18.375 2.625V5.625m0 12.75c0 .621-.504 1.125-1.125 1.125m1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125m0 3.75h-7.5A1.125 1.125 0 0 1 12 18.375m9.75-12.75c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125m19.5 0v1.5c0 .621-.504 1.125-1.125 1.125M2.25 5.625v1.5c0 .621.504 1.125 1.125 1.125m0 0h17.25m-17.25 0h7.5c.621 0 1.125.504 1.125 1.125M3.375 8.25c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m17.25-3.75h-7.5c-.621 0-1.125.504-1.125 1.125m8.625-1.125c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h7.5m-7.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M12 10.875v-1.5m0 1.5c0 .621-.504 1.125-1.125 1.125M12 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125M10.875 12c-.621 0-1.125.504-1.125 1.125M12 12c.621 0 1.125.504 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m0 0v1.5c0 .621-.504 1.125-1.125 1.125m0 0c-.621 0-1.125.504-1.125 1.125v1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CsvIcon() {
|
||||
return (
|
||||
<svg aria-hidden="true" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
export function LoadingSpinner({ progress }) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="flex flex-col items-center gap-3 w-64">
|
||||
<div className="w-8 h-8 border-[3px] border-blue-200 border-t-blue-600 rounded-full animate-spin" />
|
||||
<p className="text-[var(--muted)] text-sm">
|
||||
{progress?.total ? `Fetching rates for ${progress.total} day${progress.total > 1 ? "s" : ""}...` : "Fetching exchange rates..."}
|
||||
</p>
|
||||
{progress?.total > 1 && (
|
||||
<div className="w-full h-1.5 rounded-full bg-[var(--card-border)] overflow-hidden">
|
||||
<div className="h-full bg-blue-500 rounded-full animate-pulse" style={{ width: "100%" }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorMessage({ message }) {
|
||||
return (
|
||||
<div className="flex items-start gap-2 rounded-lg px-4 py-3 text-sm mb-4 bg-red-50 dark:bg-red-950 border border-red-500/20 text-red-500">
|
||||
<svg aria-hidden="true" className="shrink-0 mt-0.5 w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z" />
|
||||
</svg>
|
||||
<span>{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState() {
|
||||
return (
|
||||
<div className="text-center py-16 text-[var(--muted)]">
|
||||
<svg aria-hidden="true" className="mx-auto mb-4 w-12 h-12 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 3v11.25A2.25 2.25 0 0 0 6 16.5h2.25M3.75 3h-1.5m1.5 0h16.5m0 0h1.5m-1.5 0v11.25A2.25 2.25 0 0 1 18 16.5h-2.25m-7.5 0h7.5m-7.5 0-1 3m8.5-3 1 3m0 0 .5 1.5m-.5-1.5h-9.5m0 0-.5 1.5M9 11.25v-5.5m3 5.5V8.25" />
|
||||
</svg>
|
||||
<p className="text-lg font-medium mb-1">No exchange rate data</p>
|
||||
<p className="text-sm">Select a bank and date range, then click Fetch Rates to get started.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export function loadFromUrl() {
|
||||
if (typeof window === "undefined") return null;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const bank = params.get("bank");
|
||||
const currency = params.get("currency");
|
||||
const start = params.get("start");
|
||||
const end = params.get("end");
|
||||
if (!bank && !currency && !start && !end) return null;
|
||||
return {
|
||||
bank: bank || null,
|
||||
currency: currency || null,
|
||||
startDate: start ? new Date(start) : null,
|
||||
endDate: end ? new Date(end) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function loadSavedSettings() {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const saved = localStorage.getItem("exchangeRateSettings");
|
||||
if (!saved) return null;
|
||||
const parsed = JSON.parse(saved);
|
||||
return {
|
||||
bank: parsed.bank || "bidv",
|
||||
currency: parsed.currency || "USD",
|
||||
startDate: parsed.startDate ? new Date(parsed.startDate) : null,
|
||||
endDate: parsed.endDate ? new Date(parsed.endDate) : null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveSettings(bank, currency, startDate, endDate) {
|
||||
try {
|
||||
localStorage.setItem("exchangeRateSettings", JSON.stringify({
|
||||
bank,
|
||||
currency,
|
||||
startDate: startDate?.toISOString(),
|
||||
endDate: endDate?.toISOString(),
|
||||
}));
|
||||
} catch { /* ignore quota errors */ }
|
||||
}
|
||||
|
||||
export function applyTheme(value) {
|
||||
const root = document.documentElement;
|
||||
if (value === "system") {
|
||||
root.removeAttribute("data-theme");
|
||||
} else {
|
||||
root.setAttribute("data-theme", value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client";
|
||||
|
||||
export function ComparisonTable({ results }) {
|
||||
const headers = [
|
||||
{ label: "Date", numeric: false },
|
||||
{ label: "Currency", numeric: false },
|
||||
{ label: "BIDV Buy TM", numeric: true },
|
||||
{ label: "BIDV Sell", numeric: true },
|
||||
{ label: "TCB Bid TM", numeric: true },
|
||||
{ label: "TCB Ask", numeric: true },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Desktop table */}
|
||||
<div className="hidden sm:block overflow-x-auto rounded-lg border border-[var(--card-border)]">
|
||||
<table className="min-w-full text-sm">
|
||||
<thead className="sticky top-0 z-10">
|
||||
<tr className="bg-[var(--table-header-bg)]">
|
||||
{headers.map((h) => (
|
||||
<th
|
||||
key={h.label}
|
||||
className={`px-3 py-2.5 font-semibold whitespace-nowrap border-b border-[var(--card-border)] ${h.numeric ? "text-right" : "text-left"}`}
|
||||
>
|
||||
{h.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map((row, idx) => {
|
||||
const cells = [
|
||||
{ value: row.date, numeric: false },
|
||||
{ value: row.currency, numeric: false },
|
||||
{ value: row.bidvBuyTm, numeric: true },
|
||||
{ value: row.bidvSell, numeric: true },
|
||||
{ value: row.tcbBidTm, numeric: true },
|
||||
{ value: row.tcbAsk, numeric: true },
|
||||
];
|
||||
return (
|
||||
<tr
|
||||
key={`${row.date}-${row.currency}`}
|
||||
className={`transition-colors hover:!bg-[var(--table-row-hover)] ${idx % 2 !== 0 ? "bg-[var(--table-row-stripe)]" : ""}`}
|
||||
>
|
||||
{cells.map((cell, i) => (
|
||||
<td
|
||||
key={i}
|
||||
className={`px-3 py-2 whitespace-nowrap border-b border-[var(--card-border)] ${cell.numeric ? "text-right tabular-nums" : ""}`}
|
||||
>
|
||||
{cell.value || "-"}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/* Mobile cards */}
|
||||
<div className="sm:hidden flex flex-col gap-2">
|
||||
{results.map((row) => (
|
||||
<div key={`${row.date}-${row.currency}`} className="rounded-lg border border-[var(--card-border)] p-3 bg-[var(--card-bg)] text-sm">
|
||||
<div className="flex justify-between mb-1.5">
|
||||
<span className="font-medium">{row.date}</span>
|
||||
<span className="text-[var(--muted)]">{row.currency}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
||||
<div className="flex justify-between"><span className="text-[var(--muted)]">BIDV Buy</span><span className="tabular-nums">{row.bidvBuyTm || "-"}</span></div>
|
||||
<div className="flex justify-between"><span className="text-[var(--muted)]">TCB Bid</span><span className="tabular-nums">{row.tcbBidTm || "-"}</span></div>
|
||||
<div className="flex justify-between"><span className="text-[var(--muted)]">BIDV Sell</span><span className="tabular-nums">{row.bidvSell || "-"}</span></div>
|
||||
<div className="flex justify-between"><span className="text-[var(--muted)]">TCB Ask</span><span className="tabular-nums">{row.tcbAsk || "-"}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function RateTable({ results, selectedBank }) {
|
||||
const bidvHeaders = [
|
||||
{ label: "Date", numeric: false },
|
||||
{ label: "Name (VI)", numeric: false },
|
||||
{ label: "Buy TM", numeric: true },
|
||||
{ label: "Buy CK", numeric: true },
|
||||
{ label: "Currency", numeric: false },
|
||||
{ label: "Name (EN)", numeric: false },
|
||||
{ label: "Sell", numeric: true },
|
||||
];
|
||||
const tcbHeaders = [
|
||||
{ label: "Date", numeric: false },
|
||||
{ label: "Label", numeric: false },
|
||||
{ label: "Ask Rate", numeric: true },
|
||||
{ label: "Bid CK", numeric: true },
|
||||
{ label: "Bid TM", numeric: true },
|
||||
{ label: "Source", numeric: false },
|
||||
{ label: "Target", numeric: false },
|
||||
{ label: "Ask TM", numeric: true },
|
||||
];
|
||||
|
||||
const headers = selectedBank === "bidv" ? bidvHeaders : tcbHeaders;
|
||||
|
||||
const getRowCells = (row) => {
|
||||
if (selectedBank === "bidv") {
|
||||
return [
|
||||
{ value: row.date, numeric: false },
|
||||
{ value: row.nameVI, numeric: false },
|
||||
{ value: row.muaTm, numeric: true },
|
||||
{ value: row.muaCk, numeric: true },
|
||||
{ value: row.currency, numeric: false },
|
||||
{ value: row.nameEN, numeric: false },
|
||||
{ value: row.ban, numeric: true },
|
||||
];
|
||||
}
|
||||
return [
|
||||
{ value: row.date, numeric: false },
|
||||
{ value: row.label, numeric: false },
|
||||
{ value: row.askRate, numeric: true },
|
||||
{ value: row.bidRateCK, numeric: true },
|
||||
{ value: row.bidRateTM, numeric: true },
|
||||
{ value: row.sourceCurrency, numeric: false },
|
||||
{ value: row.targetCurrency, numeric: false },
|
||||
{ value: row.askRateTM, numeric: true },
|
||||
];
|
||||
};
|
||||
|
||||
const getMobileCard = (row) => {
|
||||
if (selectedBank === "bidv") {
|
||||
return { title: row.nameVI || row.nameEN, subtitle: `${row.currency} - ${row.date}`, fields: [
|
||||
{ label: "Buy TM", value: row.muaTm }, { label: "Buy CK", value: row.muaCk }, { label: "Sell", value: row.ban },
|
||||
]};
|
||||
}
|
||||
return { title: row.label, subtitle: `${row.sourceCurrency} - ${row.date}`, fields: [
|
||||
{ label: "Bid TM", value: row.bidRateTM }, { label: "Bid CK", value: row.bidRateCK },
|
||||
{ label: "Ask", value: row.askRate }, { label: "Ask TM", value: row.askRateTM },
|
||||
]};
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Desktop table */}
|
||||
<div className="hidden sm:block overflow-x-auto rounded-lg border border-[var(--card-border)]">
|
||||
<table className="min-w-full text-sm">
|
||||
<thead className="sticky top-0 z-10">
|
||||
<tr className="bg-[var(--table-header-bg)]">
|
||||
{headers.map((h) => (
|
||||
<th
|
||||
key={h.label}
|
||||
className={`px-3 py-2.5 font-semibold whitespace-nowrap border-b border-[var(--card-border)] ${h.numeric ? "text-right" : "text-left"}`}
|
||||
>
|
||||
{h.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{results.map((row, idx) => {
|
||||
const cells = getRowCells(row);
|
||||
const rowKey = selectedBank === "bidv"
|
||||
? `${row.date}-${row.currency}-${row.nameVI}`
|
||||
: `${row.date}-${row.sourceCurrency}-${row.label}`;
|
||||
return (
|
||||
<tr
|
||||
key={rowKey}
|
||||
className={`transition-colors hover:!bg-[var(--table-row-hover)] ${idx % 2 !== 0 ? "bg-[var(--table-row-stripe)]" : ""}`}
|
||||
>
|
||||
{cells.map((cell, i) => (
|
||||
<td
|
||||
key={i}
|
||||
className={`px-3 py-2 whitespace-nowrap border-b border-[var(--card-border)] ${cell.numeric ? "text-right tabular-nums" : ""}`}
|
||||
>
|
||||
{cell.value}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/* Mobile cards */}
|
||||
<div className="sm:hidden flex flex-col gap-2">
|
||||
{results.map((row) => {
|
||||
const card = getMobileCard(row);
|
||||
const rowKey = selectedBank === "bidv"
|
||||
? `${row.date}-${row.currency}-${row.nameVI}`
|
||||
: `${row.date}-${row.sourceCurrency}-${row.label}`;
|
||||
return (
|
||||
<div key={rowKey} className="rounded-lg border border-[var(--card-border)] p-3 bg-[var(--card-bg)] text-sm">
|
||||
<div className="flex justify-between mb-1.5">
|
||||
<span className="font-medium">{card.title}</span>
|
||||
<span className="text-[var(--muted)] text-xs">{card.subtitle}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
|
||||
{card.fields.map((f, i) => (
|
||||
<div key={i} className="flex justify-between">
|
||||
<span className="text-[var(--muted)]">{f.label}</span>
|
||||
<span className="tabular-nums">{f.value || "-"}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import { format, subDays, differenceInCalendarDays } from "date-fns";
|
||||
import writeExcelFile from "write-excel-file/browser";
|
||||
import { LoadingSpinner, ErrorMessage, EmptyState } from "./exchange-rate-status";
|
||||
import { RateTable, ComparisonTable } from "./exchange-rate-table";
|
||||
import { RateTrendChart } from "./exchange-rate-chart";
|
||||
import { SunIcon, MoonIcon, SystemIcon, FetchIcon, ExcelIcon, CsvIcon } from "./exchange-rate-icons";
|
||||
import { loadFromUrl, loadSavedSettings, saveSettings, applyTheme } from "./exchange-rate-storage";
|
||||
import { CURRENCY_OPTIONS, DATE_PRESETS, getActivePreset, THEME_CYCLE, THEME_LABELS } from "./exchange-rate-constants";
|
||||
import { downloadTextFile, rowsToCsv } from "./exchange-rate-export-files";
|
||||
|
||||
export default function ExchangeRateViewer() {
|
||||
const [startDate, setStartDate] = useState(() => subDays(new Date(), 7));
|
||||
const [endDate, setEndDate] = useState(() => new Date());
|
||||
const [selectedBank, setSelectedBank] = useState("bidv");
|
||||
const [selectedCurrency, setSelectedCurrency] = useState("USD");
|
||||
const [compareMode, setCompareMode] = useState(false);
|
||||
const [showChart, setShowChart] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [results, setResults] = useState([]);
|
||||
const [hasFetched, setHasFetched] = useState(false);
|
||||
const [progress, setProgress] = useState(null);
|
||||
const [theme, setTheme] = useState("system");
|
||||
|
||||
const [hydrated, setHydrated] = useState(false);
|
||||
useEffect(() => {
|
||||
const urlSettings = loadFromUrl();
|
||||
const saved = urlSettings || loadSavedSettings();
|
||||
if (saved) {
|
||||
if (saved.bank) setSelectedBank(saved.bank);
|
||||
if (saved.currency) setSelectedCurrency(saved.currency);
|
||||
if (saved.startDate) setStartDate(saved.startDate);
|
||||
if (saved.endDate) setEndDate(saved.endDate);
|
||||
}
|
||||
const savedTheme = localStorage.getItem("theme") || "system";
|
||||
setTheme(savedTheme);
|
||||
applyTheme(savedTheme);
|
||||
setHydrated(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hydrated) return;
|
||||
saveSettings(selectedBank, selectedCurrency, startDate, endDate);
|
||||
const params = new URLSearchParams();
|
||||
params.set("bank", selectedBank);
|
||||
params.set("currency", selectedCurrency);
|
||||
if (startDate) params.set("start", format(startDate, "yyyy-MM-dd"));
|
||||
if (endDate) params.set("end", format(endDate, "yyyy-MM-dd"));
|
||||
window.history.replaceState(null, "", `?${params.toString()}`);
|
||||
}, [selectedBank, selectedCurrency, startDate, endDate, hydrated]);
|
||||
|
||||
const fetchBank = async (bank) => {
|
||||
const response = await fetch("/api/exchange-rates", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
startDate: format(startDate, "yyyy-MM-dd"),
|
||||
endDate: format(endDate, "yyyy-MM-dd"),
|
||||
bank,
|
||||
currency: selectedCurrency,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || `Failed to fetch ${bank} rates`);
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const handleFetch = useCallback(async () => {
|
||||
if (!startDate || !endDate) {
|
||||
setError("Please select both start and end dates");
|
||||
return;
|
||||
}
|
||||
if (startDate > endDate) {
|
||||
setError("Start date cannot be after end date");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
setResults([]);
|
||||
setHasFetched(false);
|
||||
const totalDays = differenceInCalendarDays(endDate, startDate) + 1;
|
||||
setProgress({ total: totalDays });
|
||||
try {
|
||||
if (compareMode) {
|
||||
const [bidvData, tcbData] = await Promise.all([fetchBank("bidv"), fetchBank("tcb")]);
|
||||
const merged = new Map();
|
||||
for (const row of (bidvData.data || [])) {
|
||||
const key = `${row.date}|${row.currency}`;
|
||||
merged.set(key, { date: row.date, currency: row.currency, bidvBuyTm: row.muaTm, bidvSell: row.ban });
|
||||
}
|
||||
for (const row of (tcbData.data || [])) {
|
||||
const key = `${row.date}|${row.sourceCurrency}`;
|
||||
const existing = merged.get(key) || { date: row.date, currency: row.sourceCurrency };
|
||||
existing.tcbBidTm = row.bidRateTM;
|
||||
existing.tcbAsk = row.askRate;
|
||||
merged.set(key, existing);
|
||||
}
|
||||
setResults(Array.from(merged.values()).sort((a, b) => a.date.localeCompare(b.date)));
|
||||
} else {
|
||||
const data = await fetchBank(selectedBank);
|
||||
setResults(data.data || []);
|
||||
}
|
||||
setHasFetched(true);
|
||||
} catch (err) {
|
||||
setError(`An error occurred while fetching exchange rates: ${err.message}`);
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setProgress(null);
|
||||
}
|
||||
}, [startDate, endDate, selectedBank, selectedCurrency, compareMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hydrated) handleFetch();
|
||||
}, [hydrated]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const getExportRows = () => {
|
||||
if (compareMode) {
|
||||
const headers = ["Date", "Currency", "BIDV Buy TM", "BIDV Sell", "TCB Bid TM", "TCB Ask"];
|
||||
return [headers, ...results.map((r) => [r.date, r.currency, r.bidvBuyTm || "", r.bidvSell || "", r.tcbBidTm || "", r.tcbAsk || ""])];
|
||||
}
|
||||
if (selectedBank === "bidv") {
|
||||
const headers = ["Date", "NameVI", "MuaTm", "MuaCk", "Currency", "NameEN", "Ban"];
|
||||
return [headers, ...results.map((r) => [r.date, r.nameVI, r.muaTm, r.muaCk, r.currency, r.nameEN, r.ban])];
|
||||
}
|
||||
const headers = ["Date", "Label", "AskRate", "BidRateCK", "BidRateTM", "SourceCurrency", "TargetCurrency", "AskRateTM"];
|
||||
return [headers, ...results.map((r) => [r.date, r.label, r.askRate, r.bidRateCK, r.bidRateTM, r.sourceCurrency, r.targetCurrency, r.askRateTM])];
|
||||
};
|
||||
|
||||
const baseFilename = `exchange_rates_${compareMode ? "compare" : selectedBank}_${selectedCurrency}_${format(new Date(), "yyyy-MM-dd")}`;
|
||||
|
||||
const handleExportExcel = async () => {
|
||||
if (results.length === 0) return;
|
||||
await writeExcelFile(getExportRows(), { sheet: "Exchange Rates" }).toFile(`${baseFilename}.xlsx`);
|
||||
};
|
||||
|
||||
const handleExportCsv = () => {
|
||||
if (results.length === 0) return;
|
||||
downloadTextFile(rowsToCsv(getExportRows()), `${baseFilename}.csv`, "text/csv;charset=utf-8;");
|
||||
};
|
||||
|
||||
const activePreset = getActivePreset(startDate, endDate);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 max-w-5xl w-full">
|
||||
<div className="mb-6 flex items-start justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Exchange Rate Export</h1>
|
||||
<p className="text-sm mt-1 text-[var(--muted)]">
|
||||
Fetch exchange rates from Vietnamese banks and export to Excel or CSV.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
title={`Theme: ${THEME_LABELS[theme]}`}
|
||||
onClick={() => {
|
||||
const next = THEME_CYCLE[(THEME_CYCLE.indexOf(theme) + 1) % THEME_CYCLE.length];
|
||||
setTheme(next);
|
||||
applyTheme(next);
|
||||
localStorage.setItem("theme", next);
|
||||
}}
|
||||
className="p-2 rounded-lg border border-[var(--input-border)] text-[var(--muted)] hover:text-[var(--foreground)] transition-colors"
|
||||
>
|
||||
{theme === "dark" ? <MoonIcon /> : theme === "light" ? <SunIcon /> : <SystemIcon />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="rounded-xl p-5 mb-6 bg-[var(--card-bg)] border border-[var(--card-border)]"
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !isLoading) handleFetch(); }}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Row 1: Selectors and date pickers */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div className="flex flex-col">
|
||||
<label htmlFor="bank" className="text-sm font-medium mb-1.5">Bank</label>
|
||||
<select
|
||||
id="bank"
|
||||
value={selectedBank}
|
||||
onChange={(e) => setSelectedBank(e.target.value)}
|
||||
disabled={compareMode}
|
||||
className="border rounded-lg px-3 py-2 text-sm w-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/30 disabled:opacity-50 bg-[var(--input-bg)] text-[var(--foreground)] border-[var(--input-border)]"
|
||||
>
|
||||
<option value="bidv">BIDV</option>
|
||||
<option value="tcb">Techcombank</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<label htmlFor="currency" className="text-sm font-medium mb-1.5">Currency</label>
|
||||
<select
|
||||
id="currency"
|
||||
value={selectedCurrency}
|
||||
onChange={(e) => setSelectedCurrency(e.target.value)}
|
||||
className="border rounded-lg px-3 py-2 text-sm w-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/30 bg-[var(--input-bg)] text-[var(--foreground)] border-[var(--input-border)]"
|
||||
>
|
||||
{CURRENCY_OPTIONS.map((c) => (
|
||||
<option key={c} value={c}>{c === "ALL" ? "All Currencies" : c}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<label htmlFor="start-date" className="text-sm font-medium mb-1.5">Start Date</label>
|
||||
<DatePicker
|
||||
id="start-date"
|
||||
selected={startDate}
|
||||
onChange={(date) => setStartDate(date)}
|
||||
maxDate={endDate || new Date()}
|
||||
dateFormat="yyyy-MM-dd"
|
||||
className="border rounded-lg px-3 py-2 text-sm w-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/30"
|
||||
placeholderText="Select start date"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<label htmlFor="end-date" className="text-sm font-medium mb-1.5">End Date</label>
|
||||
<DatePicker
|
||||
id="end-date"
|
||||
selected={endDate}
|
||||
onChange={(date) => setEndDate(date)}
|
||||
minDate={startDate}
|
||||
maxDate={new Date()}
|
||||
dateFormat="yyyy-MM-dd"
|
||||
className="border rounded-lg px-3 py-2 text-sm w-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/30"
|
||||
placeholderText="Select end date"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 2: Toggles and date presets */}
|
||||
<div className="flex flex-wrap items-center gap-3 pt-1 border-t border-[var(--card-border)]">
|
||||
<label className="flex items-center gap-1.5 text-xs cursor-pointer text-[var(--muted)]">
|
||||
<input type="checkbox" checked={compareMode} onChange={(e) => setCompareMode(e.target.checked)} className="rounded" />
|
||||
Compare BIDV vs TCB
|
||||
</label>
|
||||
<label className="flex items-center gap-1.5 text-xs cursor-pointer text-[var(--muted)]">
|
||||
<input type="checkbox" checked={showChart} onChange={(e) => setShowChart(e.target.checked)} className="rounded" />
|
||||
Show Chart
|
||||
</label>
|
||||
<span className="text-[var(--card-border)]">|</span>
|
||||
{DATE_PRESETS.map((preset) => (
|
||||
<button
|
||||
key={preset.label}
|
||||
type="button"
|
||||
className={`text-xs px-3 py-1 rounded-md border transition-colors ${
|
||||
activePreset === preset.label
|
||||
? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border-blue-300 dark:border-blue-700 font-medium"
|
||||
: "border-[var(--input-border)] text-[var(--muted)] hover:bg-blue-50 dark:hover:bg-blue-900/20"
|
||||
}`}
|
||||
onClick={() => { setStartDate(preset.start()); setEndDate(preset.end()); }}
|
||||
>
|
||||
{preset.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Row 3: Action buttons */}
|
||||
<div className="flex flex-col sm:flex-row gap-2 sm:justify-end pt-1">
|
||||
<button
|
||||
className="bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white text-sm font-medium px-5 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-blue-500/40 inline-flex items-center justify-center gap-2"
|
||||
onClick={handleFetch}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<FetchIcon />
|
||||
{isLoading ? "Fetching..." : "Fetch Rates"}
|
||||
</button>
|
||||
<button
|
||||
className="bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white text-sm font-medium px-5 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-emerald-500/40 inline-flex items-center justify-center gap-2"
|
||||
onClick={handleExportExcel}
|
||||
disabled={results.length === 0 || isLoading}
|
||||
>
|
||||
<ExcelIcon />
|
||||
Export Excel
|
||||
</button>
|
||||
<button
|
||||
className="text-sm font-medium px-5 py-2 rounded-lg border transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-blue-500/30 inline-flex items-center justify-center gap-2 border-[var(--input-border)] text-[var(--foreground)]"
|
||||
onClick={handleExportCsv}
|
||||
disabled={results.length === 0 || isLoading}
|
||||
>
|
||||
<CsvIcon />
|
||||
Export CSV
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div aria-live="polite" aria-atomic="true">
|
||||
{error && <ErrorMessage message={error} />}
|
||||
{isLoading && <LoadingSpinner progress={progress} />}
|
||||
{!isLoading && hasFetched && results.length === 0 && <EmptyState />}
|
||||
{!isLoading && hasFetched && results.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<p className="text-sm text-[var(--muted)]">
|
||||
{results.length} {results.length === 1 ? "record" : "records"} found
|
||||
</p>
|
||||
</div>
|
||||
{showChart && (
|
||||
<RateTrendChart results={results} selectedBank={selectedBank} compareMode={compareMode} />
|
||||
)}
|
||||
{compareMode
|
||||
? <ComparisonTable results={results} />
|
||||
: <RateTable results={results} selectedBank={selectedBank} />
|
||||
}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+92
-3
@@ -1,21 +1,53 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--background: #f8fafc;
|
||||
--foreground: #171717;
|
||||
--card-bg: #ffffff;
|
||||
--card-border: #e2e8f0;
|
||||
--input-bg: #ffffff;
|
||||
--input-border: #cbd5e1;
|
||||
--input-focus: #3b82f6;
|
||||
--table-header-bg: #f1f5f9;
|
||||
--table-row-hover: #e2e8f0;
|
||||
--table-row-stripe: #f1f5f9;
|
||||
--muted: #64748b;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
/* Dark mode: explicit toggle OR system preference (unless overridden to light) */
|
||||
:root[data-theme="dark"] {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
--card-bg: #18181b;
|
||||
--card-border: #27272a;
|
||||
--input-bg: #1e1e22;
|
||||
--input-border: #3f3f46;
|
||||
--input-focus: #60a5fa;
|
||||
--table-header-bg: #1e1e22;
|
||||
--table-row-hover: #27272a;
|
||||
--table-row-stripe: #141416;
|
||||
--muted: #a1a1aa;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
:root:not([data-theme="light"]) {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
--card-bg: #18181b;
|
||||
--card-border: #27272a;
|
||||
--input-bg: #1e1e22;
|
||||
--input-border: #3f3f46;
|
||||
--input-focus: #60a5fa;
|
||||
--table-header-bg: #1e1e22;
|
||||
--table-row-hover: #27272a;
|
||||
--table-row-stripe: #141416;
|
||||
--muted: #a1a1aa;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,3 +56,60 @@ body {
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
/* Date picker dark mode support */
|
||||
.react-datepicker-wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.react-datepicker__input-container input {
|
||||
background: var(--input-bg) !important;
|
||||
color: var(--foreground) !important;
|
||||
border-color: var(--input-border) !important;
|
||||
}
|
||||
|
||||
.react-datepicker {
|
||||
background-color: var(--card-bg) !important;
|
||||
border-color: var(--card-border) !important;
|
||||
color: var(--foreground) !important;
|
||||
font-family: inherit !important;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12) !important;
|
||||
}
|
||||
|
||||
.react-datepicker__header {
|
||||
background-color: var(--table-header-bg) !important;
|
||||
border-bottom-color: var(--card-border) !important;
|
||||
}
|
||||
|
||||
.react-datepicker__current-month,
|
||||
.react-datepicker__day-name {
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
.react-datepicker__day {
|
||||
color: var(--foreground) !important;
|
||||
border-radius: 6px !important;
|
||||
}
|
||||
|
||||
.react-datepicker__day:hover {
|
||||
background-color: var(--table-row-hover) !important;
|
||||
}
|
||||
|
||||
.react-datepicker__day--selected,
|
||||
.react-datepicker__day--keyboard-selected {
|
||||
background-color: #3b82f6 !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
.react-datepicker__day--disabled {
|
||||
color: var(--muted) !important;
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.react-datepicker__navigation-icon::before {
|
||||
border-color: var(--muted) !important;
|
||||
}
|
||||
|
||||
.react-datepicker__triangle {
|
||||
display: none !important;
|
||||
}
|
||||
+4
-9
@@ -1,4 +1,4 @@
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Geist } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { Analytics } from "@vercel/analytics/react";
|
||||
import { SpeedInsights } from '@vercel/speed-insights/next';
|
||||
@@ -8,21 +8,16 @@ const geistSans = Geist({
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Exchange Rate Export",
|
||||
description: "Fetch exchange rates from Vietnamese banks and export to Excel or CSV.",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
className={`${geistSans.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
<Analytics />
|
||||
|
||||
+2
-20
@@ -1,28 +1,10 @@
|
||||
"use client";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import ExchangeRateViewer from "./components/ExchangeRateViewer";
|
||||
import { format, subDays } from "date-fns";
|
||||
import ExchangeRateViewer from "./components/exchange-rate-viewer";
|
||||
|
||||
export default function Home() {
|
||||
const [defaultStartDate, setDefaultStartDate] = useState("");
|
||||
const [defaultEndDate, setDefaultEndDate] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const today = new Date();
|
||||
const weekAgo = subDays(today, 7);
|
||||
setDefaultStartDate(format(weekAgo, "yyyy-MM-dd"));
|
||||
setDefaultEndDate(format(today, "yyyy-MM-dd"));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen w-full flex flex-col items-center justify-center bg-background text-foreground font-[family-name:var(--font-geist-sans)]">
|
||||
<main className="w-full flex flex-col items-center">
|
||||
{defaultStartDate && defaultEndDate && (
|
||||
<ExchangeRateViewer
|
||||
defaultStartDate={defaultStartDate}
|
||||
defaultEndDate={defaultEndDate}
|
||||
/>
|
||||
)}
|
||||
<ExchangeRateViewer />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user