Revert "Merge branch 'feature/pages'"

This reverts commit 3741d1b754, reversing
changes made to 3c7c93323f.
This commit is contained in:
tiennm99 committed 2026-08-07 13:44:56 +07:00
1 parent 3741d1b754
commit 3cef2ee4f4
30 files changed
+6003 -315

No files matched your search

-43
View File
@@ -1,43 +0,0 @@
# Simple workflow for deploying static content to GitHub Pages
name: Deploy static content to Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["feature/pages"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job since we're just deploying
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
# Upload entire repository
path: '.'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+1
View File
@@ -1,3 +1,4 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
+43 -6
View File
@@ -1,10 +1,47 @@
# exchange-rate-export
Get data from BIDV[https://bidv.com.vn/vn/ty-gia-ngoai-te] and export to Excel format.
Fetch data from BIDV or Techcombank and export to Excel or CSV.
Features:
- Allow select time range.
- Export to Excel.
- Choose BIDV or Techcombank.
- Select time range.
- View and export to Excel or CSV.
Use these api:
- https://bidv.com.vn/ServicesBIDV/ExchangeDetailSearchTimeServlet
- https://bidv.com.vn/ServicesBIDV/ExchangeDetailServlet
Use data from :
- https://bidv.com.vn/vn/ty-gia-ngoai-te
- https://techcombank.com/cong-cu-tien-ich/ty-gia
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
Requires Node.js 24+ and pnpm 11+.
First, run the development server:
```bash
pnpm install
pnpm dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
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.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-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;
-266
View File
@@ -1,266 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exchange Rate Export</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background: #f7f7f7;
}
.container {
background: #fff;
padding: 24px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.07);
max-width: 700px;
margin: auto;
}
h1 {
text-align: center;
}
label {
margin-right: 8px;
}
input[type="date"] {
margin-right: 16px;
padding: 4px 8px;
}
button {
padding: 8px 16px;
margin-right: 8px;
border: none;
border-radius: 4px;
background: #007bff;
color: #fff;
cursor: pointer;
font-size: 1rem;
}
button:disabled {
background: #aaa;
cursor: not-allowed;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 24px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
th {
background: #007bff;
color: #fff;
}
.loading {
text-align: center;
margin-top: 20px;
color: #007bff;
}
.error {
color: red;
text-align: center;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>Exchange Rate Export (USD)</h1>
<div style="margin-bottom: 20px;">
<label for="start-date">Start Date:</label>
<input type="date" id="start-date">
<label for="end-date">End Date:</label>
<input type="date" id="end-date">
<button id="fetch-btn">Fetch</button>
<button id="export-btn" disabled>Export CSV</button>
</div>
<div id="status"></div>
<table id="result-table" style="display:none;">
<thead>
<tr>
<th>Date</th>
<th>nameVI</th>
<th>muaTm</th>
<th>muaCk</th>
<th>currency</th>
<th>nameEN</th>
<th>ban</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const fetchBtn = document.getElementById('fetch-btn');
const exportBtn = document.getElementById('export-btn');
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
const statusDiv = document.getElementById('status');
const table = document.getElementById('result-table');
const tbody = table.querySelector('tbody');
let results = [];
function formatDate(date) {
// Format as dd/MM/yyyy
const d = new Date(date);
const day = String(d.getDate()).padStart(2, '0');
const month = String(d.getMonth() + 1).padStart(2, '0');
const year = d.getFullYear();
return `${day}/${month}/${year}`;
}
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);
}
return dates;
}
async function fetchNamerecord(dateStr) {
const url = 'https://bidv.com.vn/ServicesBIDV/ExchangeDetailSearchTimeServlet';
const payload = `date=${encodeURIComponent(dateStr)}`;
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: payload
});
if (!res.ok) throw new Error('API 1 error');
const data = await res.json();
if (data.status !== 1 || !data.data || !data.data.length) return null;
// Get the latest (max time) record
let latest = data.data[0];
for (const rec of data.data) {
if (rec.time > latest.time) latest = rec;
}
return latest.namerecord;
} catch (e) {
return null;
}
}
async function fetchUSD(dateStr, namerecord) {
const url = 'https://bidv.com.vn/ServicesBIDV/ExchangeDetailServlet';
const payload = `date=${encodeURIComponent(dateStr)}&time=${namerecord}`;
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: payload
});
if (!res.ok) throw new Error('API 2 error');
const data = await res.json();
if (data.status !== 1 || !data.data) return null;
// Find USD (currency === 'USD')
const usd = data.data.find(item => item.currency === 'USD');
if (!usd) return null;
return {
nameVI: usd.nameVI,
muaTm: usd.muaTm,
muaCk: usd.muaCk,
currency: usd.currency,
nameEN: usd.nameEN,
ban: usd.ban
};
} catch (e) {
return null;
}
}
function renderTable(data) {
tbody.innerHTML = '';
for (const row of data) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${row.date}</td>
<td>${row.nameVI}</td>
<td>${row.muaTm}</td>
<td>${row.muaCk}</td>
<td>${row.currency}</td>
<td>${row.nameEN}</td>
<td>${row.ban}</td>
`;
tbody.appendChild(tr);
}
table.style.display = data.length ? '' : 'none';
}
function exportCSV(data) {
const header = ['Date', 'nameVI', 'muaTm', 'muaCk', 'currency', 'nameEN', 'ban'];
const rows = [header];
for (const row of data) {
rows.push([
row.date,
row.nameVI,
row.muaTm,
row.muaCk,
row.currency,
row.nameEN,
row.ban
]);
}
const csvContent = rows.map(r => r.map(cell => '"' + String(cell).replace(/"/g, '""') + '"').join(',')).join('\r\n');
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'usd_exchange_rates.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
fetchBtn.onclick = async () => {
const start = startDateInput.value;
const end = endDateInput.value;
if (!start || !end) {
statusDiv.innerHTML = '<div class="error">Please select both start and end dates.</div>';
return;
}
if (start > end) {
statusDiv.innerHTML = '<div class="error">Start date must be before or equal to end date.</div>';
return;
}
statusDiv.innerHTML = '<div class="loading">Fetching data, please wait...</div>';
fetchBtn.disabled = true;
exportBtn.disabled = true;
results = [];
renderTable([]);
const dates = getDateRange(start, end);
for (let i = 0; i < dates.length; i++) {
const dateObj = dates[i];
const dateStr = formatDate(dateObj);
statusDiv.innerHTML = `<div class=\"loading\">Fetching: ${dateStr} (${i+1}/${dates.length})</div>`;
const namerecord = await fetchNamerecord(dateStr);
if (!namerecord) continue;
const usd = await fetchUSD(dateStr, namerecord);
if (usd) {
results.push({ date: dateStr, ...usd });
renderTable(results);
}
}
statusDiv.innerHTML = results.length ? '' : '<div class="error">No data found for the selected range.</div>';
fetchBtn.disabled = false;
exportBtn.disabled = results.length === 0;
};
exportBtn.onclick = () => {
if (results.length) exportCSV(results);
};
</script>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
+4
View File
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
+33
View File
@@ -0,0 +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": "eslint src"
},
"dependencies": {
"@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": {
"@tailwindcss/postcss": "^4",
"eslint": "^9.39.5",
"eslint-config-next": "16.2.11",
"tailwindcss": "^4"
},
"engines": {
"node": ">=24"
}
}
+4679
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
+1
View File
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

+191
View File
@@ -0,0 +1,191 @@
import { format, addDays, subDays } from "date-fns";
import axios from "axios";
import https from "https";
import crypto from "crypto";
const axiosInstance = axios.create({
httpsAgent: new https.Agent({
secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT,
}),
});
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 {
const timeUrl = `https://bidv.com.vn/ServicesBIDV/ExchangeDetailSearchTimeServlet?date=${dateStr}`;
const timeRes = await withRetry(() => axiosInstance.get(timeUrl));
const timeData = timeRes.data;
if (timeData.status !== 1 || !timeData.data?.length) return null;
const latest = timeData.data.reduce(
(best, current) => (current.time > best.time ? current : best),
timeData.data[0]
);
const rateUrl = `https://bidv.com.vn/ServicesBIDV/ExchangeDetailServlet?date=${dateStr}&time=${latest.namerecord}`;
const rateRes = await withRetry(() => axiosInstance.get(rateUrl));
const rateData = rateRes.data;
if (rateData.status !== 1 || !rateData.data) return null;
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.message);
return null;
}
}
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 withRetry(() => axiosInstance.get(url));
const data = res.data;
if (!data.exchangeRate?.data) return null;
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: 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.message);
return null;
}
}
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 = addDays(current, 1);
}
return dates;
}
// 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 = 0; attempt < maxAttempts; attempt++) {
currentDate = subDays(currentDate, 1);
const dateStr = format(currentDate, "yyyy-MM-dd");
if (rateCache.has(dateStr)) {
return rateCache.get(dateStr);
}
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, currency = "USD" } = body;
if (!startDate || !endDate || !bank) {
return Response.json(
{ error: "Missing required parameters" },
{ status: 400 }
);
}
const dates = getDateRange(startDate, endDate);
const rateCache = new Map();
const results = [];
// 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 Response.json({ data: results, total: dates.length, chunks: Math.ceil(dates.length / PARALLEL_CHUNK_SIZE) });
} catch (error) {
console.error("Server error:", error);
return Response.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+100
View File
@@ -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;
}
+47
View File
@@ -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);
}
}
+208
View File
@@ -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>
</>
);
}
+315
View File
@@ -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>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+115
View File
@@ -0,0 +1,115 @@
@import "tailwindcss";
:root {
--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);
}
/* 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: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;
}
}
body {
background: var(--background);
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;
}
+28
View File
@@ -0,0 +1,28 @@
import { Geist } from "next/font/google";
import "./globals.css";
import { Analytics } from "@vercel/analytics/react";
import { SpeedInsights } from '@vercel/speed-insights/next';
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
export const metadata = {
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} antialiased`}
>
{children}
<Analytics />
<SpeedInsights />
</body>
</html>
);
}
+11
View File
@@ -0,0 +1,11 @@
import ExchangeRateViewer from "./components/exchange-rate-viewer";
export default function Home() {
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">
<ExchangeRateViewer />
</main>
</div>
);
}