mirror of
https://github.com/vercel/next-learn.git
synced 2026-06-30 16:14:17 +00:00
* add database to project. Seed data. Update customerId to customer_id * seed customers table data * use database everywhere * refactor * fix ts lint errors * add type to invoice edit page * remove fetch-data file and fetch data directly in components * update lates invoices to use sql * in invoice table, search the database here with SQL * rename tsx files to ts and add node script to seed data * address rest of PR comments * move all data fetches to own file * add types to filter invoices function * remove unused param * prettier * update function names
63 lines
1.8 KiB
TypeScript
63 lines
1.8 KiB
TypeScript
import { Invoice, Revenue } from './definitions';
|
|
import { fetchLatestInvoices } from './data-fetches';
|
|
|
|
export const calculateAllInvoices = (
|
|
invoices: Invoice[],
|
|
status: 'pending' | 'paid',
|
|
) => {
|
|
return invoices
|
|
.filter((invoice) => !status || invoice.status === status)
|
|
.reduce((total, invoice) => total + invoice.amount / 100, 0)
|
|
.toLocaleString('en-US', {
|
|
style: 'currency',
|
|
currency: 'USD',
|
|
});
|
|
};
|
|
|
|
export const calculateCustomerInvoices = (
|
|
invoices: Invoice[],
|
|
status: 'pending' | 'paid',
|
|
customerId: number,
|
|
) => {
|
|
return invoices
|
|
.filter((invoice) => invoice.customer_id === customerId)
|
|
.filter((invoice) => !status || invoice.status === status)
|
|
.reduce((total, invoice) => total + invoice.amount / 100, 0)
|
|
.toLocaleString('en-US', {
|
|
style: 'currency',
|
|
currency: 'USD',
|
|
});
|
|
};
|
|
|
|
// Once a database is connected, we can use SQL to query the database directly
|
|
// This will be more efficient than querying all invoices and then filtering them
|
|
// E.g. "SELECT * FROM invoices
|
|
// ORDER BY date DESC
|
|
// LIMIT 5;"
|
|
|
|
export const countCustomerInvoices = (
|
|
invoices: Invoice[],
|
|
customerId: number,
|
|
) => {
|
|
return invoices.filter((invoice) => invoice.customer_id === customerId)
|
|
.length;
|
|
};
|
|
|
|
export const findLatestInvoices = async () => {
|
|
return await fetchLatestInvoices();
|
|
};
|
|
|
|
export const generateYAxis = (revenue: Revenue[]) => {
|
|
// Calculate what labels we need to display on the y-axis
|
|
// based on highest record and in 1000s
|
|
const yAxisLabels = [];
|
|
const highestRecord = Math.max(...revenue.map((month) => month.revenue));
|
|
const topLabel = Math.ceil(highestRecord / 1000) * 1000;
|
|
|
|
for (let i = topLabel; i >= 0; i -= 1000) {
|
|
yAxisLabels.push(`$${i / 1000}K`);
|
|
}
|
|
|
|
return { yAxisLabels, topLabel };
|
|
};
|