Compare commits
8 Commits
046ad1555c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b93c2e7e95 | ||
|
|
105b0c514f | ||
|
|
c6dd174376 | ||
|
|
27f6e627d4 | ||
|
|
76f2a43bd0 | ||
|
|
2df7f2d924 | ||
|
|
6fd531d9c3 | ||
|
|
01edded95a |
@@ -8,7 +8,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hono/node-server": "^1.19.5",
|
"@hono/node-server": "^1.19.5",
|
||||||
"@money/shared": "workspace:*",
|
"@money/shared": "*",
|
||||||
"better-auth": "^1.3.27",
|
"better-auth": "^1.3.27",
|
||||||
"hono": "^4.9.12",
|
"hono": "^4.9.12",
|
||||||
"plaid": "^39.0.0",
|
"plaid": "^39.0.0",
|
||||||
|
|||||||
@@ -20,25 +20,25 @@ export const auth = betterAuth({
|
|||||||
"money://",
|
"money://",
|
||||||
],
|
],
|
||||||
advanced: {
|
advanced: {
|
||||||
crossSubDomainCookies: {
|
crossSubDomainCookies: {
|
||||||
enabled: process.env.NODE_ENV == 'production',
|
enabled: process.env.NODE_ENV == "production",
|
||||||
domain: "koon.us",
|
domain: "koon.us",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
expo(),
|
expo(),
|
||||||
genericOAuth({
|
genericOAuth({
|
||||||
config: [
|
config: [
|
||||||
{
|
{
|
||||||
providerId: 'koon-family',
|
providerId: "koon-family",
|
||||||
clientId: process.env.OAUTH_CLIENT_ID!,
|
clientId: process.env.OAUTH_CLIENT_ID!,
|
||||||
clientSecret: process.env.OAUTH_CLIENT_SECRET!,
|
clientSecret: process.env.OAUTH_CLIENT_SECRET!,
|
||||||
discoveryUrl: process.env.OAUTH_DISCOVERY_URL!,
|
discoveryUrl: process.env.OAUTH_DISCOVERY_URL!,
|
||||||
scopes: ["profile", "email"],
|
scopes: ["profile", "email"],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}),
|
}),
|
||||||
deviceAuthorization(),
|
deviceAuthorization(),
|
||||||
bearer(),
|
bearer(),
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const app = getHono();
|
|||||||
app.use(
|
app.use(
|
||||||
"/api/*",
|
"/api/*",
|
||||||
cors({
|
cors({
|
||||||
origin: ['https://money.koon.us', `${BASE_URL}:8081`],
|
origin: ["https://money.koon.us", `${BASE_URL}:8081`],
|
||||||
allowMethods: ["POST", "GET", "OPTIONS"],
|
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||||
allowHeaders: ["Content-Type", "Authorization"],
|
allowHeaders: ["Content-Type", "Authorization"],
|
||||||
credentials: true,
|
credentials: true,
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import { Configuration, PlaidApi, PlaidEnvironments } from "plaid";
|
import { Configuration, PlaidApi, PlaidEnvironments } from "plaid";
|
||||||
|
|
||||||
const configuration = new Configuration({
|
const configuration = new Configuration({
|
||||||
basePath: process.env.PLAID_ENV == 'production' ? PlaidEnvironments.production : PlaidEnvironments.sandbox,
|
basePath:
|
||||||
|
process.env.PLAID_ENV == "production"
|
||||||
|
? PlaidEnvironments.production
|
||||||
|
: PlaidEnvironments.sandbox,
|
||||||
baseOptions: {
|
baseOptions: {
|
||||||
headers: {
|
headers: {
|
||||||
'PLAID-CLIENT-ID': process.env.PLAID_CLIENT_ID,
|
"PLAID-CLIENT-ID": process.env.PLAID_CLIENT_ID,
|
||||||
'PLAID-SECRET': process.env.PLAID_SECRET,
|
"PLAID-SECRET": process.env.PLAID_SECRET,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
export const plaidClient = new PlaidApi(configuration);
|
export const plaidClient = new PlaidApi(configuration);
|
||||||
|
|
||||||
|
|||||||
3
apps/api/src/plaid/sync.ts
Normal file
3
apps/api/src/plaid/sync.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
async function sync() {}
|
||||||
|
|
||||||
|
sync();
|
||||||
23
apps/api/src/plaid/tx.ts
Normal file
23
apps/api/src/plaid/tx.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import type { transaction } from "@money/shared/db";
|
||||||
|
import type { Transaction } from "plaid";
|
||||||
|
import { type InferInsertModel } from "drizzle-orm";
|
||||||
|
import { randomUUID } from "crypto";
|
||||||
|
|
||||||
|
export function transactionFromPlaid(
|
||||||
|
userId: string,
|
||||||
|
tx: Transaction,
|
||||||
|
): InferInsertModel<typeof transaction> {
|
||||||
|
return {
|
||||||
|
id: randomUUID(),
|
||||||
|
user_id: userId,
|
||||||
|
plaid_id: tx.transaction_id,
|
||||||
|
account_id: tx.account_id,
|
||||||
|
name: tx.name,
|
||||||
|
amount: tx.amount as any,
|
||||||
|
datetime: tx.datetime ? new Date(tx.datetime) : new Date(tx.date),
|
||||||
|
authorized_datetime: tx.authorized_datetime
|
||||||
|
? new Date(tx.authorized_datetime)
|
||||||
|
: undefined,
|
||||||
|
json: JSON.stringify(tx),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -3,12 +3,9 @@ import { plaidClient } from "./plaid";
|
|||||||
// import { LinkSessionFinishedWebhook, WebhookType } from "plaid";
|
// import { LinkSessionFinishedWebhook, WebhookType } from "plaid";
|
||||||
|
|
||||||
export const webhook = async (c: Context) => {
|
export const webhook = async (c: Context) => {
|
||||||
|
|
||||||
console.log("Got webhook");
|
console.log("Got webhook");
|
||||||
const b = await c.req.text();
|
const b = await c.req.text();
|
||||||
console.log("body:", b);
|
console.log("body:", b);
|
||||||
|
|
||||||
|
|
||||||
return c.text("Hi");
|
return c.text("Hi");
|
||||||
|
};
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import {
|
|||||||
PushProcessor,
|
PushProcessor,
|
||||||
ZQLDatabase,
|
ZQLDatabase,
|
||||||
} from "@rocicorp/zero/server";
|
} from "@rocicorp/zero/server";
|
||||||
import { PostgresJSConnection } from '@rocicorp/zero/pg';
|
import { PostgresJSConnection } from "@rocicorp/zero/pg";
|
||||||
import postgres from 'postgres';
|
import postgres from "postgres";
|
||||||
import {
|
import {
|
||||||
createMutators as createMutatorsShared,
|
createMutators as createMutatorsShared,
|
||||||
isLoggedIn,
|
isLoggedIn,
|
||||||
@@ -20,12 +20,33 @@ import {
|
|||||||
} from "@money/shared";
|
} from "@money/shared";
|
||||||
import type { AuthData } from "@money/shared/auth";
|
import type { AuthData } from "@money/shared/auth";
|
||||||
import { getHono } from "./hono";
|
import { getHono } from "./hono";
|
||||||
import { Configuration, CountryCode, PlaidApi, PlaidEnvironments, Products } from "plaid";
|
import {
|
||||||
|
Configuration,
|
||||||
|
CountryCode,
|
||||||
|
PlaidApi,
|
||||||
|
PlaidEnvironments,
|
||||||
|
Products,
|
||||||
|
SandboxItemFireWebhookRequestWebhookCodeEnum,
|
||||||
|
WebhookType,
|
||||||
|
} from "plaid";
|
||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
import { db } from "./db";
|
import { db } from "./db";
|
||||||
import { balance, plaidAccessTokens, plaidLink, transaction } from "@money/shared/db";
|
import {
|
||||||
import { eq, inArray, sql, type InferInsertModel } from "drizzle-orm";
|
balance,
|
||||||
|
plaidAccessTokens,
|
||||||
|
plaidLink,
|
||||||
|
transaction,
|
||||||
|
} from "@money/shared/db";
|
||||||
|
import {
|
||||||
|
and,
|
||||||
|
eq,
|
||||||
|
inArray,
|
||||||
|
sql,
|
||||||
|
type InferInsertModel,
|
||||||
|
type InferSelectModel,
|
||||||
|
} from "drizzle-orm";
|
||||||
import { plaidClient } from "./plaid";
|
import { plaidClient } from "./plaid";
|
||||||
|
import { transactionFromPlaid } from "./plaid/tx";
|
||||||
|
|
||||||
const processor = new PushProcessor(
|
const processor = new PushProcessor(
|
||||||
new ZQLDatabase(
|
new ZQLDatabase(
|
||||||
@@ -53,7 +74,7 @@ const createMutators = (authData: AuthData | null) => {
|
|||||||
products: [Products.Transactions],
|
products: [Products.Transactions],
|
||||||
country_codes: [CountryCode.Us],
|
country_codes: [CountryCode.Us],
|
||||||
webhook: "https://webhooks.koon.us/api/webhook_receiver",
|
webhook: "https://webhooks.koon.us/api/webhook_receiver",
|
||||||
hosted_link: {}
|
hosted_link: {},
|
||||||
});
|
});
|
||||||
const { link_token, hosted_link_url } = r.data;
|
const { link_token, hosted_link_url } = r.data;
|
||||||
|
|
||||||
@@ -70,29 +91,56 @@ const createMutators = (authData: AuthData | null) => {
|
|||||||
async get(_, { link_token }) {
|
async get(_, { link_token }) {
|
||||||
isLoggedIn(authData);
|
isLoggedIn(authData);
|
||||||
|
|
||||||
const linkResp = await plaidClient.linkTokenGet({
|
try {
|
||||||
link_token,
|
const token = await db.query.plaidLink.findFirst({
|
||||||
});
|
where: and(
|
||||||
if (!linkResp) throw Error("No link respo");
|
eq(plaidLink.token, link_token),
|
||||||
console.log(JSON.stringify(linkResp.data, null, 4));
|
eq(plaidLink.user_id, authData.user.id),
|
||||||
const publicToken = linkResp.data.link_sessions?.at(0)?.results?.item_add_results.at(0)?.public_token;
|
),
|
||||||
|
});
|
||||||
|
if (!token) throw Error("Link not found");
|
||||||
|
if (token.completeAt) return;
|
||||||
|
|
||||||
if (!publicToken) throw Error("No public token");
|
const linkResp = await plaidClient.linkTokenGet({
|
||||||
const { data } = await plaidClient.itemPublicTokenExchange({
|
link_token,
|
||||||
public_token: publicToken,
|
});
|
||||||
})
|
if (!linkResp) throw Error("No link respo");
|
||||||
|
|
||||||
await db.insert(plaidAccessTokens).values({
|
console.log(JSON.stringify(linkResp.data, null, 4));
|
||||||
id: randomUUID(),
|
|
||||||
userId: authData.user.id,
|
const item_add_result = linkResp.data.link_sessions
|
||||||
token: data.access_token,
|
?.at(0)
|
||||||
logoUrl: "",
|
?.results?.item_add_results.at(0);
|
||||||
name: ""
|
|
||||||
});
|
// We will assume its not done yet.
|
||||||
|
if (!item_add_result) return;
|
||||||
|
|
||||||
|
const { data } = await plaidClient.itemPublicTokenExchange({
|
||||||
|
public_token: item_add_result.public_token,
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.insert(plaidAccessTokens).values({
|
||||||
|
id: randomUUID(),
|
||||||
|
userId: authData.user.id,
|
||||||
|
token: data.access_token,
|
||||||
|
logoUrl: "",
|
||||||
|
name: item_add_result.institution?.name || "Unknown",
|
||||||
|
});
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(plaidLink)
|
||||||
|
.set({
|
||||||
|
completeAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(plaidLink.token, link_token));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
throw Error("Plaid error");
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
async webhook() {
|
||||||
async updateTransactions() {
|
|
||||||
isLoggedIn(authData);
|
isLoggedIn(authData);
|
||||||
|
|
||||||
const accounts = await db.query.plaidAccessTokens.findMany({
|
const accounts = await db.query.plaidAccessTokens.findMany({
|
||||||
where: eq(plaidAccessTokens.userId, authData.user.id),
|
where: eq(plaidAccessTokens.userId, authData.user.id),
|
||||||
});
|
});
|
||||||
@@ -101,41 +149,20 @@ const createMutators = (authData: AuthData | null) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const account of accounts) {
|
const account = accounts.at(0)!;
|
||||||
const { data } = await plaidClient.transactionsGet({
|
|
||||||
access_token: account.token,
|
|
||||||
start_date: "2025-10-01",
|
|
||||||
end_date: new Date().toISOString().split("T")[0],
|
|
||||||
});
|
|
||||||
|
|
||||||
const transactions = data.transactions.map(tx => ({
|
const { data } = await plaidClient.sandboxItemFireWebhook({
|
||||||
id: randomUUID(),
|
access_token: account.token,
|
||||||
user_id: authData.user.id,
|
webhook_type: WebhookType.Transactions,
|
||||||
plaid_id: tx.transaction_id,
|
webhook_code:
|
||||||
account_id: tx.account_id,
|
SandboxItemFireWebhookRequestWebhookCodeEnum.DefaultUpdate,
|
||||||
name: tx.name,
|
});
|
||||||
amount: tx.amount as any,
|
|
||||||
datetime: tx.datetime ? new Date(tx.datetime) : new Date(tx.date),
|
|
||||||
authorized_datetime: tx.authorized_datetime ? new Date(tx.authorized_datetime) : undefined,
|
|
||||||
json: JSON.stringify(tx),
|
|
||||||
} satisfies InferInsertModel<typeof transaction>));
|
|
||||||
|
|
||||||
await db.insert(transaction).values(transactions).onConflictDoNothing({
|
console.log(data);
|
||||||
target: transaction.plaid_id,
|
|
||||||
});
|
|
||||||
|
|
||||||
const txReplacingPendingIds = data.transactions
|
|
||||||
.filter(t => t.pending_transaction_id)
|
|
||||||
.map(t => t.pending_transaction_id!);
|
|
||||||
|
|
||||||
await db.delete(transaction)
|
|
||||||
.where(inArray(transaction.plaid_id, txReplacingPendingIds));
|
|
||||||
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
async sync() {
|
||||||
async updateBalences() {
|
|
||||||
isLoggedIn(authData);
|
isLoggedIn(authData);
|
||||||
|
|
||||||
const accounts = await db.query.plaidAccessTokens.findMany({
|
const accounts = await db.query.plaidAccessTokens.findMany({
|
||||||
where: eq(plaidAccessTokens.userId, authData.user.id),
|
where: eq(plaidAccessTokens.userId, authData.user.id),
|
||||||
});
|
});
|
||||||
@@ -144,28 +171,153 @@ const createMutators = (authData: AuthData | null) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const account of accounts) {
|
const account = accounts.at(0)!;
|
||||||
const { data } = await plaidClient.accountsBalanceGet({
|
|
||||||
access_token: account.token
|
|
||||||
});
|
|
||||||
await db.insert(balance).values(data.accounts.map(bal => ({
|
|
||||||
id: randomUUID(),
|
|
||||||
user_id: authData.user.id,
|
|
||||||
plaid_id: bal.account_id,
|
|
||||||
avaliable: bal.balances.available as any,
|
|
||||||
current: bal.balances.current as any,
|
|
||||||
name: bal.name,
|
|
||||||
tokenId: account.id,
|
|
||||||
}))).onConflictDoUpdate({
|
|
||||||
target: balance.plaid_id,
|
|
||||||
set: { current: sql.raw(`excluded.${balance.current.name}`), avaliable: sql.raw(`excluded.${balance.avaliable.name}`) }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const { data } = await plaidClient.transactionsSync({
|
||||||
|
access_token: account.token,
|
||||||
|
cursor: account.syncCursor || undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const added = data.added.map((tx) =>
|
||||||
|
transactionFromPlaid(authData.user.id, tx),
|
||||||
|
);
|
||||||
|
|
||||||
|
const updated = data.modified.map((tx) =>
|
||||||
|
transactionFromPlaid(authData.user.id, tx),
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log("added", added.length);
|
||||||
|
console.log("updated", updated.length);
|
||||||
|
console.log("removed", data.removed.length);
|
||||||
|
console.log("next cursor", data.next_cursor);
|
||||||
|
|
||||||
|
await db.transaction(async (tx) => {
|
||||||
|
if (added.length) {
|
||||||
|
await tx.insert(transaction).values(added);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updated.length) {
|
||||||
|
await tx
|
||||||
|
.insert(transaction)
|
||||||
|
.values(updated)
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: transaction.plaid_id,
|
||||||
|
set: {
|
||||||
|
name: sql.raw(`excluded.${transaction.name.name}`),
|
||||||
|
amount: sql.raw(`excluded.${transaction.amount.name}`),
|
||||||
|
json: sql.raw(`excluded.${transaction.json.name}`),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.removed.length) {
|
||||||
|
await tx.delete(transaction).where(
|
||||||
|
inArray(
|
||||||
|
transaction.id,
|
||||||
|
data.removed.map((tx) => tx.transaction_id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx
|
||||||
|
.update(plaidAccessTokens)
|
||||||
|
.set({ syncCursor: data.next_cursor })
|
||||||
|
.where(eq(plaidAccessTokens.id, account.id));
|
||||||
|
});
|
||||||
},
|
},
|
||||||
}
|
|
||||||
|
// async updateTransactions() {
|
||||||
|
// isLoggedIn(authData);
|
||||||
|
// const accounts = await db.query.plaidAccessTokens.findMany({
|
||||||
|
// where: eq(plaidAccessTokens.userId, authData.user.id),
|
||||||
|
// });
|
||||||
|
// if (accounts.length == 0) {
|
||||||
|
// console.error("No accounts");
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// for (const account of accounts) {
|
||||||
|
// const { data } = await plaidClient.transactionsGet({
|
||||||
|
// access_token: account.token,
|
||||||
|
// start_date: "2025-10-01",
|
||||||
|
// end_date: new Date().toISOString().split("T")[0],
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// const transactions = data.transactions.map(
|
||||||
|
// (tx) =>
|
||||||
|
// ({
|
||||||
|
// id: randomUUID(),
|
||||||
|
// user_id: authData.user.id,
|
||||||
|
// plaid_id: tx.transaction_id,
|
||||||
|
// account_id: tx.account_id,
|
||||||
|
// name: tx.name,
|
||||||
|
// amount: tx.amount as any,
|
||||||
|
// datetime: tx.datetime
|
||||||
|
// ? new Date(tx.datetime)
|
||||||
|
// : new Date(tx.date),
|
||||||
|
// authorized_datetime: tx.authorized_datetime
|
||||||
|
// ? new Date(tx.authorized_datetime)
|
||||||
|
// : undefined,
|
||||||
|
// json: JSON.stringify(tx),
|
||||||
|
// }) satisfies InferInsertModel<typeof transaction>,
|
||||||
|
// );
|
||||||
|
//
|
||||||
|
// await db
|
||||||
|
// .insert(transaction)
|
||||||
|
// .values(transactions)
|
||||||
|
// .onConflictDoNothing({
|
||||||
|
// target: transaction.plaid_id,
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// const txReplacingPendingIds = data.transactions
|
||||||
|
// .filter((t) => t.pending_transaction_id)
|
||||||
|
// .map((t) => t.pending_transaction_id!);
|
||||||
|
//
|
||||||
|
// await db
|
||||||
|
// .delete(transaction)
|
||||||
|
// .where(inArray(transaction.plaid_id, txReplacingPendingIds));
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
//
|
||||||
|
// async updateBalences() {
|
||||||
|
// isLoggedIn(authData);
|
||||||
|
// const accounts = await db.query.plaidAccessTokens.findMany({
|
||||||
|
// where: eq(plaidAccessTokens.userId, authData.user.id),
|
||||||
|
// });
|
||||||
|
// if (accounts.length == 0) {
|
||||||
|
// console.error("No accounts");
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// for (const account of accounts) {
|
||||||
|
// const { data } = await plaidClient.accountsBalanceGet({
|
||||||
|
// access_token: account.token,
|
||||||
|
// });
|
||||||
|
// await db
|
||||||
|
// .insert(balance)
|
||||||
|
// .values(
|
||||||
|
// data.accounts.map((bal) => ({
|
||||||
|
// id: randomUUID(),
|
||||||
|
// user_id: authData.user.id,
|
||||||
|
// plaid_id: bal.account_id,
|
||||||
|
// avaliable: bal.balances.available as any,
|
||||||
|
// current: bal.balances.current as any,
|
||||||
|
// name: bal.name,
|
||||||
|
// tokenId: account.id,
|
||||||
|
// })),
|
||||||
|
// )
|
||||||
|
// .onConflictDoUpdate({
|
||||||
|
// target: balance.plaid_id,
|
||||||
|
// set: {
|
||||||
|
// current: sql.raw(`excluded.${balance.current.name}`),
|
||||||
|
// avaliable: sql.raw(`excluded.${balance.avaliable.name}`),
|
||||||
|
// },
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
},
|
||||||
} as const satisfies Mutators;
|
} as const satisfies Mutators;
|
||||||
}
|
};
|
||||||
|
|
||||||
const zero = getHono()
|
const zero = getHono()
|
||||||
.post("/mutate", async (c) => {
|
.post("/mutate", async (c) => {
|
||||||
|
|||||||
@@ -38,7 +38,8 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"expo-sqlite"
|
"expo-sqlite",
|
||||||
|
"expo-secure-store"
|
||||||
],
|
],
|
||||||
"experiments": {
|
"experiments": {
|
||||||
"typedRoutes": true,
|
"typedRoutes": true,
|
||||||
|
|||||||
@@ -5,13 +5,15 @@ import { authClient } from "@/lib/auth-client";
|
|||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const { route: initalRoute } = useLocalSearchParams<{ route: string[] }>();
|
const { route: initalRoute } = useLocalSearchParams<{ route: string[] }>();
|
||||||
const [route, setRoute] = useState(initalRoute ? "/" + initalRoute.join("/") : "/");
|
const [route, setRoute] = useState(
|
||||||
|
initalRoute ? "/" + initalRoute.join("/") : "/",
|
||||||
|
);
|
||||||
|
|
||||||
const { data } = authClient.useSession();
|
const { data } = authClient.useSession();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handler = () => {
|
const handler = () => {
|
||||||
const newRoute = window.location.pathname.slice(1);
|
const newRoute = window.location.pathname.slice(1) + "/";
|
||||||
setRoute(newRoute);
|
setRoute(newRoute);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,23 @@
|
|||||||
import { Stack } from 'expo-router';
|
import { Stack } from "expo-router";
|
||||||
import 'react-native-reanimated';
|
import "react-native-reanimated";
|
||||||
|
|
||||||
import { authClient } from '@/lib/auth-client';
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { ZeroProvider } from '@rocicorp/zero/react';
|
import { ZeroProvider } from "@rocicorp/zero/react";
|
||||||
import { useMemo } from 'react';
|
import { useMemo } from "react";
|
||||||
import { authDataSchema } from '@money/shared/auth';
|
import { authDataSchema } from "@money/shared/auth";
|
||||||
import { Platform } from 'react-native';
|
import { Platform } from "react-native";
|
||||||
import type { ZeroOptions } from '@rocicorp/zero';
|
import type { ZeroOptions } from "@rocicorp/zero";
|
||||||
import { schema, type Schema, createMutators, type Mutators, BASE_URL } from '@money/shared';
|
import {
|
||||||
|
schema,
|
||||||
|
type Schema,
|
||||||
|
createMutators,
|
||||||
|
type Mutators,
|
||||||
|
BASE_URL,
|
||||||
|
} from "@money/shared";
|
||||||
import { expoSQLiteStoreProvider } from "@rocicorp/zero/react-native";
|
import { expoSQLiteStoreProvider } from "@rocicorp/zero/react-native";
|
||||||
|
|
||||||
export const unstable_settings = {
|
export const unstable_settings = {
|
||||||
anchor: 'index',
|
anchor: "index",
|
||||||
};
|
};
|
||||||
|
|
||||||
const kvStore = Platform.OS === "web" ? undefined : expoSQLiteStoreProvider();
|
const kvStore = Platform.OS === "web" ? undefined : expoSQLiteStoreProvider();
|
||||||
@@ -25,14 +31,17 @@ export default function RootLayout() {
|
|||||||
}, [session]);
|
}, [session]);
|
||||||
|
|
||||||
const cookie = useMemo(() => {
|
const cookie = useMemo(() => {
|
||||||
return Platform.OS == 'web' ? undefined : authClient.getCookie();
|
return Platform.OS == "web" ? undefined : authClient.getCookie();
|
||||||
}, [session, isPending]);
|
}, [session, isPending]);
|
||||||
|
|
||||||
const zeroProps = useMemo(() => {
|
const zeroProps = useMemo(() => {
|
||||||
return {
|
return {
|
||||||
storageKey: 'money',
|
storageKey: "money",
|
||||||
kvStore,
|
kvStore,
|
||||||
server: process.env.NODE_ENV == 'production' ? 'https://zero.koon.us' : `${BASE_URL}:4848`,
|
server:
|
||||||
|
process.env.NODE_ENV == "production"
|
||||||
|
? "https://zero.koon.us"
|
||||||
|
: `${BASE_URL}:4848`,
|
||||||
userID: authData?.user.id ?? "anon",
|
userID: authData?.user.id ?? "anon",
|
||||||
schema,
|
schema,
|
||||||
mutators: createMutators(authData),
|
mutators: createMutators(authData),
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useEffect } from "react";
|
|||||||
import { Text } from "react-native";
|
import { Text } from "react-native";
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const { code } = useLocalSearchParams<{code: string }>();
|
const { code } = useLocalSearchParams<{ code: string }>();
|
||||||
const { isPending, data } = authClient.useSession();
|
const { isPending, data } = authClient.useSession();
|
||||||
if (isPending) return <Text>Loading...</Text>;
|
if (isPending) return <Text>Loading...</Text>;
|
||||||
if (!isPending && !data) return <Text>Please log in</Text>;
|
if (!isPending && !data) return <Text>Please log in</Text>;
|
||||||
@@ -13,11 +13,7 @@ export default function Page() {
|
|||||||
authClient.device.approve({
|
authClient.device.approve({
|
||||||
userCode: code,
|
userCode: code,
|
||||||
});
|
});
|
||||||
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return <Text>
|
return <Text>Approving: {code}</Text>;
|
||||||
Approving: {code}
|
|
||||||
</Text>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ export default function Auth() {
|
|||||||
const onLogin = () => {
|
const onLogin = () => {
|
||||||
authClient.signIn.oauth2({
|
authClient.signIn.oauth2({
|
||||||
providerId: "koon-family",
|
providerId: "koon-family",
|
||||||
callbackURL: process.env.NODE_ENV == 'production' ? 'https://money.koon.us' : `${BASE_URL}:8081`,
|
callbackURL:
|
||||||
|
process.env.NODE_ENV == "production"
|
||||||
|
? "https://money.koon.us"
|
||||||
|
: `${BASE_URL}:8081`,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -14,5 +17,5 @@ export default function Auth() {
|
|||||||
<View>
|
<View>
|
||||||
<Button onPress={onLogin} title="Login with Koon Family" />
|
<Button onPress={onLogin} title="Login with Koon Family" />
|
||||||
</View>
|
</View>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
import { authClient } from '@/lib/auth-client';
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { RefreshControl, ScrollView, StatusBar, Text, View } from 'react-native';
|
import {
|
||||||
|
RefreshControl,
|
||||||
|
ScrollView,
|
||||||
|
StatusBar,
|
||||||
|
Text,
|
||||||
|
View,
|
||||||
|
} from "react-native";
|
||||||
import { useQuery, useZero } from "@rocicorp/zero/react";
|
import { useQuery, useZero } from "@rocicorp/zero/react";
|
||||||
import { queries, type Mutators, type Schema } from '@money/shared';
|
import { queries, type Mutators, type Schema } from "@money/shared";
|
||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
|
|
||||||
export default function HomeScreen() {
|
export default function HomeScreen() {
|
||||||
const { data: session } = authClient.useSession();
|
const { data: session } = authClient.useSession();
|
||||||
@@ -20,16 +26,43 @@ export default function HomeScreen() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<StatusBar barStyle="dark-content" />
|
<StatusBar barStyle="dark-content" />
|
||||||
<ScrollView contentContainerStyle={{ paddingTop: StatusBar.currentHeight, flexGrow: 1 }} refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />} style={{ paddingHorizontal: 10 }}>
|
<ScrollView
|
||||||
{balances.map(balance => <Balance key={balance.id} balance={balance} />)}
|
contentContainerStyle={{
|
||||||
|
paddingTop: StatusBar.currentHeight,
|
||||||
|
flexGrow: 1,
|
||||||
|
}}
|
||||||
|
refreshControl={
|
||||||
|
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
|
||||||
|
}
|
||||||
|
style={{ paddingHorizontal: 10 }}
|
||||||
|
>
|
||||||
|
{balances.map((balance) => (
|
||||||
|
<Balance key={balance.id} balance={balance} />
|
||||||
|
))}
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Balance({ balance }: { balance: { name: string, current: number, avaliable: number } }) {
|
function Balance({
|
||||||
return <View style={{ backgroundColor: "#eee", borderColor: "#ddd", borderWidth: 1, marginBottom: 10, borderRadius: 10 }}>
|
balance,
|
||||||
<Text style={{ fontSize: 15, textAlign: "center" }}>{balance.name}</Text>
|
}: {
|
||||||
<Text style={{ fontSize: 30, textAlign: "center" }}>{balance.current}</Text>
|
balance: { name: string; current: number; avaliable: number };
|
||||||
</View>
|
}) {
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
backgroundColor: "#eee",
|
||||||
|
borderColor: "#ddd",
|
||||||
|
borderWidth: 1,
|
||||||
|
marginBottom: 10,
|
||||||
|
borderRadius: 10,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text style={{ fontSize: 15, textAlign: "center" }}>{balance.name}</Text>
|
||||||
|
<Text style={{ fontSize: 30, textAlign: "center" }}>
|
||||||
|
{balance.current}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// https://docs.expo.dev/guides/using-eslint/
|
// https://docs.expo.dev/guides/using-eslint/
|
||||||
const { defineConfig } = require('eslint/config');
|
const { defineConfig } = require("eslint/config");
|
||||||
const expoConfig = require('eslint-config-expo/flat');
|
const expoConfig = require("eslint-config-expo/flat");
|
||||||
|
|
||||||
module.exports = defineConfig([
|
module.exports = defineConfig([
|
||||||
expoConfig,
|
expoConfig,
|
||||||
{
|
{
|
||||||
ignores: ['dist/*'],
|
ignores: ["dist/*"],
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import { createAuthClient } from "better-auth/react";
|
import { createAuthClient } from "better-auth/react";
|
||||||
import { deviceAuthorizationClient, genericOAuthClient } from "better-auth/client/plugins";
|
import {
|
||||||
|
deviceAuthorizationClient,
|
||||||
|
genericOAuthClient,
|
||||||
|
} from "better-auth/client/plugins";
|
||||||
import { expoClient } from "@better-auth/expo/client";
|
import { expoClient } from "@better-auth/expo/client";
|
||||||
import * as SecureStore from "expo-secure-store";
|
import * as SecureStore from "expo-secure-store";
|
||||||
import { BASE_URL } from "@money/shared";
|
import { BASE_URL } from "@money/shared";
|
||||||
|
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: process.env.NODE_ENV == 'production' ? 'https://money-api.koon.us' : `${BASE_URL}:3000`,
|
baseURL:
|
||||||
|
process.env.NODE_ENV == "production"
|
||||||
|
? "https://money-api.koon.us"
|
||||||
|
: `${BASE_URL}:3000`,
|
||||||
plugins: [
|
plugins: [
|
||||||
expoClient({
|
expoClient({
|
||||||
scheme: "money",
|
scheme: "money",
|
||||||
@@ -14,5 +20,5 @@ export const authClient = createAuthClient({
|
|||||||
}),
|
}),
|
||||||
genericOAuthClient(),
|
genericOAuthClient(),
|
||||||
deviceAuthorizationClient(),
|
deviceAuthorizationClient(),
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const { getDefaultConfig } = require("expo/metro-config");
|
const { getDefaultConfig } = require("expo/metro-config");
|
||||||
|
|
||||||
const config = getDefaultConfig(__dirname)
|
const config = getDefaultConfig(__dirname);
|
||||||
|
|
||||||
// Add wasm asset support
|
// Add wasm asset support
|
||||||
config.resolver.assetExts.push("wasm");
|
config.resolver.assetExts.push("wasm");
|
||||||
|
|||||||
@@ -10,14 +10,14 @@
|
|||||||
"web": "expo start --web",
|
"web": "expo start --web",
|
||||||
"build": "expo export --platform web",
|
"build": "expo export --platform web",
|
||||||
"lint": "expo lint",
|
"lint": "expo lint",
|
||||||
"db:migrate": "dotenv -- pnpm run --dir=shared db:migrate",
|
"db:migrate": "dotenv -- bun run --dir=shared db:migrate",
|
||||||
"db:gen": "dotenv -- pnpm run --dir=shared generate:zero"
|
"db:gen": "dotenv -- bun run --dir=shared generate:zero"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@better-auth/expo": "^1.3.27",
|
"@better-auth/expo": "^1.3.27",
|
||||||
"@expo/vector-icons": "^15.0.2",
|
"@expo/vector-icons": "^15.0.2",
|
||||||
"@money/shared": "workspace:*",
|
"@money/shared": "*",
|
||||||
"@money/ui": "workspace:*",
|
"@money/ui": "*",
|
||||||
"@react-navigation/bottom-tabs": "^7.4.0",
|
"@react-navigation/bottom-tabs": "^7.4.0",
|
||||||
"@react-navigation/elements": "^2.6.3",
|
"@react-navigation/elements": "^2.6.3",
|
||||||
"@react-navigation/native": "^7.1.8",
|
"@react-navigation/native": "^7.1.8",
|
||||||
@@ -31,7 +31,9 @@
|
|||||||
"expo-haptics": "~15.0.7",
|
"expo-haptics": "~15.0.7",
|
||||||
"expo-image": "~3.0.9",
|
"expo-image": "~3.0.9",
|
||||||
"expo-linking": "~8.0.8",
|
"expo-linking": "~8.0.8",
|
||||||
|
"expo-network": "~8.0.8",
|
||||||
"expo-router": "~6.0.11",
|
"expo-router": "~6.0.11",
|
||||||
|
"expo-secure-store": "~15.0.8",
|
||||||
"expo-splash-screen": "~31.0.10",
|
"expo-splash-screen": "~31.0.10",
|
||||||
"expo-sqlite": "~16.0.8",
|
"expo-sqlite": "~16.0.8",
|
||||||
"expo-status-bar": "~3.0.8",
|
"expo-status-bar": "~3.0.8",
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ import path from "path";
|
|||||||
const aliasPlugin = {
|
const aliasPlugin = {
|
||||||
name: "alias-react-native",
|
name: "alias-react-native",
|
||||||
setup(build) {
|
setup(build) {
|
||||||
build.onResolve({ filter: /^react-native$/ }, args => {
|
build.onResolve({ filter: /^react-native$/ }, (args) => {
|
||||||
return {
|
return {
|
||||||
path: path.resolve(__dirname, "../../packages/react-native-opentui/index.tsx"),
|
path: path.resolve(
|
||||||
|
__dirname,
|
||||||
|
"../../packages/react-native-opentui/index.tsx",
|
||||||
|
),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -16,9 +19,9 @@ const aliasPlugin = {
|
|||||||
// Build configuration
|
// Build configuration
|
||||||
await esbuild.build({
|
await esbuild.build({
|
||||||
entryPoints: ["src/index.tsx"], // your app entry
|
entryPoints: ["src/index.tsx"], // your app entry
|
||||||
bundle: true, // inline all dependencies (ui included)
|
bundle: true, // inline all dependencies (ui included)
|
||||||
platform: "node", // Node/Bun target
|
platform: "node", // Node/Bun target
|
||||||
format: "esm", // keep ESM for top-level await
|
format: "esm", // keep ESM for top-level await
|
||||||
outfile: "dist/index.js",
|
outfile: "dist/index.js",
|
||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
plugins: [aliasPlugin],
|
plugins: [aliasPlugin],
|
||||||
|
|||||||
@@ -4,9 +4,5 @@ import { deviceAuthorizationClient } from "better-auth/client/plugins";
|
|||||||
|
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: config.apiUrl,
|
baseURL: config.apiUrl,
|
||||||
plugins: [
|
plugins: [deviceAuthorizationClient()],
|
||||||
deviceAuthorizationClient(),
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,39 +1,70 @@
|
|||||||
import { Context, Data, Effect, Layer, Schema, Console, Schedule, Ref, Duration } from "effect";
|
import {
|
||||||
|
Context,
|
||||||
|
Data,
|
||||||
|
Effect,
|
||||||
|
Layer,
|
||||||
|
Schema,
|
||||||
|
Console,
|
||||||
|
Schedule,
|
||||||
|
Ref,
|
||||||
|
Duration,
|
||||||
|
} from "effect";
|
||||||
import { FileSystem } from "@effect/platform";
|
import { FileSystem } from "@effect/platform";
|
||||||
import { config } from "./config";
|
import { config } from "./config";
|
||||||
import { AuthState } from "./schema";
|
import { AuthState } from "./schema";
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
import type { BetterFetchResponse } from "@better-fetch/fetch";
|
import type { BetterFetchResponse } from "@better-fetch/fetch";
|
||||||
|
|
||||||
class AuthClientUnknownError extends Data.TaggedError("AuthClientUnknownError") {};
|
class AuthClientUnknownError extends Data.TaggedError(
|
||||||
class AuthClientExpiredToken extends Data.TaggedError("AuthClientExpiredToken") {};
|
"AuthClientUnknownError",
|
||||||
class AuthClientNoData extends Data.TaggedError("AuthClientNoData") {};
|
) {}
|
||||||
class AuthClientFetchError extends Data.TaggedError("AuthClientFetchError")<{ message: string, }> {};
|
class AuthClientExpiredToken extends Data.TaggedError(
|
||||||
|
"AuthClientExpiredToken",
|
||||||
|
) {}
|
||||||
|
class AuthClientNoData extends Data.TaggedError("AuthClientNoData") {}
|
||||||
|
class AuthClientFetchError extends Data.TaggedError("AuthClientFetchError")<{
|
||||||
|
message: string;
|
||||||
|
}> {}
|
||||||
class AuthClientError<T> extends Data.TaggedError("AuthClientError")<{
|
class AuthClientError<T> extends Data.TaggedError("AuthClientError")<{
|
||||||
error: T,
|
error: T;
|
||||||
}> {};
|
}> {}
|
||||||
|
|
||||||
type ErrorType<E> = { [key in keyof ((E extends Record<string, any> ? E : {
|
type ErrorType<E> = {
|
||||||
message?: string;
|
[key in keyof ((E extends Record<string, any>
|
||||||
}) & {
|
? E
|
||||||
|
: {
|
||||||
|
message?: string;
|
||||||
|
}) & {
|
||||||
status: number;
|
status: number;
|
||||||
statusText: string;
|
statusText: string;
|
||||||
})]: ((E extends Record<string, any> ? E : {
|
})]: ((E extends Record<string, any>
|
||||||
message?: string;
|
? E
|
||||||
}) & {
|
: {
|
||||||
|
message?: string;
|
||||||
|
}) & {
|
||||||
status: number;
|
status: number;
|
||||||
statusText: string;
|
statusText: string;
|
||||||
})[key]; };
|
})[key];
|
||||||
|
};
|
||||||
|
|
||||||
export class AuthClient extends Context.Tag("AuthClient")<AuthClient, AuthClientImpl>() {};
|
export class AuthClient extends Context.Tag("AuthClient")<
|
||||||
|
AuthClient,
|
||||||
|
AuthClientImpl
|
||||||
|
>() {}
|
||||||
|
|
||||||
export interface AuthClientImpl {
|
export interface AuthClientImpl {
|
||||||
use: <T, E>(
|
use: <T, E>(
|
||||||
fn: (client: typeof authClient) => Promise<BetterFetchResponse<T, E>>,
|
fn: (client: typeof authClient) => Promise<BetterFetchResponse<T, E>>,
|
||||||
) => Effect.Effect<T, AuthClientError<ErrorType<E>> | AuthClientFetchError | AuthClientUnknownError | AuthClientNoData, never>
|
) => Effect.Effect<
|
||||||
|
T,
|
||||||
|
| AuthClientError<ErrorType<E>>
|
||||||
|
| AuthClientFetchError
|
||||||
|
| AuthClientUnknownError
|
||||||
|
| AuthClientNoData,
|
||||||
|
never
|
||||||
|
>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const make = () =>
|
export const make = () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
return AuthClient.of({
|
return AuthClient.of({
|
||||||
@@ -41,11 +72,13 @@ export const make = () =>
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const { data, error } = yield* Effect.tryPromise({
|
const { data, error } = yield* Effect.tryPromise({
|
||||||
try: () => fn(authClient),
|
try: () => fn(authClient),
|
||||||
catch: (error) => error instanceof Error
|
catch: (error) =>
|
||||||
? new AuthClientFetchError({ message: error.message })
|
error instanceof Error
|
||||||
: new AuthClientUnknownError()
|
? new AuthClientFetchError({ message: error.message })
|
||||||
|
: new AuthClientUnknownError(),
|
||||||
});
|
});
|
||||||
if (error != null) return yield* Effect.fail(new AuthClientError({ error }));
|
if (error != null)
|
||||||
|
return yield* Effect.fail(new AuthClientError({ error }));
|
||||||
if (data == null) return yield* Effect.fail(new AuthClientNoData());
|
if (data == null) return yield* Effect.fail(new AuthClientNoData());
|
||||||
return data;
|
return data;
|
||||||
}),
|
}),
|
||||||
@@ -54,76 +87,80 @@ export const make = () =>
|
|||||||
|
|
||||||
export const AuthClientLayer = Layer.scoped(AuthClient, make());
|
export const AuthClientLayer = Layer.scoped(AuthClient, make());
|
||||||
|
|
||||||
const pollToken = ({ device_code }: { device_code: string }) => Effect.gen(function* () {
|
const pollToken = ({ device_code }: { device_code: string }) =>
|
||||||
const auth = yield* AuthClient;
|
Effect.gen(function* () {
|
||||||
const intervalRef = yield* Ref.make(5);
|
const auth = yield* AuthClient;
|
||||||
|
const intervalRef = yield* Ref.make(5);
|
||||||
|
|
||||||
const tokenEffect = auth.use(client => {
|
const tokenEffect = auth.use((client) => {
|
||||||
Console.debug("Fetching");
|
Console.debug("Fetching");
|
||||||
|
|
||||||
return client.device.token({
|
return client.device.token({
|
||||||
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
||||||
device_code,
|
device_code,
|
||||||
client_id: config.authClientId,
|
client_id: config.authClientId,
|
||||||
fetchOptions: { headers: { "user-agent": config.authClientUserAgent } },
|
fetchOptions: { headers: { "user-agent": config.authClientUserAgent } },
|
||||||
})
|
});
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
return yield* tokenEffect
|
return yield* tokenEffect.pipe(
|
||||||
.pipe(
|
Effect.tapError((error) =>
|
||||||
Effect.tapError(error =>
|
|
||||||
error._tag == "AuthClientError" && error.error.error == "slow_down"
|
error._tag == "AuthClientError" && error.error.error == "slow_down"
|
||||||
? Ref.update(intervalRef, current => {
|
? Ref.update(intervalRef, (current) => {
|
||||||
Console.debug("updating delay to ", current + 5);
|
Console.debug("updating delay to ", current + 5);
|
||||||
return current + 5
|
return current + 5;
|
||||||
})
|
})
|
||||||
: Effect.void
|
: Effect.void,
|
||||||
),
|
),
|
||||||
Effect.retry({
|
Effect.retry({
|
||||||
schedule: Schedule.addDelayEffect(
|
schedule: Schedule.addDelayEffect(
|
||||||
Schedule.recurWhile<Effect.Effect.Error<typeof tokenEffect>>(error =>
|
Schedule.recurWhile<Effect.Effect.Error<typeof tokenEffect>>(
|
||||||
error._tag == "AuthClientError" &&
|
(error) =>
|
||||||
(error.error.error == "authorization_pending" || error.error.error == "slow_down")
|
error._tag == "AuthClientError" &&
|
||||||
|
(error.error.error == "authorization_pending" ||
|
||||||
|
error.error.error == "slow_down"),
|
||||||
),
|
),
|
||||||
() => Ref.get(intervalRef).pipe(Effect.map(Duration.seconds))
|
() => Ref.get(intervalRef).pipe(Effect.map(Duration.seconds)),
|
||||||
)
|
),
|
||||||
})
|
}),
|
||||||
|
|
||||||
);
|
);
|
||||||
|
});
|
||||||
});
|
|
||||||
|
|
||||||
const getFromFromDisk = Effect.gen(function* () {
|
const getFromFromDisk = Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const content = yield* fs.readFileString(config.authPath);
|
const content = yield* fs.readFileString(config.authPath);
|
||||||
const auth = yield* Schema.decode(Schema.parseJson(AuthState))(content);
|
const auth = yield* Schema.decode(Schema.parseJson(AuthState))(content);
|
||||||
if (auth.session.expiresAt < new Date()) yield* Effect.fail(new AuthClientExpiredToken());
|
if (auth.session.expiresAt < new Date())
|
||||||
|
yield* Effect.fail(new AuthClientExpiredToken());
|
||||||
return auth;
|
return auth;
|
||||||
});
|
});
|
||||||
|
|
||||||
const requestAuth = Effect.gen(function* () {
|
const requestAuth = Effect.gen(function* () {
|
||||||
const auth = yield* AuthClient;
|
const auth = yield* AuthClient;
|
||||||
const { device_code, user_code } = yield* auth.use(client => client.device.code({
|
const { device_code, user_code } = yield* auth.use((client) =>
|
||||||
client_id: config.authClientId,
|
client.device.code({
|
||||||
scope: "openid profile email",
|
client_id: config.authClientId,
|
||||||
}));
|
scope: "openid profile email",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
console.log(`Please use the code: ${user_code}`);
|
console.log(`Please use the code: ${user_code}`);
|
||||||
|
|
||||||
const { access_token } = yield* pollToken({ device_code });
|
const { access_token } = yield* pollToken({ device_code });
|
||||||
|
|
||||||
const sessionData = yield* auth.use(client => client.getSession({
|
const sessionData = yield* auth.use((client) =>
|
||||||
fetchOptions: {
|
client.getSession({
|
||||||
auth: {
|
fetchOptions: {
|
||||||
type: "Bearer",
|
auth: {
|
||||||
token: access_token,
|
type: "Bearer",
|
||||||
}
|
token: access_token,
|
||||||
}
|
},
|
||||||
}));
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
if (sessionData == null) return yield* Effect.fail(new AuthClientNoData());
|
if (sessionData == null) return yield* Effect.fail(new AuthClientNoData());
|
||||||
|
|
||||||
const result = yield* Schema.decodeUnknown(AuthState)(sessionData)
|
const result = yield* Schema.decodeUnknown(AuthState)(sessionData);
|
||||||
|
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
yield* fs.writeFileString(config.authPath, JSON.stringify(result));
|
yield* fs.writeFileString(config.authPath, JSON.stringify(result));
|
||||||
@@ -134,33 +171,51 @@ const requestAuth = Effect.gen(function* () {
|
|||||||
export const getAuth = Effect.gen(function* () {
|
export const getAuth = Effect.gen(function* () {
|
||||||
return yield* getFromFromDisk.pipe(
|
return yield* getFromFromDisk.pipe(
|
||||||
Effect.catchAll(() => requestAuth),
|
Effect.catchAll(() => requestAuth),
|
||||||
Effect.catchTag("AuthClientFetchError", (err) => Effect.gen(function* () {
|
Effect.catchTag("AuthClientFetchError", (err) =>
|
||||||
yield* Console.error("Authentication failed: " + err.message);
|
Effect.gen(function* () {
|
||||||
process.exit(1);
|
yield* Console.error("Authentication failed: " + err.message);
|
||||||
})),
|
process.exit(1);
|
||||||
Effect.catchTag("AuthClientNoData", () => Effect.gen(function* () {
|
}),
|
||||||
yield* Console.error("Authentication failed: No error and no data was given by the auth server.");
|
),
|
||||||
process.exit(1);
|
Effect.catchTag("AuthClientNoData", () =>
|
||||||
})),
|
Effect.gen(function* () {
|
||||||
Effect.catchTag("ParseError", (err) => Effect.gen(function* () {
|
yield* Console.error(
|
||||||
yield* Console.error("Authentication failed: Auth data failed: " + err.toString());
|
"Authentication failed: No error and no data was given by the auth server.",
|
||||||
process.exit(1);
|
);
|
||||||
})),
|
process.exit(1);
|
||||||
Effect.catchTag("BadArgument", () => Effect.gen(function* () {
|
}),
|
||||||
yield* Console.error("Authentication failed: Bad argument");
|
),
|
||||||
process.exit(1);
|
Effect.catchTag("ParseError", (err) =>
|
||||||
})),
|
Effect.gen(function* () {
|
||||||
Effect.catchTag("SystemError", () => Effect.gen(function* () {
|
yield* Console.error(
|
||||||
yield* Console.error("Authentication failed: System error");
|
"Authentication failed: Auth data failed: " + err.toString(),
|
||||||
process.exit(1);
|
);
|
||||||
})),
|
process.exit(1);
|
||||||
Effect.catchTag("AuthClientError", ({ error }) => Effect.gen(function* () {
|
}),
|
||||||
yield* Console.error("Authentication error: " + error.statusText);
|
),
|
||||||
process.exit(1);
|
Effect.catchTag("BadArgument", () =>
|
||||||
})),
|
Effect.gen(function* () {
|
||||||
Effect.catchTag("AuthClientUnknownError", () => Effect.gen(function* () {
|
yield* Console.error("Authentication failed: Bad argument");
|
||||||
yield* Console.error("Unknown authentication error");
|
process.exit(1);
|
||||||
process.exit(1);
|
}),
|
||||||
})),
|
),
|
||||||
|
Effect.catchTag("SystemError", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* Console.error("Authentication failed: System error");
|
||||||
|
process.exit(1);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.catchTag("AuthClientError", ({ error }) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* Console.error("Authentication error: " + error.statusText);
|
||||||
|
process.exit(1);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.catchTag("AuthClientUnknownError", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* Console.error("Unknown authentication error");
|
||||||
|
process.exit(1);
|
||||||
|
}),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,5 +10,5 @@ export const config = {
|
|||||||
authClientId: "koon-family",
|
authClientId: "koon-family",
|
||||||
authClientUserAgent: "CLI",
|
authClientUserAgent: "CLI",
|
||||||
zeroUrl: "http://laptop:4848",
|
zeroUrl: "http://laptop:4848",
|
||||||
apiUrl: "http://laptop:3000"
|
apiUrl: "http://laptop:3000",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { createCliRenderer } from "@opentui/core";
|
import { createCliRenderer } from "@opentui/core";
|
||||||
import { createRoot, useKeyboard } from "@opentui/react";
|
import { createRoot, useKeyboard, useRenderer } from "@opentui/react";
|
||||||
import { App, type Route } from "@money/ui";
|
import { App, type Route } from "@money/ui";
|
||||||
import { ZeroProvider } from "@rocicorp/zero/react";
|
import { ZeroProvider } from "@rocicorp/zero/react";
|
||||||
import { schema } from '@money/shared';
|
import { schema, createMutators } from "@money/shared";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { AuthClientLayer, getAuth } from "./auth";
|
import { AuthClientLayer, getAuth } from "./auth";
|
||||||
import { Effect } from "effect";
|
import { Effect } from "effect";
|
||||||
@@ -13,29 +13,34 @@ import { config } from "./config";
|
|||||||
|
|
||||||
function Main({ auth }: { auth: AuthData }) {
|
function Main({ auth }: { auth: AuthData }) {
|
||||||
const [route, setRoute] = useState<Route>("/");
|
const [route, setRoute] = useState<Route>("/");
|
||||||
|
const renderer = useRenderer();
|
||||||
|
|
||||||
useKeyboard(key => {
|
useKeyboard((key) => {
|
||||||
if (key.name == "c" && key.ctrl) process.exit(0);
|
if (key.name == "c" && key.ctrl) process.exit(0);
|
||||||
|
if (key.name == "i" && key.meta) renderer.console.toggle();
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return <App auth={auth} route={route} setRoute={setRoute} />;
|
||||||
<ZeroProvider {...{ userID: auth.user.id, auth: auth.session.token, server: config.zeroUrl, schema, kvStore }}>
|
|
||||||
<App
|
|
||||||
auth={auth}
|
|
||||||
route={route}
|
|
||||||
setRoute={setRoute}
|
|
||||||
/>
|
|
||||||
</ZeroProvider>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const auth = await Effect.runPromise(
|
const auth = await Effect.runPromise(
|
||||||
getAuth.pipe(
|
getAuth.pipe(
|
||||||
Effect.provide(BunContext.layer),
|
Effect.provide(BunContext.layer),
|
||||||
Effect.provide(AuthClientLayer),
|
Effect.provide(AuthClientLayer),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
const renderer = await createCliRenderer({ exitOnCtrlC: false });
|
const renderer = await createCliRenderer({ exitOnCtrlC: false });
|
||||||
createRoot(renderer).render(<Main auth={auth} />);
|
createRoot(renderer).render(
|
||||||
|
<ZeroProvider
|
||||||
|
{...{
|
||||||
|
userID: auth.user.id,
|
||||||
|
auth: auth.session.token,
|
||||||
|
server: config.zeroUrl,
|
||||||
|
schema,
|
||||||
|
mutators: createMutators(auth),
|
||||||
|
kvStore,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Main auth={auth} />
|
||||||
|
</ZeroProvider>,
|
||||||
|
);
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema } from "effect";
|
||||||
|
|
||||||
const DateFromDateOrString = Schema.Union(Schema.DateFromString, Schema.DateFromSelf);
|
const DateFromDateOrString = Schema.Union(
|
||||||
|
Schema.DateFromString,
|
||||||
|
Schema.DateFromSelf,
|
||||||
|
);
|
||||||
|
|
||||||
const SessionSchema = Schema.Struct({
|
const SessionSchema = Schema.Struct({
|
||||||
expiresAt: DateFromDateOrString,
|
expiresAt: DateFromDateOrString,
|
||||||
@@ -23,11 +26,9 @@ const UserSchema = Schema.Struct({
|
|||||||
id: Schema.String,
|
id: Schema.String,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
export const AuthState = Schema.Struct({
|
export const AuthState = Schema.Struct({
|
||||||
session: SessionSchema,
|
session: SessionSchema,
|
||||||
user: UserSchema,
|
user: UserSchema,
|
||||||
});
|
});
|
||||||
|
|
||||||
export type AuthData = typeof AuthState.Type;
|
export type AuthData = typeof AuthState.Type;
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ async function loadFile(name: string): Promise<Map<string, ReadonlyJSONValue>> {
|
|||||||
const buf = await fs.readFile(filePath, "utf8");
|
const buf = await fs.readFile(filePath, "utf8");
|
||||||
const obj = JSON.parse(buf) as Record<string, ReadonlyJSONValue>;
|
const obj = JSON.parse(buf) as Record<string, ReadonlyJSONValue>;
|
||||||
const frozen = Object.fromEntries(
|
const frozen = Object.fromEntries(
|
||||||
Object.entries(obj).map(([k, v]) => [k, deepFreeze(v)])
|
Object.entries(obj).map(([k, v]) => [k, deepFreeze(v)]),
|
||||||
);
|
);
|
||||||
return new Map(Object.entries(frozen));
|
return new Map(Object.entries(frozen));
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -73,7 +73,9 @@ export const kvStore: StoreProvider = {
|
|||||||
closed: txClosed,
|
closed: txClosed,
|
||||||
async has(key: string) {
|
async has(key: string) {
|
||||||
if (txClosed) throw new Error("transaction closed");
|
if (txClosed) throw new Error("transaction closed");
|
||||||
return staging.has(key) ? staging.get(key) !== undefined : data.has(key);
|
return staging.has(key)
|
||||||
|
? staging.get(key) !== undefined
|
||||||
|
: data.has(key);
|
||||||
},
|
},
|
||||||
async get(key: string) {
|
async get(key: string) {
|
||||||
if (txClosed) throw new Error("transaction closed");
|
if (txClosed) throw new Error("transaction closed");
|
||||||
|
|||||||
@@ -22,5 +22,3 @@ export function QR(value: string): string {
|
|||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
15
biome.jsonc
Normal file
15
biome.jsonc
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
|
||||||
|
"formatter": {
|
||||||
|
"enabled": true,
|
||||||
|
"indentStyle": "space"
|
||||||
|
},
|
||||||
|
"linter": {
|
||||||
|
"enabled": false
|
||||||
|
},
|
||||||
|
"vcs": {
|
||||||
|
"enabled": true,
|
||||||
|
"clientKind": "git",
|
||||||
|
"useIgnoreFile": true
|
||||||
|
}
|
||||||
|
}
|
||||||
20
package.json
20
package.json
@@ -3,16 +3,14 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "process-compose up -p 0",
|
"dev": "process-compose up -p 0",
|
||||||
"tui": "bun run --hot apps/tui/src/index.tsx"
|
"tui": "bun --filter=@money/tui run build && bun --filter=@money/tui run start",
|
||||||
|
"db:gen": "bun --filter=@money/shared db:gen",
|
||||||
|
"db:push": "bun --filter=@money/shared db:push"
|
||||||
},
|
},
|
||||||
"pnpm": {
|
"workspaces": ["apps/*", "packages/*"],
|
||||||
"onlyBuiltDependencies": [
|
"trustedDependencies": [
|
||||||
"@rocicorp/zero-sqlite3"
|
"@rocicorp/zero-sqlite3",
|
||||||
],
|
"protobufjs",
|
||||||
"ignoredBuiltDependencies": [
|
"unrs-resolver"
|
||||||
"esbuild",
|
]
|
||||||
"protobufjs",
|
|
||||||
"unrs-resolver"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ import type {
|
|||||||
PressableProps,
|
PressableProps,
|
||||||
ScrollViewProps,
|
ScrollViewProps,
|
||||||
ModalProps,
|
ModalProps,
|
||||||
|
|
||||||
StyleProp,
|
StyleProp,
|
||||||
ViewStyle,
|
ViewStyle,
|
||||||
|
|
||||||
LinkingImpl,
|
LinkingImpl,
|
||||||
|
TextInputProps,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { useTerminalDimensions } from "@opentui/react";
|
import { useTerminalDimensions } from "@opentui/react";
|
||||||
import { RGBA } from "@opentui/core";
|
import { BorderSides, RGBA } from "@opentui/core";
|
||||||
import { platform } from "node:os";
|
import { platform } from "node:os";
|
||||||
import { exec } from "node:child_process";
|
import { exec } from "node:child_process";
|
||||||
|
|
||||||
@@ -22,187 +21,284 @@ const RATIO_HEIGHT = 17;
|
|||||||
function attr<K extends keyof ViewStyle>(
|
function attr<K extends keyof ViewStyle>(
|
||||||
style: StyleProp<ViewStyle>,
|
style: StyleProp<ViewStyle>,
|
||||||
name: K,
|
name: K,
|
||||||
type: "string"
|
type: "string",
|
||||||
): Extract<ViewStyle[K], string> | undefined;
|
): Extract<ViewStyle[K], string> | undefined;
|
||||||
|
|
||||||
function attr<K extends keyof ViewStyle>(
|
function attr<K extends keyof ViewStyle>(
|
||||||
style: StyleProp<ViewStyle>,
|
style: StyleProp<ViewStyle>,
|
||||||
name: K,
|
name: K,
|
||||||
type: "number"
|
type: "number",
|
||||||
): Extract<ViewStyle[K], number> | undefined;
|
): Extract<ViewStyle[K], number> | undefined;
|
||||||
|
|
||||||
function attr<K extends keyof ViewStyle>(
|
function attr<K extends keyof ViewStyle>(
|
||||||
style: StyleProp<ViewStyle>,
|
style: StyleProp<ViewStyle>,
|
||||||
name: K,
|
name: K,
|
||||||
type: "boolean"
|
type: "boolean",
|
||||||
): Extract<ViewStyle[K], boolean> | undefined;
|
): Extract<ViewStyle[K], boolean> | undefined;
|
||||||
|
|
||||||
function attr<K extends keyof ViewStyle>(
|
function attr<K extends keyof ViewStyle>(
|
||||||
style: StyleProp<ViewStyle>,
|
style: StyleProp<ViewStyle>,
|
||||||
name: K,
|
name: K,
|
||||||
type: "string" | "number" | "boolean"
|
type: "string" | "number" | "boolean",
|
||||||
) {
|
) {
|
||||||
if (!style) return undefined;
|
if (!style) return undefined;
|
||||||
|
|
||||||
const obj: ViewStyle =
|
const obj: ViewStyle = Array.isArray(style)
|
||||||
Array.isArray(style)
|
? Object.assign({}, ...style.filter(Boolean))
|
||||||
? Object.assign({}, ...style.filter(Boolean))
|
: (style as ViewStyle);
|
||||||
: (style as ViewStyle);
|
|
||||||
|
|
||||||
const v = obj[name];
|
const v = obj[name];
|
||||||
return typeof v === type ? v : undefined;
|
return typeof v === type ? v : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function View({ children, style }: ViewProps) {
|
export function View({ children, style }: ViewProps) {
|
||||||
const bg = style &&
|
const bg =
|
||||||
'backgroundColor' in style
|
style && "backgroundColor" in style
|
||||||
? typeof style.backgroundColor == 'string'
|
? typeof style.backgroundColor == "string"
|
||||||
? style.backgroundColor.startsWith('rgba(')
|
? style.backgroundColor.startsWith("rgba(")
|
||||||
? (() => {
|
? (() => {
|
||||||
const parts = style.backgroundColor.split("(")[1].split(")")[0];
|
const parts = style.backgroundColor.split("(")[1].split(")")[0];
|
||||||
const [r, g, b, a] = parts.split(",").map(parseFloat);
|
const [r, g, b, a] = parts.split(",").map(parseFloat);
|
||||||
return RGBA.fromInts(r, g, b, a * 255);
|
return RGBA.fromInts(r, g, b, a * 255);
|
||||||
})()
|
})()
|
||||||
: style.backgroundColor
|
: style.backgroundColor
|
||||||
: undefined
|
: undefined
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
const padding = attr(style, 'padding', 'number');
|
const padding = attr(style, "padding", "number");
|
||||||
|
const paddingTop = attr(style, "paddingTop", "number");
|
||||||
|
const paddingLeft = attr(style, "paddingLeft", "number");
|
||||||
|
const paddingBottom = attr(style, "paddingBottom", "number");
|
||||||
|
const paddingRight = attr(style, "paddingRight", "number");
|
||||||
|
const gap = attr(style, "gap", "number");
|
||||||
|
|
||||||
|
const borderBottomWidth = attr(style, "borderBottomWidth", "number");
|
||||||
|
const borderTopWidth = attr(style, "borderTopWidth", "number");
|
||||||
|
const borderLeftWidth = attr(style, "borderLeftWidth", "number");
|
||||||
|
const borderRightWidth = attr(style, "borderRightWidth", "number");
|
||||||
|
|
||||||
|
const borderBottomColor = attr(style, "borderBottomColor", "string");
|
||||||
|
const borderTopColor = attr(style, "borderTopColor", "string");
|
||||||
|
const borderLeftColor = attr(style, "borderLeftColor", "string");
|
||||||
|
const borderRightColor = attr(style, "borderRightColor", "string");
|
||||||
|
|
||||||
|
const borderColor = attr(style, "borderColor", "string");
|
||||||
|
|
||||||
|
const top = attr(style, "top", "number");
|
||||||
|
|
||||||
|
const width = attr(style, "width", "number");
|
||||||
|
|
||||||
const props = {
|
const props = {
|
||||||
overflow: attr(style, 'overflow', 'string'),
|
overflow: attr(style, "overflow", "string"),
|
||||||
position: attr(style, 'position', 'string'),
|
position: attr(style, "position", "string"),
|
||||||
alignSelf: attr(style, 'alignSelf', 'string'),
|
alignSelf: attr(style, "alignSelf", "string"),
|
||||||
alignItems: attr(style, 'alignItems', 'string'),
|
alignItems: attr(style, "alignItems", "string"),
|
||||||
justifyContent: attr(style, 'justifyContent', 'string'),
|
justifyContent: attr(style, "justifyContent", "string"),
|
||||||
flexShrink: attr(style, 'flexShrink', 'number'),
|
flexShrink: attr(style, "flexShrink", "number"),
|
||||||
flexDirection: attr(style, 'flexDirection', 'string'),
|
flexDirection: attr(style, "flexDirection", "string"),
|
||||||
flexGrow: attr(style, 'flex', 'number') || attr(style, 'flexGrow', 'number'),
|
zIndex: attr(style, "zIndex", "number"),
|
||||||
|
left: attr(style, "left", "number"),
|
||||||
|
right: attr(style, "right", "number"),
|
||||||
|
bottom: attr(style, "bottom", "number"),
|
||||||
|
flexGrow:
|
||||||
|
attr(style, "flex", "number") || attr(style, "flexGrow", "number"),
|
||||||
};
|
};
|
||||||
|
|
||||||
return <box
|
const border = (() => {
|
||||||
backgroundColor={bg}
|
const sides: BorderSides[] = [];
|
||||||
paddingTop={padding && Math.round(padding / RATIO_HEIGHT)}
|
if (borderBottomWidth) sides.push("bottom");
|
||||||
paddingBottom={padding && Math.round(padding / RATIO_HEIGHT)}
|
if (borderTopWidth) sides.push("top");
|
||||||
paddingLeft={padding && Math.round(padding / RATIO_WIDTH)}
|
if (borderLeftWidth) sides.push("left");
|
||||||
paddingRight={padding && Math.round(padding / RATIO_WIDTH)}
|
if (borderRightWidth) sides.push("right");
|
||||||
{...props}
|
if (!sides.length) return undefined;
|
||||||
>{children}</box>
|
return sides;
|
||||||
|
})();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
backgroundColor={bg}
|
||||||
|
paddingTop={
|
||||||
|
(paddingTop && Math.round(paddingTop / RATIO_HEIGHT)) ||
|
||||||
|
(padding && Math.round(padding / RATIO_HEIGHT))
|
||||||
|
}
|
||||||
|
paddingBottom={
|
||||||
|
(paddingBottom && Math.round(paddingBottom / RATIO_HEIGHT)) ||
|
||||||
|
(padding && Math.round(padding / RATIO_HEIGHT))
|
||||||
|
}
|
||||||
|
paddingLeft={
|
||||||
|
(paddingLeft && Math.round(paddingLeft / RATIO_WIDTH)) ||
|
||||||
|
(padding && Math.round(padding / RATIO_WIDTH))
|
||||||
|
}
|
||||||
|
paddingRight={
|
||||||
|
(paddingRight && Math.round(paddingRight / RATIO_WIDTH)) ||
|
||||||
|
(padding && Math.round(padding / RATIO_WIDTH))
|
||||||
|
}
|
||||||
|
gap={gap && Math.round(gap / RATIO_HEIGHT)}
|
||||||
|
border={border}
|
||||||
|
borderColor={borderColor}
|
||||||
|
width={width && Math.round(width / RATIO_WIDTH)}
|
||||||
|
top={top && Math.round(top / RATIO_HEIGHT)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Pressable({ children: childrenRaw, style, onPress }: PressableProps) {
|
export function Pressable({
|
||||||
const bg = style &&
|
children: childrenRaw,
|
||||||
'backgroundColor' in style
|
style,
|
||||||
? typeof style.backgroundColor == 'string'
|
onPress,
|
||||||
? style.backgroundColor.startsWith('rgba(')
|
}: PressableProps) {
|
||||||
? (() => {
|
const bg =
|
||||||
const parts = style.backgroundColor.split("(")[1].split(")")[0];
|
style && "backgroundColor" in style
|
||||||
const [r, g, b, a] = parts.split(",").map(parseFloat);
|
? typeof style.backgroundColor == "string"
|
||||||
return RGBA.fromInts(r, g, b, a * 255);
|
? style.backgroundColor.startsWith("rgba(")
|
||||||
})()
|
? (() => {
|
||||||
: style.backgroundColor
|
const parts = style.backgroundColor.split("(")[1].split(")")[0];
|
||||||
: undefined
|
const [r, g, b, a] = parts.split(",").map(parseFloat);
|
||||||
: undefined;
|
return RGBA.fromInts(r, g, b, a * 255);
|
||||||
const flexDirection = style &&
|
})()
|
||||||
'flexDirection' in style
|
: style.backgroundColor
|
||||||
? typeof style.flexDirection == 'string'
|
: undefined
|
||||||
? style.flexDirection
|
: undefined;
|
||||||
: undefined
|
const flexDirection =
|
||||||
: undefined;
|
style && "flexDirection" in style
|
||||||
const flex = style &&
|
? typeof style.flexDirection == "string"
|
||||||
'flex' in style
|
? style.flexDirection
|
||||||
? typeof style.flex == 'number'
|
: undefined
|
||||||
? style.flex
|
: undefined;
|
||||||
: undefined
|
const flex =
|
||||||
: undefined;
|
style && "flex" in style
|
||||||
const flexShrink = style &&
|
? typeof style.flex == "number"
|
||||||
'flexShrink' in style
|
? style.flex
|
||||||
? typeof style.flexShrink == 'number'
|
: undefined
|
||||||
? style.flexShrink
|
: undefined;
|
||||||
: undefined
|
const flexShrink =
|
||||||
: undefined;
|
style && "flexShrink" in style
|
||||||
const overflow = style &&
|
? typeof style.flexShrink == "number"
|
||||||
'overflow' in style
|
? style.flexShrink
|
||||||
? typeof style.overflow == 'string'
|
: undefined
|
||||||
? style.overflow
|
: undefined;
|
||||||
: undefined
|
const overflow =
|
||||||
: undefined;
|
style && "overflow" in style
|
||||||
const position = style &&
|
? typeof style.overflow == "string"
|
||||||
'position' in style
|
? style.overflow
|
||||||
? typeof style.position == 'string'
|
: undefined
|
||||||
? style.position
|
: undefined;
|
||||||
: undefined
|
const position =
|
||||||
: undefined;
|
style && "position" in style
|
||||||
const justifyContent = style &&
|
? typeof style.position == "string"
|
||||||
'justifyContent' in style
|
? style.position
|
||||||
? typeof style.justifyContent == 'string'
|
: undefined
|
||||||
? style.justifyContent
|
: undefined;
|
||||||
: undefined
|
const justifyContent =
|
||||||
: undefined;
|
style && "justifyContent" in style
|
||||||
const alignItems = style &&
|
? typeof style.justifyContent == "string"
|
||||||
'alignItems' in style
|
? style.justifyContent
|
||||||
? typeof style.alignItems == 'string'
|
: undefined
|
||||||
? style.alignItems
|
: undefined;
|
||||||
: undefined
|
const alignItems =
|
||||||
: undefined;
|
style && "alignItems" in style
|
||||||
|
? typeof style.alignItems == "string"
|
||||||
|
? style.alignItems
|
||||||
|
: undefined
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const padding = style &&
|
const padding =
|
||||||
'padding' in style
|
style && "padding" in style
|
||||||
? typeof style.padding == 'number'
|
? typeof style.padding == "number"
|
||||||
? style.padding
|
? style.padding
|
||||||
: undefined
|
: undefined
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
const children = childrenRaw instanceof Function ? childrenRaw({ pressed: true }) : childrenRaw;
|
const children =
|
||||||
|
childrenRaw instanceof Function
|
||||||
|
? childrenRaw({ pressed: true })
|
||||||
|
: childrenRaw;
|
||||||
|
|
||||||
return <box
|
return (
|
||||||
onMouseDown={onPress ? ((_event) => {
|
<box
|
||||||
// @ts-ignore
|
onMouseDown={
|
||||||
onPress();
|
onPress
|
||||||
}) : undefined}
|
? (_event) => {
|
||||||
|
// @ts-ignore
|
||||||
backgroundColor={bg}
|
onPress();
|
||||||
flexDirection={flexDirection}
|
}
|
||||||
flexGrow={flex}
|
: undefined
|
||||||
overflow={overflow}
|
}
|
||||||
flexShrink={flexShrink}
|
backgroundColor={bg}
|
||||||
position={position}
|
flexDirection={flexDirection}
|
||||||
justifyContent={justifyContent}
|
flexGrow={flex}
|
||||||
alignItems={alignItems}
|
overflow={overflow}
|
||||||
paddingTop={padding && Math.round(padding / RATIO_HEIGHT)}
|
flexShrink={flexShrink}
|
||||||
paddingBottom={padding && Math.round(padding / RATIO_HEIGHT)}
|
position={position}
|
||||||
paddingLeft={padding && Math.round(padding / RATIO_WIDTH)}
|
justifyContent={justifyContent}
|
||||||
paddingRight={padding && Math.round(padding / RATIO_WIDTH)}
|
alignItems={alignItems}
|
||||||
>{children}</box>
|
paddingTop={padding && Math.round(padding / RATIO_HEIGHT)}
|
||||||
|
paddingBottom={padding && Math.round(padding / RATIO_HEIGHT)}
|
||||||
|
paddingLeft={padding && Math.round(padding / RATIO_WIDTH)}
|
||||||
|
paddingRight={padding && Math.round(padding / RATIO_WIDTH)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export function Text({ style, children }: TextProps) {
|
export function Text({ style, children }: TextProps) {
|
||||||
const fg = style &&
|
const fg =
|
||||||
'color' in style
|
style && "color" in style
|
||||||
? typeof style.color == 'string'
|
? typeof style.color == "string"
|
||||||
? style.color
|
? style.color
|
||||||
: undefined
|
: undefined
|
||||||
: undefined;
|
: undefined;
|
||||||
return <text fg={fg || "black"}>{children}</text>
|
return <text fg={fg || "black"}>{children}</text>;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ScrollView({ children }: ScrollViewProps) {
|
export function ScrollView({ children }: ScrollViewProps) {
|
||||||
return <scrollbox >{children}</scrollbox>
|
return <scrollbox>{children}</scrollbox>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Modal({ children, visible }: ModalProps) {
|
export function Modal({ children, visible }: ModalProps) {
|
||||||
const { width, height } = useTerminalDimensions();
|
const { width, height } = useTerminalDimensions();
|
||||||
return <box
|
return (
|
||||||
visible={visible}
|
<box
|
||||||
position="absolute"
|
visible={visible}
|
||||||
width={width}
|
position="absolute"
|
||||||
height={height}
|
width={width}
|
||||||
zIndex={10}
|
height={height}
|
||||||
>
|
zIndex={10}
|
||||||
{children}
|
>
|
||||||
</box>
|
{children}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextInput({
|
||||||
|
defaultValue,
|
||||||
|
onChangeText,
|
||||||
|
onKeyPress,
|
||||||
|
}: TextInputProps) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
minWidth={20}
|
||||||
|
minHeight={1}
|
||||||
|
backgroundColor="white"
|
||||||
|
textColor="black"
|
||||||
|
focused={true}
|
||||||
|
cursorColor={"black"}
|
||||||
|
onInput={onChangeText}
|
||||||
|
onKeyDown={(key) =>
|
||||||
|
// @ts-ignore
|
||||||
|
onKeyPress({
|
||||||
|
nativeEvent: {
|
||||||
|
key: key.name == "return" ? "Enter" : key.name,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
placeholder={defaultValue}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Platform = {
|
export const Platform = {
|
||||||
@@ -215,13 +311,13 @@ export const Linking = {
|
|||||||
platform() == "darwin"
|
platform() == "darwin"
|
||||||
? `open ${url}`
|
? `open ${url}`
|
||||||
: platform() == "win32"
|
: platform() == "win32"
|
||||||
? `start "" "${url}"`
|
? `start "" "${url}"`
|
||||||
: `xdg-open "${url}"`;
|
: `xdg-open "${url}"`;
|
||||||
exec(cmd);
|
exec(cmd);
|
||||||
}
|
},
|
||||||
} satisfies Partial<LinkingImpl>;
|
} satisfies Partial<LinkingImpl>;
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
View,
|
View,
|
||||||
Text,
|
Text,
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -13,6 +13,6 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"db:gen": "drizzle-zero generate -s ./src/db/schema/public.ts -o ./src/zero-schema.gen.ts -f && sed -i 's/enableLegacyQueries: true,/enableLegacyQueries: false,/g' src/zero-schema.gen.ts && sed -i 's/enableLegacyMutators: true,/enableLegacyMutators: false,/g' src/zero-schema.gen.ts",
|
"db:gen": "drizzle-zero generate -s ./src/db/schema/public.ts -o ./src/zero-schema.gen.ts -f && sed -i 's/enableLegacyQueries: true,/enableLegacyQueries: false,/g' src/zero-schema.gen.ts && sed -i 's/enableLegacyMutators: true,/enableLegacyMutators: false,/g' src/zero-schema.gen.ts",
|
||||||
"db:migrate": "drizzle-kit push"
|
"db:push": "drizzle-kit push"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
export const HOST = process.env.EXPO_PUBLIC_TAILSCALE_MACHINE || "localhost";
|
export const HOST = process.env.EXPO_PUBLIC_TAILSCALE_MACHINE || "localhost";
|
||||||
export const BASE_URL = `http://${HOST}`;
|
export const BASE_URL = `http://${HOST}`;
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,14 @@
|
|||||||
import { pgTable, text, boolean, timestamp, uniqueIndex, decimal } from "drizzle-orm/pg-core";
|
import { relations } from "drizzle-orm";
|
||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
decimal,
|
||||||
|
pgTable,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
pgEnum,
|
||||||
|
uniqueIndex,
|
||||||
|
numeric,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
export const users = pgTable(
|
export const users = pgTable(
|
||||||
"user",
|
"user",
|
||||||
@@ -33,6 +43,7 @@ export const plaidLink = pgTable("plaidLink", {
|
|||||||
user_id: text("user_id").notNull(),
|
user_id: text("user_id").notNull(),
|
||||||
link: text("link").notNull(),
|
link: text("link").notNull(),
|
||||||
token: text("token").notNull(),
|
token: text("token").notNull(),
|
||||||
|
completeAt: timestamp("complete_at"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -54,5 +65,41 @@ export const plaidAccessTokens = pgTable("plaidAccessToken", {
|
|||||||
logoUrl: text("logoUrl").notNull(),
|
logoUrl: text("logoUrl").notNull(),
|
||||||
userId: text("user_id").notNull(),
|
userId: text("user_id").notNull(),
|
||||||
token: text("token").notNull(),
|
token: text("token").notNull(),
|
||||||
|
syncCursor: text("sync_cursor"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const budget = pgTable("budget", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
orgId: text("org_id").notNull(),
|
||||||
|
label: text("label").notNull(),
|
||||||
|
createdBy: text("created_by").notNull(),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const category = pgTable("category", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
budgetId: text("budget_id").notNull(),
|
||||||
|
amount: decimal("amount").notNull(),
|
||||||
|
every: text("every", { enum: ["year", "month", "week"] }).notNull(),
|
||||||
|
order: numeric("order").notNull(),
|
||||||
|
label: text("label").notNull(),
|
||||||
|
color: text("color").notNull(),
|
||||||
|
createdBy: text("created_by").notNull(),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
removedBy: text("removed_by"),
|
||||||
|
removedAt: timestamp("removed_at"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const budgetRelations = relations(budget, ({ many }) => ({
|
||||||
|
categories: many(category),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const categoryRelations = relations(category, ({ one }) => ({
|
||||||
|
budget: one(budget, {
|
||||||
|
fields: [category.budgetId],
|
||||||
|
references: [budget.id],
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Transaction } from "@rocicorp/zero";
|
import type { Transaction } from "@rocicorp/zero";
|
||||||
import type { AuthData } from "./auth";
|
import { authDataSchema, type AuthData } from "./auth";
|
||||||
import { type Schema } from "./zero-schema.gen";
|
import { type Category, type Schema } from "./zero-schema.gen";
|
||||||
import { isLoggedIn } from "./zql";
|
import { isLoggedIn } from "./zql";
|
||||||
|
|
||||||
type Tx = Transaction<Schema>;
|
type Tx = Transaction<Schema>;
|
||||||
@@ -10,34 +10,145 @@ export function createMutators(authData: AuthData | null) {
|
|||||||
link: {
|
link: {
|
||||||
async create() {},
|
async create() {},
|
||||||
async get(tx: Tx, { link_token }: { link_token: string }) {},
|
async get(tx: Tx, { link_token }: { link_token: string }) {},
|
||||||
async updateTransactions() {},
|
async webhook() {},
|
||||||
async updateBalences() {},
|
async sync() {},
|
||||||
async deleteAccounts(tx: Tx, { accountIds }: { accountIds: string[] }) {
|
// async updateTransactions() {},
|
||||||
|
// async updateBalences() {},
|
||||||
|
async deleteAccounts(tx: Tx, { accountIds }: { accountIds: string[] }) {
|
||||||
isLoggedIn(authData);
|
isLoggedIn(authData);
|
||||||
for (const id of accountIds) {
|
for (const id of accountIds) {
|
||||||
const token = await tx.query.plaidAccessTokens.where("userId", '=', authData.user.id).one();
|
const token = await tx.query.plaidAccessTokens
|
||||||
|
.where("userId", "=", authData.user.id)
|
||||||
|
.one();
|
||||||
if (!token) continue;
|
if (!token) continue;
|
||||||
await tx.mutate.plaidAccessTokens.delete({ id });
|
await tx.mutate.plaidAccessTokens.delete({ id });
|
||||||
|
|
||||||
const balances = await tx.query.balance
|
const balances = await tx.query.balance
|
||||||
.where('user_id', '=', authData.user.id)
|
.where("user_id", "=", authData.user.id)
|
||||||
.where("tokenId", '=', token.id)
|
.where("tokenId", "=", token.id)
|
||||||
.run();
|
.run();
|
||||||
|
|
||||||
for (const bal of balances) {
|
for (const bal of balances) {
|
||||||
await tx.mutate.balance.delete({ id: bal.id });
|
await tx.mutate.balance.delete({ id: bal.id });
|
||||||
const txs = await tx.query.transaction
|
const txs = await tx.query.transaction
|
||||||
.where('user_id', '=', authData.user.id)
|
.where("user_id", "=", authData.user.id)
|
||||||
.where('account_id', '=', bal.tokenId)
|
.where("account_id", "=", bal.tokenId)
|
||||||
.run();
|
.run();
|
||||||
for (const transaction of txs) {
|
for (const transaction of txs) {
|
||||||
await tx.mutate.transaction.delete({ id: transaction.id });
|
await tx.mutate.transaction.delete({ id: transaction.id });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
|
budget: {
|
||||||
|
async create(
|
||||||
|
tx: Tx,
|
||||||
|
{ id, categoryId }: { id: string; categoryId: string },
|
||||||
|
) {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
await tx.mutate.budget.insert({
|
||||||
|
id,
|
||||||
|
orgId: authData.user.id,
|
||||||
|
label: "New Budget",
|
||||||
|
createdBy: authData.user.id,
|
||||||
|
});
|
||||||
|
await tx.mutate.category.insert({
|
||||||
|
id: categoryId,
|
||||||
|
budgetId: id,
|
||||||
|
amount: 0,
|
||||||
|
every: "week",
|
||||||
|
order: 1000,
|
||||||
|
label: "My category",
|
||||||
|
color: "#f06",
|
||||||
|
createdBy: authData.user.id,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
async delete(tx: Tx, { id }: { id: string }) {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
await tx.mutate.budget.delete({
|
||||||
|
id,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
async createCategory(
|
||||||
|
tx: Tx,
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
budgetId,
|
||||||
|
order,
|
||||||
|
}: { id: string; budgetId: string; order: number },
|
||||||
|
) {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
|
||||||
|
if (order != undefined) {
|
||||||
|
const after = await tx.query.category
|
||||||
|
.where("budgetId", "=", budgetId)
|
||||||
|
.where("order", ">", order);
|
||||||
|
|
||||||
|
after.forEach((item) => {
|
||||||
|
tx.mutate.category.update({
|
||||||
|
id: item.id,
|
||||||
|
order: item.order + 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
tx.mutate.category.insert({
|
||||||
|
id,
|
||||||
|
budgetId,
|
||||||
|
amount: 0,
|
||||||
|
every: "week",
|
||||||
|
order: order + 1,
|
||||||
|
label: "My category",
|
||||||
|
color: "#f06",
|
||||||
|
createdBy: authData.user.id,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
async deleteCategory(tx: Tx, { id }: { id: string }) {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
const item = await tx.query.category.where("id", "=", id).one();
|
||||||
|
if (!item) throw Error("Item does not exist");
|
||||||
|
tx.mutate.category.update({
|
||||||
|
id,
|
||||||
|
removedAt: new Date().getTime(),
|
||||||
|
removedBy: authData.user.id,
|
||||||
|
});
|
||||||
|
const after = await tx.query.category
|
||||||
|
.where("budgetId", "=", item.budgetId)
|
||||||
|
.where("order", ">", item.order)
|
||||||
|
.run();
|
||||||
|
for (const item of after) {
|
||||||
|
tx.mutate.category.update({ id: item.id, order: item.order - 1 });
|
||||||
|
}
|
||||||
|
// after.forEach((item) => {
|
||||||
|
// });
|
||||||
|
},
|
||||||
|
async updateCategory(
|
||||||
|
tx: Tx,
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
order,
|
||||||
|
amount,
|
||||||
|
every,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
label?: string;
|
||||||
|
order?: number;
|
||||||
|
amount?: number;
|
||||||
|
every?: Category["every"];
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
tx.mutate.category.update({
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
order,
|
||||||
|
amount,
|
||||||
|
every,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
} as const;
|
} as const;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,37 +5,79 @@ import { type AuthData } from "./auth";
|
|||||||
import { isLoggedIn } from "./zql";
|
import { isLoggedIn } from "./zql";
|
||||||
|
|
||||||
export const queries = {
|
export const queries = {
|
||||||
me: syncedQueryWithContext('me', z.tuple([]), (authData: AuthData | null) => {
|
me: syncedQueryWithContext("me", z.tuple([]), (authData: AuthData | null) => {
|
||||||
isLoggedIn(authData);
|
isLoggedIn(authData);
|
||||||
return builder.users
|
return builder.users.where("id", "=", authData.user.id).one();
|
||||||
.where('id', '=', authData.user.id)
|
|
||||||
.one();
|
|
||||||
}),
|
}),
|
||||||
allTransactions: syncedQueryWithContext('allTransactions', z.tuple([]), (authData: AuthData | null) => {
|
allTransactions: syncedQueryWithContext(
|
||||||
isLoggedIn(authData);
|
"allTransactions",
|
||||||
return builder.transaction
|
z.tuple([]),
|
||||||
.where('user_id', '=', authData.user.id)
|
(authData: AuthData | null) => {
|
||||||
.orderBy('datetime', 'desc')
|
isLoggedIn(authData);
|
||||||
.limit(50)
|
return builder.transaction
|
||||||
}),
|
.where("user_id", "=", authData.user.id)
|
||||||
getPlaidLink: syncedQueryWithContext('getPlaidLink', z.tuple([]), (authData: AuthData | null) => {
|
.orderBy("datetime", "desc")
|
||||||
isLoggedIn(authData);
|
.limit(50);
|
||||||
return builder.plaidLink
|
},
|
||||||
.where('user_id', '=', authData.user.id)
|
),
|
||||||
.where('createdAt', '>', new Date().getTime() - (1000 * 60 * 60 * 4))
|
getPlaidLink: syncedQueryWithContext(
|
||||||
.orderBy('createdAt', 'desc')
|
"getPlaidLink",
|
||||||
.one();
|
z.tuple([]),
|
||||||
}),
|
(authData: AuthData | null) => {
|
||||||
getBalances: syncedQueryWithContext('getBalances', z.tuple([]), (authData: AuthData | null) => {
|
isLoggedIn(authData);
|
||||||
isLoggedIn(authData);
|
return builder.plaidLink
|
||||||
return builder.balance
|
.where(({ cmp, and, or }) =>
|
||||||
.where('user_id', '=', authData.user.id)
|
and(
|
||||||
.orderBy('name', 'asc');
|
cmp("user_id", "=", authData.user.id),
|
||||||
}),
|
cmp("createdAt", ">", new Date().getTime() - 1000 * 60 * 60 * 4),
|
||||||
getItems: syncedQueryWithContext('getItems', z.tuple([]), (authData: AuthData | null) => {
|
or(
|
||||||
isLoggedIn(authData);
|
cmp("completeAt", ">", new Date().getTime() - 1000 * 5),
|
||||||
return builder.plaidAccessTokens
|
cmp("completeAt", "IS", null),
|
||||||
.where('userId', '=', authData.user.id)
|
),
|
||||||
.orderBy('createdAt', 'desc');
|
),
|
||||||
})
|
)
|
||||||
|
.orderBy("createdAt", "desc")
|
||||||
|
.one();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
getBalances: syncedQueryWithContext(
|
||||||
|
"getBalances",
|
||||||
|
z.tuple([]),
|
||||||
|
(authData: AuthData | null) => {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
return builder.balance
|
||||||
|
.where("user_id", "=", authData.user.id)
|
||||||
|
.orderBy("name", "asc");
|
||||||
|
},
|
||||||
|
),
|
||||||
|
getItems: syncedQueryWithContext(
|
||||||
|
"getItems",
|
||||||
|
z.tuple([]),
|
||||||
|
(authData: AuthData | null) => {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
return builder.plaidAccessTokens
|
||||||
|
.where("userId", "=", authData.user.id)
|
||||||
|
.orderBy("createdAt", "desc");
|
||||||
|
},
|
||||||
|
),
|
||||||
|
getBudgets: syncedQueryWithContext(
|
||||||
|
"getBudgets",
|
||||||
|
z.tuple([]),
|
||||||
|
(authData: AuthData | null) => {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
return builder.budget
|
||||||
|
.related("categories", (q) =>
|
||||||
|
q.where("removedAt", "IS", null).orderBy("order", "asc"),
|
||||||
|
)
|
||||||
|
.limit(10);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
getBudgetCategories: syncedQueryWithContext(
|
||||||
|
"getBudgetCategories",
|
||||||
|
z.tuple([]),
|
||||||
|
(authData: AuthData | null) => {
|
||||||
|
isLoggedIn(authData);
|
||||||
|
return builder.category.orderBy("order", "desc");
|
||||||
|
},
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -112,6 +112,190 @@ export const schema = {
|
|||||||
},
|
},
|
||||||
primaryKey: ["id"],
|
primaryKey: ["id"],
|
||||||
},
|
},
|
||||||
|
budget: {
|
||||||
|
name: "budget",
|
||||||
|
columns: {
|
||||||
|
id: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"id"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
orgId: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"orgId"
|
||||||
|
>,
|
||||||
|
serverName: "org_id",
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"label"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"createdBy"
|
||||||
|
>,
|
||||||
|
serverName: "created_by",
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"createdAt"
|
||||||
|
>,
|
||||||
|
serverName: "created_at",
|
||||||
|
},
|
||||||
|
updatedAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"budget",
|
||||||
|
"updatedAt"
|
||||||
|
>,
|
||||||
|
serverName: "updated_at",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
primaryKey: ["id"],
|
||||||
|
},
|
||||||
|
category: {
|
||||||
|
name: "category",
|
||||||
|
columns: {
|
||||||
|
id: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"id"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
budgetId: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"budgetId"
|
||||||
|
>,
|
||||||
|
serverName: "budget_id",
|
||||||
|
},
|
||||||
|
amount: {
|
||||||
|
type: "number",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"amount"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
every: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"every"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
order: {
|
||||||
|
type: "number",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"order"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"label"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
color: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"color"
|
||||||
|
>,
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: "string",
|
||||||
|
optional: false,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"createdBy"
|
||||||
|
>,
|
||||||
|
serverName: "created_by",
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"createdAt"
|
||||||
|
>,
|
||||||
|
serverName: "created_at",
|
||||||
|
},
|
||||||
|
updatedAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"updatedAt"
|
||||||
|
>,
|
||||||
|
serverName: "updated_at",
|
||||||
|
},
|
||||||
|
removedBy: {
|
||||||
|
type: "string",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"removedBy"
|
||||||
|
>,
|
||||||
|
serverName: "removed_by",
|
||||||
|
},
|
||||||
|
removedAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"category",
|
||||||
|
"removedAt"
|
||||||
|
>,
|
||||||
|
serverName: "removed_at",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
primaryKey: ["id"],
|
||||||
|
},
|
||||||
plaidAccessTokens: {
|
plaidAccessTokens: {
|
||||||
name: "plaidAccessTokens",
|
name: "plaidAccessTokens",
|
||||||
columns: {
|
columns: {
|
||||||
@@ -161,6 +345,16 @@ export const schema = {
|
|||||||
"token"
|
"token"
|
||||||
>,
|
>,
|
||||||
},
|
},
|
||||||
|
syncCursor: {
|
||||||
|
type: "string",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"plaidAccessTokens",
|
||||||
|
"syncCursor"
|
||||||
|
>,
|
||||||
|
serverName: "sync_cursor",
|
||||||
|
},
|
||||||
createdAt: {
|
createdAt: {
|
||||||
type: "number",
|
type: "number",
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -214,6 +408,16 @@ export const schema = {
|
|||||||
"token"
|
"token"
|
||||||
>,
|
>,
|
||||||
},
|
},
|
||||||
|
completeAt: {
|
||||||
|
type: "number",
|
||||||
|
optional: true,
|
||||||
|
customType: null as unknown as ZeroCustomType<
|
||||||
|
ZeroSchema,
|
||||||
|
"plaidLink",
|
||||||
|
"completeAt"
|
||||||
|
>,
|
||||||
|
serverName: "complete_at",
|
||||||
|
},
|
||||||
createdAt: {
|
createdAt: {
|
||||||
type: "number",
|
type: "number",
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -408,7 +612,28 @@ export const schema = {
|
|||||||
serverName: "user",
|
serverName: "user",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
relationships: {},
|
relationships: {
|
||||||
|
budget: {
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
sourceField: ["id"],
|
||||||
|
destField: ["budgetId"],
|
||||||
|
destSchema: "category",
|
||||||
|
cardinality: "many",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
category: {
|
||||||
|
budget: [
|
||||||
|
{
|
||||||
|
sourceField: ["budgetId"],
|
||||||
|
destField: ["id"],
|
||||||
|
destSchema: "budget",
|
||||||
|
cardinality: "one",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
enableLegacyQueries: false,
|
enableLegacyQueries: false,
|
||||||
enableLegacyMutators: false,
|
enableLegacyMutators: false,
|
||||||
} as const;
|
} as const;
|
||||||
@@ -423,6 +648,16 @@ export type Schema = typeof schema;
|
|||||||
* This type is auto-generated from your Drizzle schema definition.
|
* This type is auto-generated from your Drizzle schema definition.
|
||||||
*/
|
*/
|
||||||
export type Balance = Row<Schema["tables"]["balance"]>;
|
export type Balance = Row<Schema["tables"]["balance"]>;
|
||||||
|
/**
|
||||||
|
* Represents a row from the "budget" table.
|
||||||
|
* This type is auto-generated from your Drizzle schema definition.
|
||||||
|
*/
|
||||||
|
export type Budget = Row<Schema["tables"]["budget"]>;
|
||||||
|
/**
|
||||||
|
* Represents a row from the "category" table.
|
||||||
|
* This type is auto-generated from your Drizzle schema definition.
|
||||||
|
*/
|
||||||
|
export type Category = Row<Schema["tables"]["category"]>;
|
||||||
/**
|
/**
|
||||||
* Represents a row from the "plaidAccessTokens" table.
|
* Represents a row from the "plaidAccessTokens" table.
|
||||||
* This type is auto-generated from your Drizzle schema definition.
|
* This type is auto-generated from your Drizzle schema definition.
|
||||||
|
|||||||
@@ -1,29 +1,39 @@
|
|||||||
import { useKeyboard } from "../src/useKeyboard";
|
import { useEffect, type ReactNode } from "react";
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { Text, Pressable } from "react-native";
|
import { Text, Pressable } from "react-native";
|
||||||
|
import { useShortcut, type Key } from "../lib/shortcuts";
|
||||||
|
|
||||||
|
type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
|
||||||
|
|
||||||
export interface ButtonProps {
|
export interface ButtonProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
onPress?: () => void;
|
onPress?: () => void;
|
||||||
variant?: 'default' | 'secondary' | 'destructive';
|
variant?: "default" | "secondary" | "destructive";
|
||||||
shortcut?: string;
|
shortcut?: Key;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STYLES: Record<NonNullable<ButtonProps['variant']>, { backgroundColor: string, color: string }> = {
|
const STYLES: Record<
|
||||||
default: { backgroundColor: 'black', color: 'white' },
|
NonNullable<ButtonProps["variant"]>,
|
||||||
secondary: { backgroundColor: '#ccc', color: 'black' },
|
{ backgroundColor: string; color: string }
|
||||||
destructive: { backgroundColor: 'red', color: 'white' },
|
> = {
|
||||||
|
default: { backgroundColor: "black", color: "white" },
|
||||||
|
secondary: { backgroundColor: "#ccc", color: "black" },
|
||||||
|
destructive: { backgroundColor: "red", color: "white" },
|
||||||
};
|
};
|
||||||
|
|
||||||
export function Button({ children, variant, onPress, shortcut }: ButtonProps) {
|
export function Button({ children, variant, onPress, shortcut }: ButtonProps) {
|
||||||
const { backgroundColor, color } = STYLES[variant || "default"];
|
const { backgroundColor, color } = STYLES[variant || "default"];
|
||||||
|
|
||||||
useKeyboard((key) => {
|
if (shortcut && onPress) {
|
||||||
if (!shortcut || !onPress) return;
|
useShortcut(shortcut, onPress);
|
||||||
if (key.name == shortcut) onPress();
|
}
|
||||||
});
|
|
||||||
|
|
||||||
return <Pressable onPress={onPress} style={{ backgroundColor }}>
|
return (
|
||||||
<Text style={{ fontFamily: 'mono', color }}> {children}{shortcut && ` (${shortcut})`} </Text>
|
<Pressable onPress={onPress} style={{ backgroundColor }}>
|
||||||
</Pressable>
|
<Text style={{ fontFamily: "mono", color }}>
|
||||||
|
{" "}
|
||||||
|
{children}
|
||||||
|
{shortcut && ` (${shortcut})`}{" "}
|
||||||
|
</Text>
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import { type ReactNode } from "react";
|
import { createContext, use, type ReactNode } from "react";
|
||||||
import { Modal, View, Text } from "react-native";
|
import { Modal, View, Text } from "react-native";
|
||||||
import { useKeyboard } from "../src/useKeyboard";
|
import { useShortcut } from "../lib/shortcuts";
|
||||||
|
|
||||||
|
export interface DialogState {
|
||||||
|
close?: () => void;
|
||||||
|
}
|
||||||
|
export const Context = createContext<DialogState>({
|
||||||
|
close: () => {},
|
||||||
|
});
|
||||||
|
|
||||||
interface ProviderProps {
|
interface ProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -8,19 +15,22 @@ interface ProviderProps {
|
|||||||
close?: () => void;
|
close?: () => void;
|
||||||
}
|
}
|
||||||
export function Provider({ children, visible, close }: ProviderProps) {
|
export function Provider({ children, visible, close }: ProviderProps) {
|
||||||
useKeyboard((key) => {
|
|
||||||
if (key.name == 'escape') {
|
|
||||||
if (close) close();
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal transparent visible={visible} >
|
<Context.Provider value={{ close }}>
|
||||||
{/* <Pressable onPress={() => close && close()} style={{ justifyContent: 'center', alignItems: 'center', flex: 1, backgroundColor: 'rgba(0,0,0,0.2)', }}> */}
|
<Modal transparent visible={visible}>
|
||||||
<View style={{ justifyContent: 'center', alignItems: 'center', flex: 1, backgroundColor: 'rgba(0,0,0,0.2)', }}>
|
{/* <Pressable onPress={() => close && close()} style={{ justifyContent: 'center', alignItems: 'center', flex: 1, backgroundColor: 'rgba(0,0,0,0.2)', }}> */}
|
||||||
{visible && children}
|
<View
|
||||||
</View>
|
style={{
|
||||||
</Modal>
|
// justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: "rgba(0,0,0,0.2)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{visible && children}
|
||||||
|
</View>
|
||||||
|
</Modal>
|
||||||
|
</Context.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,8 +38,11 @@ interface ContentProps {
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
export function Content({ children }: ContentProps) {
|
export function Content({ children }: ContentProps) {
|
||||||
|
const { close } = use(Context);
|
||||||
|
useShortcut("escape", () => close?.(), "dialog");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={{ backgroundColor: 'white', padding: 12, alignItems: 'center' }}>
|
<View style={{ backgroundColor: "white", alignItems: "center", top: 120 }}>
|
||||||
{children}
|
{children}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,28 +3,34 @@ import { View, Text } from "react-native";
|
|||||||
import { useKeyboard } from "../src/useKeyboard";
|
import { useKeyboard } from "../src/useKeyboard";
|
||||||
|
|
||||||
export type ListProps<T> = {
|
export type ListProps<T> = {
|
||||||
items: T[],
|
items: T[];
|
||||||
renderItem: (props: { item: T, isSelected: boolean }) => ReactNode;
|
renderItem: (props: { item: T; isSelected: boolean }) => ReactNode;
|
||||||
};
|
};
|
||||||
export function List<T>({ items, renderItem }: ListProps<T>) {
|
export function List<T>({ items, renderItem }: ListProps<T>) {
|
||||||
const [idx, setIdx] = useState(0);
|
const [idx, setIdx] = useState(0);
|
||||||
|
|
||||||
useKeyboard((key) => {
|
useKeyboard(
|
||||||
if (key.name == 'j') {
|
(key) => {
|
||||||
setIdx((prevIdx) => prevIdx + 1 < items.length ? prevIdx + 1 : items.length - 1);
|
if (key.name == "j") {
|
||||||
} else if (key.name == 'k') {
|
setIdx((prevIdx) =>
|
||||||
setIdx((prevIdx) => prevIdx == 0 ? 0 : prevIdx - 1);
|
prevIdx + 1 < items.length ? prevIdx + 1 : items.length - 1,
|
||||||
} else if (key.name == 'g' && key.shift) {
|
);
|
||||||
setIdx(items.length - 1);
|
} else if (key.name == "k") {
|
||||||
}
|
setIdx((prevIdx) => (prevIdx == 0 ? 0 : prevIdx - 1));
|
||||||
}, [items]);
|
} else if (key.name == "g" && key.shift) {
|
||||||
|
setIdx(items.length - 1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[items],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View>
|
<View>
|
||||||
{items.map((item, index) => <View style={{ backgroundColor: index == idx ? 'black' : undefined }}>
|
{items.map((item, index) => (
|
||||||
{renderItem({ item, isSelected: index == idx })}
|
<View style={{ backgroundColor: index == idx ? "black" : undefined }}>
|
||||||
</View>)}
|
{renderItem({ item, isSelected: index == idx })}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import { createContext, use, useState, type ReactNode } from "react";
|
import { createContext, use, useEffect, useState, type ReactNode } from "react";
|
||||||
import { View, Text } from "react-native";
|
import { View, Text } from "react-native";
|
||||||
import { useKeyboard } from "../src/useKeyboard";
|
import { useShortcut } from "../lib/shortcuts/hooks";
|
||||||
import type { KeyEvent } from "@opentui/core";
|
import type { Key } from "../lib/shortcuts";
|
||||||
|
|
||||||
const HEADER_COLOR = '#7158e2';
|
const HEADER_COLOR = "#7158e2";
|
||||||
const TABLE_COLORS = [
|
|
||||||
'#ddd',
|
|
||||||
'#eee'
|
|
||||||
];
|
|
||||||
const SELECTED_COLOR = '#f7b730';
|
|
||||||
|
|
||||||
|
const COLORS = {
|
||||||
|
focused: "#ddd",
|
||||||
|
selected: "#eaebf6",
|
||||||
|
focused_selected: "#d5d7ef",
|
||||||
|
};
|
||||||
|
|
||||||
const EXTRA = 5;
|
const EXTRA = 5;
|
||||||
|
|
||||||
@@ -20,99 +20,157 @@ interface TableState {
|
|||||||
columns: Column[];
|
columns: Column[];
|
||||||
columnMap: Map<string, number>;
|
columnMap: Map<string, number>;
|
||||||
idx: number;
|
idx: number;
|
||||||
selectedFrom: number | undefined;
|
selectedIdx: Set<number>;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
|
||||||
const INITAL_STATE = {
|
const INITAL_STATE = {
|
||||||
data: [],
|
data: [],
|
||||||
columns: [],
|
columns: [],
|
||||||
columnMap: new Map(),
|
columnMap: new Map(),
|
||||||
idx: 0,
|
idx: 0,
|
||||||
selectedFrom: undefined,
|
selectedIdx: new Set(),
|
||||||
} satisfies TableState;
|
} satisfies TableState;
|
||||||
|
|
||||||
export const Context = createContext<TableState>(INITAL_STATE);
|
export const Context = createContext<TableState>(INITAL_STATE);
|
||||||
|
|
||||||
export type Column = { name: string, label: string, render?: (i: number | string) => string };
|
export type Column = {
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
render?: (i: number | string) => string;
|
||||||
|
};
|
||||||
|
|
||||||
function renderCell(row: ValidRecord, column: Column): string {
|
function renderCell(row: ValidRecord, column: Column): string {
|
||||||
const cell = row[column.name];
|
const cell = row[column.name];
|
||||||
if (cell == undefined) return 'n/a';
|
if (cell == undefined) return "n/a";
|
||||||
if (cell == null) return 'null';
|
if (cell == null) return "null";
|
||||||
if (column.render) return column.render(cell);
|
if (column.render) return column.render(cell);
|
||||||
return cell.toString();
|
return cell.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TableShortcut<T> {
|
||||||
|
key: Key;
|
||||||
|
handler: (params: { selected: T[]; index: number }) => void;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ProviderProps<T> {
|
export interface ProviderProps<T> {
|
||||||
data: T[];
|
data: T[];
|
||||||
columns: Column[];
|
columns: Column[];
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
onKey?: (event: KeyEvent, selected: T[]) => void;
|
shortcuts?: TableShortcut<T>[];
|
||||||
};
|
}
|
||||||
export function Provider<T extends ValidRecord>({ data, columns, children, onKey }: ProviderProps<T>) {
|
export function Provider<T extends ValidRecord>({
|
||||||
|
data,
|
||||||
|
columns,
|
||||||
|
children,
|
||||||
|
shortcuts,
|
||||||
|
}: ProviderProps<T>) {
|
||||||
const [idx, setIdx] = useState(0);
|
const [idx, setIdx] = useState(0);
|
||||||
const [selectedFrom, setSelectedFrom] = useState<number>();
|
const [selectedIdx, setSelectedIdx] = useState(new Set<number>());
|
||||||
|
|
||||||
useKeyboard((key) => {
|
useShortcut("j", () => {
|
||||||
if (key.name == 'j' || key.name == 'down') {
|
setIdx((prev) => Math.min(prev + 1, data.length - 1));
|
||||||
if (key.shift && selectedFrom == undefined) {
|
});
|
||||||
setSelectedFrom(idx);
|
useShortcut("down", () => {
|
||||||
}
|
setIdx((prev) => Math.min(prev + 1, data.length - 1));
|
||||||
setIdx((prev) => Math.min(prev + 1, data.length - 1));
|
});
|
||||||
} else if (key.name == 'k' || key.name == 'up') {
|
useShortcut("k", () => {
|
||||||
if (key.shift && selectedFrom == undefined) {
|
setIdx((prev) => Math.max(prev - 1, 0));
|
||||||
setSelectedFrom(idx);
|
});
|
||||||
}
|
useShortcut("up", () => {
|
||||||
setIdx((prev) => Math.max(prev - 1, 0));
|
setIdx((prev) => Math.max(prev - 1, 0));
|
||||||
} else if (key.name == 'g' && key.shift) {
|
});
|
||||||
setIdx(data.length - 1);
|
|
||||||
} else if (key.name == 'v') {
|
useShortcut("escape", () => {
|
||||||
setSelectedFrom(idx);
|
setSelectedIdx(new Set());
|
||||||
} else if (key.name == 'escape') {
|
});
|
||||||
setSelectedFrom(undefined);
|
useShortcut("x", () => {
|
||||||
} else {
|
setSelectedIdx((last) => {
|
||||||
const from = selectedFrom ? Math.min(idx, selectedFrom) : idx;
|
const newSelected = new Set(last);
|
||||||
const to = selectedFrom ? Math.max(idx, selectedFrom) : idx;
|
newSelected.add(idx);
|
||||||
const selected = data.slice(from, to + 1);
|
return newSelected;
|
||||||
if (onKey) onKey(key, selected);
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIdx((prev) => Math.max(Math.min(prev, data.length - 1), 0));
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
if (shortcuts) {
|
||||||
|
for (const shortcut of shortcuts) {
|
||||||
|
useShortcut(shortcut.key, () => {
|
||||||
|
const selected = data.filter(
|
||||||
|
(_, index) => idx == index || selectedIdx.has(index),
|
||||||
|
);
|
||||||
|
shortcut.handler({ selected, index: idx });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, [data, idx, selectedFrom]);
|
}
|
||||||
|
|
||||||
|
|
||||||
const columnMap = new Map(columns.map(col => {
|
|
||||||
return [col.name, Math.max(col.label.length, ...data.map(row => renderCell(row, col).length))]
|
|
||||||
}));
|
|
||||||
|
|
||||||
|
const columnMap = new Map(
|
||||||
|
columns.map((col) => {
|
||||||
|
return [
|
||||||
|
col.name,
|
||||||
|
Math.max(
|
||||||
|
col.label.length,
|
||||||
|
...data.map((row) => renderCell(row, col).length),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Context.Provider value={{ data, columns, columnMap, idx, selectedFrom }}>
|
<Context.Provider value={{ data, columns, columnMap, idx, selectedIdx }}>
|
||||||
{children}
|
{children}
|
||||||
</Context.Provider>
|
</Context.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Body() {
|
export function Body() {
|
||||||
const { columns, data, columnMap, idx, selectedFrom } = use(Context);
|
const { columns, data, columnMap, idx, selectedIdx } = use(Context);
|
||||||
return (
|
return (
|
||||||
<View>
|
<View>
|
||||||
<View style={{ backgroundColor: HEADER_COLOR, flexDirection: 'row' }}>
|
<View style={{ backgroundColor: HEADER_COLOR, flexDirection: "row" }}>
|
||||||
{columns.map(column => <Text key={column.name} style={{ fontFamily: 'mono', color: 'white' }}>{rpad(column.label, columnMap.get(column.name)! - column.label.length + EXTRA)}</Text>)}
|
{columns.map((column) => (
|
||||||
|
<Text
|
||||||
|
key={column.name}
|
||||||
|
style={{ fontFamily: "mono", color: "white" }}
|
||||||
|
>
|
||||||
|
{rpad(
|
||||||
|
column.label,
|
||||||
|
columnMap.get(column.name)! - column.label.length + EXTRA,
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
</View>
|
</View>
|
||||||
{data.map((row, index) => {
|
{data.map((row, index) => {
|
||||||
const isSelected = index == idx || (selectedFrom != undefined && ((selectedFrom <= index && index <= idx) || (idx <= index && index <= selectedFrom)))
|
const isSelected = selectedIdx.has(index);
|
||||||
|
const isFocused = index == idx;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View key={index} style={{ backgroundColor: isSelected ? SELECTED_COLOR : TABLE_COLORS[index % 2] }}>
|
<View
|
||||||
<TableRow key={index} row={row as ValidRecord} index={index} isSelected={isSelected} />
|
key={index}
|
||||||
</View>
|
style={{
|
||||||
);
|
backgroundColor:
|
||||||
})}
|
isSelected && isFocused
|
||||||
|
? COLORS.focused_selected
|
||||||
|
: isFocused
|
||||||
|
? COLORS.focused
|
||||||
|
: isSelected
|
||||||
|
? COLORS.selected
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TableRow
|
||||||
|
key={index}
|
||||||
|
row={row as ValidRecord}
|
||||||
|
index={index}
|
||||||
|
isSelected={isSelected}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</View>
|
</View>
|
||||||
)
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RowProps<T> {
|
interface RowProps<T> {
|
||||||
@@ -123,19 +181,34 @@ interface RowProps<T> {
|
|||||||
function TableRow<T extends ValidRecord>({ row, isSelected }: RowProps<T>) {
|
function TableRow<T extends ValidRecord>({ row, isSelected }: RowProps<T>) {
|
||||||
const { columns, columnMap } = use(Context);
|
const { columns, columnMap } = use(Context);
|
||||||
|
|
||||||
|
return (
|
||||||
return <View style={{ flexDirection: 'row' }}>
|
<View style={{ flexDirection: "row" }}>
|
||||||
{columns.map(column => {
|
{columns.map((column) => {
|
||||||
const rendered = renderCell(row, column);
|
const rendered = renderCell(row, column);
|
||||||
return <Text key={column.name} style={{ fontFamily: 'mono', color: isSelected ? 'black' : 'black' }}>{rpad(rendered, columnMap.get(column.name)! - rendered.length + EXTRA)}</Text>;
|
return (
|
||||||
})}
|
<Text
|
||||||
</View>
|
key={column.name}
|
||||||
|
style={{
|
||||||
|
fontFamily: "mono",
|
||||||
|
color: isSelected ? "black" : "black",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{rpad(
|
||||||
|
rendered,
|
||||||
|
columnMap.get(column.name)! - rendered.length + EXTRA,
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function rpad(input: string, length: number): string {
|
function rpad(input: string, length: number): string {
|
||||||
return input + Array.from({ length })
|
return (
|
||||||
.map(_ => " ")
|
input +
|
||||||
.join("");
|
Array.from({ length })
|
||||||
|
.map((_) => " ")
|
||||||
|
.join("")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
41
packages/ui/lib/shortcuts/Debug.tsx
Normal file
41
packages/ui/lib/shortcuts/Debug.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { useSyncExternalStore } from "react";
|
||||||
|
import { View, Text } from "react-native";
|
||||||
|
import { keysStore, type ScopeKeys } from "./store";
|
||||||
|
|
||||||
|
export function ShortcutDebug() {
|
||||||
|
const entries = useSyncExternalStore(
|
||||||
|
keysStore.subscribe,
|
||||||
|
keysStore.getSnapshot,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
zIndex: 100,
|
||||||
|
bottom: 0,
|
||||||
|
right: 0,
|
||||||
|
backgroundColor: "black",
|
||||||
|
padding: 10,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text style={{ color: "red", fontFamily: "mono" }}>Scopes:</Text>
|
||||||
|
{entries.map(([scope, keys]) => (
|
||||||
|
<ScopeView key={scope} scope={scope} keys={keys} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ScopeView({ scope, keys }: { scope: string; keys: ScopeKeys }) {
|
||||||
|
return (
|
||||||
|
<Text style={{ color: "red", fontFamily: "mono", textAlign: "right" }}>
|
||||||
|
{scope}:
|
||||||
|
{keys
|
||||||
|
.entries()
|
||||||
|
.map(([key, _]) => key)
|
||||||
|
.toArray()
|
||||||
|
.join(",")}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
12
packages/ui/lib/shortcuts/Provider.tsx
Normal file
12
packages/ui/lib/shortcuts/Provider.tsx
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useKeyboard } from "@opentui/react";
|
||||||
|
import { keysStore } from "./store";
|
||||||
|
|
||||||
|
export function ShortcutProvider({ children }: { children: ReactNode }) {
|
||||||
|
useKeyboard((e) => {
|
||||||
|
const fn = keysStore.getHandler(e.name);
|
||||||
|
fn?.();
|
||||||
|
});
|
||||||
|
|
||||||
|
return children;
|
||||||
|
}
|
||||||
26
packages/ui/lib/shortcuts/Provider.web.tsx
Normal file
26
packages/ui/lib/shortcuts/Provider.web.tsx
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { keysStore } from "./store";
|
||||||
|
import type { KeyName } from "./types";
|
||||||
|
|
||||||
|
const KEY_MAP: { [k: string]: KeyName } = {
|
||||||
|
Escape: "escape",
|
||||||
|
ArrowUp: "up",
|
||||||
|
ArrowDown: "down",
|
||||||
|
ArrowLeft: "left",
|
||||||
|
ArrowRight: "right",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
window.addEventListener("keydown", (e) => {
|
||||||
|
const key = Object.hasOwn(KEY_MAP, e.key) ? KEY_MAP[e.key]! : e.key;
|
||||||
|
const fn = keysStore.getHandler(key);
|
||||||
|
// console.log(e.key);
|
||||||
|
if (!fn) return;
|
||||||
|
e.preventDefault();
|
||||||
|
fn();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShortcutProvider({ children }: { children: ReactNode }) {
|
||||||
|
return children;
|
||||||
|
}
|
||||||
22
packages/ui/lib/shortcuts/hooks.ts
Normal file
22
packages/ui/lib/shortcuts/hooks.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import { keysStore } from "./store";
|
||||||
|
import type { Key } from "./types";
|
||||||
|
import { enforceKeyOptions } from "./util";
|
||||||
|
|
||||||
|
export const useShortcut = (
|
||||||
|
key: Key,
|
||||||
|
handler: () => void,
|
||||||
|
scope: string = "global",
|
||||||
|
) => {
|
||||||
|
const keyOptions = enforceKeyOptions(key);
|
||||||
|
const keyName = keyOptions.name;
|
||||||
|
const ref = useRef(handler);
|
||||||
|
ref.current = handler;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
keysStore.register(keyName, ref, scope);
|
||||||
|
return () => {
|
||||||
|
keysStore.deregister(keyName, scope);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
};
|
||||||
4
packages/ui/lib/shortcuts/index.ts
Normal file
4
packages/ui/lib/shortcuts/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export * from "./Debug";
|
||||||
|
export * from "./Provider";
|
||||||
|
export * from "./hooks";
|
||||||
|
export * from "./types";
|
||||||
58
packages/ui/lib/shortcuts/store.ts
Normal file
58
packages/ui/lib/shortcuts/store.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { type RefObject } from "react";
|
||||||
|
|
||||||
|
export type ScopeKeys = Map<string, RefObject<() => void>>;
|
||||||
|
|
||||||
|
// outer reactive container
|
||||||
|
const scopes = new Map<string, ScopeKeys>();
|
||||||
|
|
||||||
|
// stable snapshot for subscribers
|
||||||
|
let snapshot: [string, ScopeKeys][] = [];
|
||||||
|
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function emit() {
|
||||||
|
// replace identity so subscribers re-render
|
||||||
|
snapshot = Array.from(scopes.entries());
|
||||||
|
for (const fn of listeners) fn();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const keysStore = {
|
||||||
|
subscribe(fn: () => void) {
|
||||||
|
listeners.add(fn);
|
||||||
|
return () => listeners.delete(fn);
|
||||||
|
},
|
||||||
|
|
||||||
|
getSnapshot() {
|
||||||
|
return snapshot;
|
||||||
|
},
|
||||||
|
|
||||||
|
register(key: string, ref: RefObject<() => void>, scope: string) {
|
||||||
|
const prev = scopes.get(scope);
|
||||||
|
const next = new Map(prev); // <-- important: new identity
|
||||||
|
next.set(key, ref);
|
||||||
|
|
||||||
|
scopes.set(scope, next); // <-- outer identity also changes
|
||||||
|
emit();
|
||||||
|
},
|
||||||
|
|
||||||
|
deregister(key: string, scope: string) {
|
||||||
|
const prev = scopes.get(scope);
|
||||||
|
if (!prev) return;
|
||||||
|
|
||||||
|
const next = new Map(prev);
|
||||||
|
next.delete(key);
|
||||||
|
|
||||||
|
if (next.size === 0) {
|
||||||
|
scopes.delete(scope);
|
||||||
|
} else {
|
||||||
|
scopes.set(scope, next);
|
||||||
|
}
|
||||||
|
emit();
|
||||||
|
},
|
||||||
|
|
||||||
|
getHandler(key: string) {
|
||||||
|
// last scope wins — clarify this logic as needed
|
||||||
|
const last = Array.from(scopes.values()).at(-1);
|
||||||
|
return last?.get(key)?.current;
|
||||||
|
},
|
||||||
|
};
|
||||||
52
packages/ui/lib/shortcuts/types.ts
Normal file
52
packages/ui/lib/shortcuts/types.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
export type KeyName =
|
||||||
|
| "0"
|
||||||
|
| "1"
|
||||||
|
| "2"
|
||||||
|
| "3"
|
||||||
|
| "4"
|
||||||
|
| "5"
|
||||||
|
| "6"
|
||||||
|
| "7"
|
||||||
|
| "8"
|
||||||
|
| "9"
|
||||||
|
| "a"
|
||||||
|
| "b"
|
||||||
|
| "c"
|
||||||
|
| "d"
|
||||||
|
| "e"
|
||||||
|
| "f"
|
||||||
|
| "g"
|
||||||
|
| "h"
|
||||||
|
| "i"
|
||||||
|
| "j"
|
||||||
|
| "k"
|
||||||
|
| "l"
|
||||||
|
| "m"
|
||||||
|
| "n"
|
||||||
|
| "o"
|
||||||
|
| "p"
|
||||||
|
| "q"
|
||||||
|
| "r"
|
||||||
|
| "s"
|
||||||
|
| "t"
|
||||||
|
| "u"
|
||||||
|
| "v"
|
||||||
|
| "w"
|
||||||
|
| "x"
|
||||||
|
| "y"
|
||||||
|
| "z"
|
||||||
|
| ":"
|
||||||
|
| "up"
|
||||||
|
| "down"
|
||||||
|
| "left"
|
||||||
|
| "right"
|
||||||
|
| "return"
|
||||||
|
| "escape";
|
||||||
|
|
||||||
|
export type Key = KeyName | KeyOptions;
|
||||||
|
|
||||||
|
export interface KeyOptions {
|
||||||
|
name: KeyName;
|
||||||
|
ctrl?: boolean;
|
||||||
|
shift?: boolean;
|
||||||
|
}
|
||||||
9
packages/ui/lib/shortcuts/util.ts
Normal file
9
packages/ui/lib/shortcuts/util.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { Key, KeyOptions } from "./types";
|
||||||
|
|
||||||
|
export function enforceKeyOptions(key: Key): KeyOptions {
|
||||||
|
return typeof key == "string"
|
||||||
|
? {
|
||||||
|
name: key,
|
||||||
|
}
|
||||||
|
: key;
|
||||||
|
}
|
||||||
160
packages/ui/src/budget.tsx
Normal file
160
packages/ui/src/budget.tsx
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
import { use, useRef, useState } from "react";
|
||||||
|
import { View, Text, TextInput } from "react-native";
|
||||||
|
import { RouterContext } from ".";
|
||||||
|
import {
|
||||||
|
queries,
|
||||||
|
type Category,
|
||||||
|
type Mutators,
|
||||||
|
type Schema,
|
||||||
|
} from "@money/shared";
|
||||||
|
import { useQuery, useZero } from "@rocicorp/zero/react";
|
||||||
|
import * as Table from "../components/Table";
|
||||||
|
import { Button } from "../components/Button";
|
||||||
|
import { RenameCategoryDialog } from "./budget/RenameCategoryDialog";
|
||||||
|
import {
|
||||||
|
UpdateCategoryAmountDialog,
|
||||||
|
type CategoryWithComputed,
|
||||||
|
type Updating,
|
||||||
|
} from "./budget/UpdateCategoryAmountDialog";
|
||||||
|
|
||||||
|
const COLUMNS: Table.Column[] = [
|
||||||
|
{ name: "label", label: "Name" },
|
||||||
|
{ name: "week", label: "Week" },
|
||||||
|
{ name: "month", label: "Month" },
|
||||||
|
{ name: "year", label: "Year" },
|
||||||
|
{ name: "order", label: "Order" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Budget() {
|
||||||
|
const { auth } = use(RouterContext);
|
||||||
|
const [budgets] = useQuery(queries.getBudgets(auth));
|
||||||
|
const [renaming, setRenaming] = useState<Category>();
|
||||||
|
const [editCategoryAmount, setEditCategoryAmount] = useState<Updating>();
|
||||||
|
|
||||||
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
|
const newBudget = () => {
|
||||||
|
const id = new Date().getTime().toString();
|
||||||
|
const categoryId = new Date().getTime().toString();
|
||||||
|
z.mutate.budget.create({
|
||||||
|
id,
|
||||||
|
categoryId,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (budgets.length == 0)
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
flex: 1,
|
||||||
|
gap: 10,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
No budgets, please create a new budget
|
||||||
|
</Text>
|
||||||
|
<Button onPress={newBudget} shortcut="n">
|
||||||
|
New budget
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
|
||||||
|
const budget = budgets[0]!;
|
||||||
|
|
||||||
|
const data = budget.categories.slice().map((category) => {
|
||||||
|
const { amount } = category;
|
||||||
|
const week = amount / 4;
|
||||||
|
const month = amount;
|
||||||
|
const year = amount * 12;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...category,
|
||||||
|
...{
|
||||||
|
week,
|
||||||
|
month,
|
||||||
|
year,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const newCategory = ({ index }: { index: number }) => {
|
||||||
|
const id = new Date().getTime().toString();
|
||||||
|
z.mutate.budget.createCategory({
|
||||||
|
id,
|
||||||
|
budgetId: budget.id,
|
||||||
|
order: index,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteCategory = ({ selected }: { selected: { id: string }[] }) => {
|
||||||
|
for (const { id } of selected) {
|
||||||
|
z.mutate.budget.deleteCategory({ id });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renameCategory = ({ selected }: { selected: Category[] }) => {
|
||||||
|
for (const category of selected) {
|
||||||
|
setRenaming(category);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEditCategoryYearly = ({
|
||||||
|
selected,
|
||||||
|
}: { selected: CategoryWithComputed[] }) => {
|
||||||
|
for (const category of selected) {
|
||||||
|
setEditCategoryAmount({ category, every: "year" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEditCategoryMonthly = ({
|
||||||
|
selected,
|
||||||
|
}: { selected: CategoryWithComputed[] }) => {
|
||||||
|
for (const category of selected) {
|
||||||
|
setEditCategoryAmount({ category, every: "month" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEditCategoryWeekly = ({
|
||||||
|
selected,
|
||||||
|
}: { selected: CategoryWithComputed[] }) => {
|
||||||
|
for (const category of selected) {
|
||||||
|
setEditCategoryAmount({ category, every: "week" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<RenameCategoryDialog renaming={renaming} setRenaming={setRenaming} />
|
||||||
|
<UpdateCategoryAmountDialog
|
||||||
|
updating={editCategoryAmount}
|
||||||
|
setUpdating={setEditCategoryAmount}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<View style={{ alignItems: "flex-start" }}>
|
||||||
|
<Text style={{ fontFamily: "mono", textAlign: "left" }}>
|
||||||
|
Selected Budget: {budget.label}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Table.Provider
|
||||||
|
data={data}
|
||||||
|
columns={COLUMNS}
|
||||||
|
shortcuts={[
|
||||||
|
{ key: "i", handler: newCategory },
|
||||||
|
{ key: "d", handler: deleteCategory },
|
||||||
|
{ key: "r", handler: renameCategory },
|
||||||
|
{ key: "y", handler: onEditCategoryYearly },
|
||||||
|
{ key: "m", handler: onEditCategoryMonthly },
|
||||||
|
{ key: "w", handler: onEditCategoryWeekly },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<View style={{ flex: 1 }}>
|
||||||
|
<View style={{ flexShrink: 0 }}>
|
||||||
|
<Table.Body />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</Table.Provider>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
77
packages/ui/src/budget/RenameCategoryDialog.tsx
Normal file
77
packages/ui/src/budget/RenameCategoryDialog.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import * as Dialog from "../../components/Dialog";
|
||||||
|
import { View, Text, TextInput } from "react-native";
|
||||||
|
import { type Category, type Mutators, type Schema } from "@money/shared";
|
||||||
|
import { useZero } from "@rocicorp/zero/react";
|
||||||
|
|
||||||
|
interface RenameCategoryDialogProps {
|
||||||
|
renaming: Category | undefined;
|
||||||
|
setRenaming: (v: Category | undefined) => void;
|
||||||
|
}
|
||||||
|
export function RenameCategoryDialog({
|
||||||
|
renaming,
|
||||||
|
setRenaming,
|
||||||
|
}: RenameCategoryDialogProps) {
|
||||||
|
const refText = useRef("");
|
||||||
|
const [renamingText, setRenamingText] = useState("");
|
||||||
|
|
||||||
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog.Provider
|
||||||
|
visible={renaming != undefined}
|
||||||
|
close={() => setRenaming(undefined)}
|
||||||
|
>
|
||||||
|
<Dialog.Content>
|
||||||
|
<View style={{ width: 400 }}>
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
paddingTop: 12,
|
||||||
|
paddingLeft: 12,
|
||||||
|
paddingRight: 12,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TextInput
|
||||||
|
style={{
|
||||||
|
fontFamily: "mono",
|
||||||
|
// @ts-ignore
|
||||||
|
outline: "none",
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
selectTextOnFocus
|
||||||
|
defaultValue={renaming?.label}
|
||||||
|
onChangeText={(t) => {
|
||||||
|
refText.current = t;
|
||||||
|
setRenamingText(t);
|
||||||
|
}}
|
||||||
|
onKeyPress={(e) => {
|
||||||
|
if (!renaming) return;
|
||||||
|
if (e.nativeEvent.key == "Enter") {
|
||||||
|
if (refText.current.trim() == "")
|
||||||
|
return setRenaming(undefined);
|
||||||
|
z.mutate.budget.updateCategory({
|
||||||
|
id: renaming.id,
|
||||||
|
label: refText.current,
|
||||||
|
});
|
||||||
|
setRenaming(undefined);
|
||||||
|
} else if (e.nativeEvent.key == "Escape") {
|
||||||
|
setRenaming(undefined);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View
|
||||||
|
style={{ paddingLeft: 12, paddingRight: 12, paddingBottom: 12 }}
|
||||||
|
>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
→ Rename category to: {renamingText || renaming?.label}
|
||||||
|
</Text>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>→ Cancel</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
107
packages/ui/src/budget/UpdateCategoryAmountDialog.tsx
Normal file
107
packages/ui/src/budget/UpdateCategoryAmountDialog.tsx
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import * as Dialog from "../../components/Dialog";
|
||||||
|
import { View, Text, TextInput } from "react-native";
|
||||||
|
import { type Category, type Mutators, type Schema } from "@money/shared";
|
||||||
|
import { useZero } from "@rocicorp/zero/react";
|
||||||
|
|
||||||
|
export type Updating = {
|
||||||
|
category: CategoryWithComputed;
|
||||||
|
every: Category["every"];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CategoryWithComputed = Category & {
|
||||||
|
month: number;
|
||||||
|
year: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface UpdateCategoryAmountDialogProps {
|
||||||
|
updating: Updating | undefined;
|
||||||
|
setUpdating: (v: Updating | undefined) => void;
|
||||||
|
}
|
||||||
|
export function UpdateCategoryAmountDialog({
|
||||||
|
updating,
|
||||||
|
setUpdating,
|
||||||
|
}: UpdateCategoryAmountDialogProps) {
|
||||||
|
const category = updating?.category;
|
||||||
|
const every = updating?.every;
|
||||||
|
|
||||||
|
const refText = useRef("");
|
||||||
|
const [amountText, setAmountText] = useState("");
|
||||||
|
|
||||||
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog.Provider
|
||||||
|
visible={category != undefined}
|
||||||
|
close={() => setUpdating(undefined)}
|
||||||
|
>
|
||||||
|
<Dialog.Content>
|
||||||
|
<View style={{ width: 400 }}>
|
||||||
|
<View
|
||||||
|
style={{
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
paddingTop: 12,
|
||||||
|
paddingLeft: 12,
|
||||||
|
paddingRight: 12,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TextInput
|
||||||
|
style={{
|
||||||
|
fontFamily: "mono",
|
||||||
|
// @ts-ignore
|
||||||
|
outline: "none",
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
selectTextOnFocus
|
||||||
|
defaultValue={category?.month.toString()}
|
||||||
|
onChangeText={(t) => {
|
||||||
|
refText.current = t;
|
||||||
|
setAmountText(t);
|
||||||
|
}}
|
||||||
|
onKeyPress={(e) => {
|
||||||
|
if (!category) return;
|
||||||
|
if (e.nativeEvent.key == "Enter") {
|
||||||
|
if (refText.current.trim() == "")
|
||||||
|
return setUpdating(undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = parseFloat(refText.current);
|
||||||
|
|
||||||
|
const amount = (function () {
|
||||||
|
switch (every) {
|
||||||
|
case "year":
|
||||||
|
return parsed / 12;
|
||||||
|
case "month":
|
||||||
|
return parsed;
|
||||||
|
case "week":
|
||||||
|
return parsed * 4;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
z.mutate.budget.updateCategory({
|
||||||
|
id: category.id,
|
||||||
|
amount,
|
||||||
|
every,
|
||||||
|
});
|
||||||
|
setUpdating(undefined);
|
||||||
|
} catch (e) {}
|
||||||
|
} else if (e.nativeEvent.key == "Escape") {
|
||||||
|
setUpdating(undefined);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
<View
|
||||||
|
style={{ paddingLeft: 12, paddingRight: 12, paddingBottom: 12 }}
|
||||||
|
>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
→ Update monthly amount to: {amountText || category?.month}
|
||||||
|
</Text>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>→ Cancel</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,43 +1,52 @@
|
|||||||
import { createContext, use } from "react";
|
import { createContext, use, type ReactNode } from "react";
|
||||||
import { Transactions } from "./transactions";
|
import { Transactions } from "./transactions";
|
||||||
import { View, Text } from "react-native";
|
import { View } from "react-native";
|
||||||
import { Settings } from "./settings";
|
import { Settings } from "./settings";
|
||||||
import { useKeyboard } from "./useKeyboard";
|
|
||||||
import type { AuthData } from "@money/shared/auth";
|
import type { AuthData } from "@money/shared/auth";
|
||||||
|
import { Budget } from "./budget";
|
||||||
|
import {
|
||||||
|
ShortcutProvider,
|
||||||
|
ShortcutDebug,
|
||||||
|
useShortcut,
|
||||||
|
type KeyName,
|
||||||
|
} from "../lib/shortcuts";
|
||||||
|
|
||||||
const PAGES = {
|
const PAGES = {
|
||||||
'/': {
|
"/": {
|
||||||
screen: <Transactions />,
|
screen: <Transactions />,
|
||||||
key: "1",
|
key: "1",
|
||||||
},
|
},
|
||||||
'/settings': {
|
"/budget": {
|
||||||
screen: <Settings />,
|
screen: <Budget />,
|
||||||
key: "2",
|
key: "2",
|
||||||
|
},
|
||||||
|
"/settings": {
|
||||||
|
screen: <Settings />,
|
||||||
|
key: "3",
|
||||||
children: {
|
children: {
|
||||||
"/accounts": {},
|
"/accounts": {},
|
||||||
"/family": {},
|
"/family": {},
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
};
|
} satisfies Record<
|
||||||
|
string,
|
||||||
|
{ screen: ReactNode; key: KeyName; children?: Record<string, unknown> }
|
||||||
|
>;
|
||||||
|
|
||||||
type Join<A extends string, B extends string> =
|
type Join<A extends string, B extends string> = `${A}${B}` extends `${infer X}`
|
||||||
`${A}${B}` extends `${infer X}` ? X : never;
|
? X
|
||||||
|
: never;
|
||||||
|
|
||||||
type ChildRoutes<Parent extends string, Children> =
|
type ChildRoutes<Parent extends string, Children> = {
|
||||||
{
|
[K in keyof Children & string]: K extends `/${string}`
|
||||||
[K in keyof Children & string]:
|
? Join<Parent, K>
|
||||||
K extends `/${string}`
|
: never;
|
||||||
? Join<Parent, K>
|
}[keyof Children & string];
|
||||||
: never;
|
|
||||||
}[keyof Children & string];
|
|
||||||
|
|
||||||
type Routes<T> = {
|
type Routes<T> = {
|
||||||
[K in keyof T & string]:
|
[K in keyof T & string]:
|
||||||
| K
|
| K
|
||||||
| (T[K] extends { children: infer C }
|
| (T[K] extends { children: infer C } ? ChildRoutes<K, C> : never);
|
||||||
? ChildRoutes<K, C>
|
|
||||||
: never)
|
|
||||||
}[keyof T & string];
|
}[keyof T & string];
|
||||||
|
|
||||||
export type Route = Routes<typeof PAGES>;
|
export type Route = Routes<typeof PAGES>;
|
||||||
@@ -48,49 +57,46 @@ interface RouterContextType {
|
|||||||
setRoute: (route: Route) => void;
|
setRoute: (route: Route) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const RouterContext = createContext<RouterContextType>({
|
export const RouterContext = createContext<RouterContextType>({
|
||||||
auth: null,
|
auth: null,
|
||||||
route: '/',
|
route: "/",
|
||||||
setRoute: () => {}
|
setRoute: () => {},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
type AppProps = {
|
type AppProps = {
|
||||||
auth: AuthData | null;
|
auth: AuthData | null;
|
||||||
route: Route;
|
route: Route;
|
||||||
setRoute: (page: Route) => void;
|
setRoute: (page: Route) => void;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function App({ auth, route, setRoute }: AppProps) {
|
export function App({ auth, route, setRoute }: AppProps) {
|
||||||
return <RouterContext.Provider value={{ auth, route, setRoute }}>
|
return (
|
||||||
<Main />
|
<RouterContext.Provider value={{ auth, route, setRoute }}>
|
||||||
</RouterContext.Provider>
|
<ShortcutProvider>
|
||||||
|
<ShortcutDebug />
|
||||||
|
<Main />
|
||||||
|
</ShortcutProvider>
|
||||||
|
</RouterContext.Provider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Main() {
|
function Main() {
|
||||||
const { route, setRoute } = use(RouterContext);
|
const { route, setRoute } = use(RouterContext);
|
||||||
|
|
||||||
useKeyboard((key) => {
|
for (const [route, page] of Object.entries(PAGES)) {
|
||||||
const screen = Object.entries(PAGES)
|
useShortcut(page.key, () => setRoute(route as Route));
|
||||||
.find(([, screen]) => screen.key == key.name);
|
}
|
||||||
|
|
||||||
if (!screen) return;
|
|
||||||
|
|
||||||
const [route] = screen as [Route, never];
|
|
||||||
|
|
||||||
setRoute(route);
|
|
||||||
});
|
|
||||||
|
|
||||||
const match =
|
const match =
|
||||||
route in PAGES
|
route in PAGES
|
||||||
? (route as keyof typeof PAGES)
|
? (route as keyof typeof PAGES)
|
||||||
: (Object.keys(PAGES).sort((a, b) => b.length - a.length).find(p => route.startsWith(p)) as
|
: (Object.keys(PAGES)
|
||||||
keyof typeof PAGES);
|
.sort((a, b) => b.length - a.length)
|
||||||
|
.find((p) => route.startsWith(p)) as keyof typeof PAGES);
|
||||||
|
|
||||||
return <View style={{ backgroundColor: 'white', flex: 1 }}>
|
return (
|
||||||
{PAGES[match].screen}
|
<View style={{ backgroundColor: "white", flex: 1 }}>
|
||||||
</View>
|
{PAGES[match].screen}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,66 +4,79 @@ import { RouterContext, type Route } from ".";
|
|||||||
import { General } from "./settings/general";
|
import { General } from "./settings/general";
|
||||||
import { Accounts } from "./settings/accounts";
|
import { Accounts } from "./settings/accounts";
|
||||||
import { Family } from "./settings/family";
|
import { Family } from "./settings/family";
|
||||||
import { useKeyboard } from "./useKeyboard";
|
import { useShortcut } from "../lib/shortcuts";
|
||||||
import { Modal } from "react-native-opentui";
|
|
||||||
|
|
||||||
type SettingsRoute = Extract<Route, `/settings${string}`>;
|
type SettingsRoute = Extract<Route, `/settings${string}`>;
|
||||||
|
|
||||||
const TABS = {
|
const TABS = {
|
||||||
"/settings": {
|
"/settings": {
|
||||||
label: "💽 General",
|
label: "💽 General",
|
||||||
screen: <General />
|
screen: <General />,
|
||||||
},
|
},
|
||||||
"/settings/accounts": {
|
"/settings/accounts": {
|
||||||
label: "🏦 Bank Accounts",
|
label: "🏦 Bank Accounts",
|
||||||
screen: <Accounts />
|
screen: <Accounts />,
|
||||||
},
|
},
|
||||||
"/settings/family": {
|
"/settings/family": {
|
||||||
label: "👑 Family",
|
label: "👑 Family",
|
||||||
screen: <Family />
|
screen: <Family />,
|
||||||
},
|
},
|
||||||
} as const satisfies Record<SettingsRoute, { label: string, screen: ReactNode }>;
|
} as const satisfies Record<
|
||||||
|
SettingsRoute,
|
||||||
|
{ label: string; screen: ReactNode }
|
||||||
|
>;
|
||||||
|
|
||||||
type Tab = keyof typeof TABS;
|
type Tab = keyof typeof TABS;
|
||||||
|
|
||||||
export function Settings() {
|
export function Settings() {
|
||||||
const { route, setRoute } = use(RouterContext);
|
const { route, setRoute } = use(RouterContext);
|
||||||
|
|
||||||
useKeyboard((key) => {
|
useShortcut("h", () => {
|
||||||
if (key.name == 'h') {
|
const currentIdx = Object.entries(TABS).findIndex(
|
||||||
const currentIdx = Object.entries(TABS).findIndex(([tabRoute, _]) => tabRoute == route)
|
([tabRoute, _]) => tabRoute == route,
|
||||||
const routes = Object.keys(TABS) as SettingsRoute[];
|
);
|
||||||
const last = routes[currentIdx - 1]
|
const routes = Object.keys(TABS) as SettingsRoute[];
|
||||||
if (!last) return;
|
const last = routes[currentIdx - 1];
|
||||||
setRoute(last);
|
if (!last) return;
|
||||||
} else if (key.name == 'l') {
|
setRoute(last);
|
||||||
const currentIdx = Object.entries(TABS).findIndex(([tabRoute, _]) => tabRoute == route)
|
});
|
||||||
const routes = Object.keys(TABS) as SettingsRoute[];
|
useShortcut("l", () => {
|
||||||
const next = routes[currentIdx + 1]
|
const currentIdx = Object.entries(TABS).findIndex(
|
||||||
if (!next) return;
|
([tabRoute, _]) => tabRoute == route,
|
||||||
setRoute(next);
|
);
|
||||||
}
|
const routes = Object.keys(TABS) as SettingsRoute[];
|
||||||
}, [route]);
|
const next = routes[currentIdx + 1];
|
||||||
|
if (!next) return;
|
||||||
|
setRoute(next);
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={{ flexDirection: "row" }}>
|
<View style={{ flexDirection: "row" }}>
|
||||||
|
|
||||||
<View style={{ padding: 10 }}>
|
<View style={{ padding: 10 }}>
|
||||||
{Object.entries(TABS).map(([tabRoute, tab]) => {
|
{Object.entries(TABS).map(([tabRoute, tab]) => {
|
||||||
const isSelected = tabRoute == route;
|
const isSelected = tabRoute == route;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Pressable key={tab.label} style={{ backgroundColor: isSelected ? 'black' : undefined }} onPress={() => setRoute(tabRoute as SettingsRoute)}>
|
<Pressable
|
||||||
<Text style={{ fontFamily: 'mono', color: isSelected ? 'white' : 'black' }}> {tab.label} </Text>
|
key={tab.label}
|
||||||
|
style={{ backgroundColor: isSelected ? "black" : undefined }}
|
||||||
|
onPress={() => setRoute(tabRoute as SettingsRoute)}
|
||||||
|
>
|
||||||
|
<Text
|
||||||
|
style={{
|
||||||
|
fontFamily: "mono",
|
||||||
|
color: isSelected ? "white" : "black",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{" "}
|
||||||
|
{tab.label}{" "}
|
||||||
|
</Text>
|
||||||
</Pressable>
|
</Pressable>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View>
|
<View>{TABS[route as Tab].screen}</View>
|
||||||
{TABS[route as Tab].screen}
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
import { useQuery, useZero } from "@rocicorp/zero/react";
|
import { useQuery, useZero } from "@rocicorp/zero/react";
|
||||||
import { queries, type Mutators, type Schema } from '@money/shared';
|
import { queries, type Mutators, type Schema } from "@money/shared";
|
||||||
import { use, useEffect, useState } from "react";
|
import { use, useEffect, useState } from "react";
|
||||||
import { RouterContext } from "..";
|
import { RouterContext } from "..";
|
||||||
import { View, Text, Linking } from "react-native";
|
import { View, Text, Linking } from "react-native";
|
||||||
import { useKeyboard } from "../useKeyboard";
|
|
||||||
import { Button } from "../../components/Button";
|
import { Button } from "../../components/Button";
|
||||||
import * as Table from "../../components/Table";
|
import * as Table from "../../components/Table";
|
||||||
import * as Dialog from "../../components/Dialog";
|
import * as Dialog from "../../components/Dialog";
|
||||||
|
|
||||||
const COLUMNS: Table.Column[] = [
|
const COLUMNS: Table.Column[] = [
|
||||||
{ name: 'name', label: 'Name' },
|
{ name: "name", label: "Name" },
|
||||||
{ name: 'createdAt', label: 'Added At', render: (n) => new Date(n).toLocaleString() },
|
{
|
||||||
|
name: "createdAt",
|
||||||
|
label: "Added At",
|
||||||
|
render: (n) => new Date(n).toLocaleString(),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export function Accounts() {
|
export function Accounts() {
|
||||||
@@ -21,75 +24,89 @@ export function Accounts() {
|
|||||||
|
|
||||||
const z = useZero<Schema, Mutators>();
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
|
|
||||||
// useKeyboard((key) => {
|
|
||||||
// if (key.name == 'n') {
|
|
||||||
// setDeleting([]);
|
|
||||||
// } else if (key.name == 'y') {
|
|
||||||
// onDelete();
|
|
||||||
// }
|
|
||||||
// }, [deleting]);
|
|
||||||
|
|
||||||
const onDelete = () => {
|
const onDelete = () => {
|
||||||
if (!deleting) return
|
if (!deleting) return;
|
||||||
const accountIds = deleting.map(account => account.id);
|
const accountIds = deleting.map((account) => account.id);
|
||||||
z.mutate.link.deleteAccounts({ accountIds });
|
z.mutate.link.deleteAccounts({ accountIds });
|
||||||
setDeleting([]);
|
setDeleting([]);
|
||||||
}
|
};
|
||||||
|
|
||||||
const addAccount = () => {
|
const addAccount = () => {
|
||||||
setIsAddOpen(true);
|
setIsAddOpen(true);
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<Dialog.Provider
|
||||||
<Dialog.Provider visible={!deleting} close={() => setDeleting([])}>
|
visible={deleting.length > 0}
|
||||||
|
close={() => setDeleting([])}
|
||||||
|
>
|
||||||
<Dialog.Content>
|
<Dialog.Content>
|
||||||
<Text style={{ fontFamily: 'mono' }}>Delete Account</Text>
|
<Text style={{ fontFamily: "mono" }}>Delete Account</Text>
|
||||||
<Text style={{ fontFamily: 'mono' }}> </Text>
|
<Text style={{ fontFamily: "mono" }}> </Text>
|
||||||
<Text style={{ fontFamily: 'mono' }}>You are about to delete the following accounts:</Text>
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
You are about to delete the following accounts:
|
||||||
|
</Text>
|
||||||
|
|
||||||
<View>
|
<View>
|
||||||
{deleting.map(account => <Text style={{ fontFamily: 'mono' }}>- {account.name}</Text>)}
|
{deleting.map((account) => (
|
||||||
|
<Text style={{ fontFamily: "mono" }}>- {account.name}</Text>
|
||||||
|
))}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<Text style={{ fontFamily: 'mono' }}> </Text>
|
<Text style={{ fontFamily: "mono" }}> </Text>
|
||||||
|
|
||||||
<View style={{ flexDirection: 'row' }}>
|
<View style={{ flexDirection: "row" }}>
|
||||||
<Button variant="secondary" onPress={() => { setDeleting([]); }}>Cancel (n)</Button>
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
onPress={() => {
|
||||||
|
setDeleting([]);
|
||||||
|
}}
|
||||||
|
shortcut="n"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
|
||||||
<Text style={{ fontFamily: 'mono' }}> </Text>
|
<Text style={{ fontFamily: "mono" }}> </Text>
|
||||||
|
|
||||||
<Button variant="destructive" onPress={() => {
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onPress={() => {
|
||||||
onDelete();
|
onDelete();
|
||||||
}}>Delete (y)</Button>
|
}}
|
||||||
|
shortcut="y"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
</Dialog.Content>
|
</Dialog.Content>
|
||||||
</Dialog.Provider>
|
</Dialog.Provider>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<Dialog.Provider visible={isAddOpen} close={() => setIsAddOpen(false)}>
|
<Dialog.Provider visible={isAddOpen} close={() => setIsAddOpen(false)}>
|
||||||
<Dialog.Content>
|
<Dialog.Content>
|
||||||
<Text style={{ fontFamily: 'mono' }}>Add Account</Text>
|
<Text style={{ fontFamily: "mono" }}>Add Account</Text>
|
||||||
<AddAccount />
|
<AddAccount />
|
||||||
</Dialog.Content>
|
</Dialog.Content>
|
||||||
</Dialog.Provider>
|
</Dialog.Provider>
|
||||||
|
|
||||||
<View style={{ padding: 10 }}>
|
<View style={{ padding: 10 }}>
|
||||||
|
|
||||||
<View style={{ alignSelf: "flex-start" }}>
|
<View style={{ alignSelf: "flex-start" }}>
|
||||||
<Button shortcut="a" onPress={addAccount}>Add Account</Button>
|
<Button shortcut="a" onPress={addAccount}>
|
||||||
|
Add Account
|
||||||
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<Text style={{ fontFamily: 'mono' }}> </Text>
|
<Text style={{ fontFamily: "mono" }}> </Text>
|
||||||
|
|
||||||
<Table.Provider columns={COLUMNS} data={items} onKey={(key, selected) => {
|
<Table.Provider
|
||||||
if (key.name == 'd') {
|
columns={COLUMNS}
|
||||||
setDeleting(selected);
|
data={items}
|
||||||
}
|
onKey={(key, selected) => {
|
||||||
}}>
|
if (key.name == "d") {
|
||||||
|
setDeleting(selected);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Table.Body />
|
<Table.Body />
|
||||||
</Table.Provider>
|
</Table.Provider>
|
||||||
</View>
|
</View>
|
||||||
@@ -97,34 +114,53 @@ export function Accounts() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function AddAccount() {
|
function AddAccount() {
|
||||||
const { auth } = use(RouterContext);
|
const { auth } = use(RouterContext);
|
||||||
const [link, details] = useQuery(queries.getPlaidLink(auth));
|
const [link, details] = useQuery(queries.getPlaidLink(auth));
|
||||||
|
const { close } = use(Dialog.Context);
|
||||||
|
|
||||||
const openLink = () => {
|
const openLink = () => {
|
||||||
if (!link) return
|
if (!link) return;
|
||||||
Linking.openURL(link.link);
|
Linking.openURL(link.link);
|
||||||
}
|
};
|
||||||
|
|
||||||
const z = useZero<Schema, Mutators>();
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log(link, details);
|
console.log(link, details);
|
||||||
if (details.type != "complete") return;
|
if (details.type != "complete") return;
|
||||||
if (link != undefined) return;
|
if (link != undefined) {
|
||||||
|
if (!link.completeAt) {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
console.log("Checking for link");
|
||||||
|
z.mutate.link.get({ link_token: link.token });
|
||||||
|
}, 1000 * 5);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
} else {
|
||||||
|
if (close) close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
console.log("Creating new link");
|
console.log("Creating new link");
|
||||||
z.mutate.link.create();
|
z.mutate.link.create();
|
||||||
}, [link, details]);
|
}, [link, details]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{link ? <>
|
<Button onPress={() => close && close()}>close</Button>
|
||||||
<Text style={{ fontFamily: 'mono' }}>Please click the button to complete setup.</Text>
|
{link ? (
|
||||||
|
<>
|
||||||
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
Please click the button to complete setup.
|
||||||
|
</Text>
|
||||||
|
|
||||||
<Button shortcut="return" onPress={openLink}>Open Plaid</Button>
|
<Button shortcut="return" onPress={openLink}>
|
||||||
</> : <Text style={{ fontFamily: 'mono' }}>Loading Plaid Link</Text>}
|
Open Plaid
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Text style={{ fontFamily: "mono" }}>Loading Plaid Link</Text>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Text } from "react-native";
|
import { Text } from "react-native";
|
||||||
|
|
||||||
export function Family() {
|
export function Family() {
|
||||||
return <Text style={{ fontFamily: 'mono' }}>Welcome to family</Text>
|
return <Text style={{ fontFamily: "mono" }}>Welcome to family</Text>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { Text } from "react-native";
|
import { Text } from "react-native";
|
||||||
|
|
||||||
export function General() {
|
export function General() {
|
||||||
return <Text style={{ fontFamily: 'mono' }}>Welcome to settings</Text>
|
return <Text style={{ fontFamily: "mono" }}>Welcome to settings</Text>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import * as Table from "../components/Table";
|
import * as Table from "../components/Table";
|
||||||
import { useQuery } from "@rocicorp/zero/react";
|
import { useQuery, useZero } from "@rocicorp/zero/react";
|
||||||
import { queries, type Transaction } from '@money/shared';
|
import {
|
||||||
|
queries,
|
||||||
|
type Mutators,
|
||||||
|
type Schema,
|
||||||
|
type Transaction,
|
||||||
|
} from "@money/shared";
|
||||||
import { use } from "react";
|
import { use } from "react";
|
||||||
import { View, Text } from "react-native";
|
import { View, Text } from "react-native";
|
||||||
import { RouterContext } from ".";
|
import { RouterContext } from ".";
|
||||||
|
|
||||||
|
|
||||||
const FORMAT = new Intl.NumberFormat("en-US", {
|
const FORMAT = new Intl.NumberFormat("en-US", {
|
||||||
minimumFractionDigits: 2,
|
minimumFractionDigits: 2,
|
||||||
maximumFractionDigits: 2,
|
maximumFractionDigits: 2,
|
||||||
@@ -14,23 +18,32 @@ const FORMAT = new Intl.NumberFormat("en-US", {
|
|||||||
export type Account = {
|
export type Account = {
|
||||||
name: string;
|
name: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
}
|
};
|
||||||
|
|
||||||
const COLUMNS: Table.Column[] = [
|
const COLUMNS: Table.Column[] = [
|
||||||
{ name: 'createdAt', label: 'Date', render: (n) => new Date(n).toDateString() },
|
{
|
||||||
{ name: 'amount', label: 'Amount' },
|
name: "createdAt",
|
||||||
{ name: 'name', label: 'Name' },
|
label: "Date",
|
||||||
|
render: (n) => new Date(n).toDateString(),
|
||||||
|
},
|
||||||
|
{ name: "amount", label: "Amount" },
|
||||||
|
{ name: "name", label: "Name" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
||||||
export function Transactions() {
|
export function Transactions() {
|
||||||
const { auth } = use(RouterContext);
|
const { auth } = use(RouterContext);
|
||||||
const [items] = useQuery(queries.allTransactions(auth));
|
const [items] = useQuery(queries.allTransactions(auth));
|
||||||
|
|
||||||
|
const z = useZero<Schema, Mutators>();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Table.Provider data={items} columns={COLUMNS}>
|
<Table.Provider
|
||||||
<View style={{ flex: 1 }}>
|
data={items}
|
||||||
<View style={{ flexShrink: 0}}>
|
columns={COLUMNS}
|
||||||
|
shortcuts={[{ key: "r", handler: () => z.mutate.link.sync() }]}
|
||||||
|
>
|
||||||
|
<View style={{ padding: 10, flex: 1 }}>
|
||||||
|
<View style={{ flexShrink: 0 }}>
|
||||||
<Table.Body />
|
<Table.Body />
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
@@ -38,30 +51,29 @@ export function Transactions() {
|
|||||||
<Selected />
|
<Selected />
|
||||||
</View>
|
</View>
|
||||||
</Table.Provider>
|
</Table.Provider>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Selected() {
|
function Selected() {
|
||||||
const { data, idx, selectedFrom } = use(Table.Context);
|
const { data, selectedIdx } = use(Table.Context);
|
||||||
|
|
||||||
if (selectedFrom == undefined)
|
if (selectedIdx.size == 0)
|
||||||
return (
|
return (
|
||||||
<View style={{ backgroundColor: '#ddd' }}>
|
<View style={{ backgroundColor: "#ddd" }}>
|
||||||
<Text style={{ fontFamily: 'mono' }}>No items selected</Text>
|
<Text style={{ fontFamily: "mono" }}>No items selected</Text>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
|
|
||||||
const from = Math.min(idx, selectedFrom);
|
const selected = data.filter((_, i) => selectedIdx.has(i)) as Transaction[];
|
||||||
const to = Math.max(idx, selectedFrom);
|
|
||||||
const selected = data.slice(from, to + 1) as Transaction[];
|
|
||||||
const count = selected.length;
|
const count = selected.length;
|
||||||
const sum = selected.reduce((prev, curr) => prev + curr.amount, 0);
|
const sum = selected.reduce((prev, curr) => prev + curr.amount, 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={{ backgroundColor: '#9f9' }}>
|
<View style={{ backgroundColor: "#9f9" }}>
|
||||||
<Text style={{ fontFamily: 'mono' }}>{count} transaction{count == 1 ? "" : "s"} selected | ${FORMAT.format(sum)}</Text>
|
<Text style={{ fontFamily: "mono" }}>
|
||||||
|
{count} transaction{count == 1 ? "" : "s"} selected | $
|
||||||
|
{FORMAT.format(sum)}
|
||||||
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
import { useKeyboard as useOpentuiKeyboard } from "@opentui/react";
|
|
||||||
|
|
||||||
export function useKeyboard(handler: Parameters<typeof useOpentuiKeyboard>[0], _deps: any[] = []) {
|
|
||||||
return useOpentuiKeyboard(handler);
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { useEffect } from "react";
|
|
||||||
import type { KeyboardEvent } from "react";
|
|
||||||
import type { KeyEvent } from "@opentui/core";
|
|
||||||
|
|
||||||
|
|
||||||
function convertName(keyName: string): string {
|
|
||||||
const result = keyName.toLowerCase()
|
|
||||||
if (result == 'arrowdown') return 'down';
|
|
||||||
if (result == 'arrowup') return 'up';
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useKeyboard(handler: (key: KeyEvent) => void, deps: any[] = []) {
|
|
||||||
useEffect(() => {
|
|
||||||
const handlerWeb = (event: KeyboardEvent) => {
|
|
||||||
// @ts-ignore
|
|
||||||
handler({
|
|
||||||
name: convertName(event.key),
|
|
||||||
ctrl: event.ctrlKey,
|
|
||||||
meta: event.metaKey,
|
|
||||||
shift: event.shiftKey,
|
|
||||||
option: event.metaKey,
|
|
||||||
sequence: '',
|
|
||||||
number: false,
|
|
||||||
raw: '',
|
|
||||||
eventType: 'press',
|
|
||||||
source: "raw",
|
|
||||||
code: event.code,
|
|
||||||
super: false,
|
|
||||||
hyper: false,
|
|
||||||
capsLock: false,
|
|
||||||
numLock: false,
|
|
||||||
baseCode: event.keyCode,
|
|
||||||
preventDefault: () => event.preventDefault(),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
window.addEventListener("keydown", handlerWeb);
|
|
||||||
return () => {
|
|
||||||
// @ts-ignore
|
|
||||||
window.removeEventListener("keydown", handlerWeb);
|
|
||||||
};
|
|
||||||
}, deps);
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"paths": {
|
|
||||||
"@/*": ["./*"]
|
|
||||||
},
|
|
||||||
// Environment setup & latest features
|
// Environment setup & latest features
|
||||||
"lib": ["ESNext"],
|
"lib": ["ESNext", "DOM"],
|
||||||
"target": "ESNext",
|
"target": "ESNext",
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"moduleDetection": "force",
|
"moduleDetection": "force",
|
||||||
|
|||||||
16112
pnpm-lock.yaml
generated
16112
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,4 +0,0 @@
|
|||||||
nodeLinker: hoisted
|
|
||||||
packages:
|
|
||||||
- 'apps/*'
|
|
||||||
- 'packages/*'
|
|
||||||
@@ -26,16 +26,16 @@ processes:
|
|||||||
period_seconds: 1
|
period_seconds: 1
|
||||||
|
|
||||||
tailscale_machine_name:
|
tailscale_machine_name:
|
||||||
command: "pnpm tsx ./scripts/set-machine-name.ts"
|
command: "bun tsx ./scripts/set-machine-name.ts"
|
||||||
|
|
||||||
expo:
|
expo:
|
||||||
command: "pnpm --filter=@money/expo start"
|
command: "bun --filter=@money/expo start"
|
||||||
depends_on:
|
depends_on:
|
||||||
tailscale_machine_name:
|
tailscale_machine_name:
|
||||||
condition: process_completed_successfully
|
condition: process_completed_successfully
|
||||||
|
|
||||||
api:
|
api:
|
||||||
command: "pnpm --filter=@money/api dev"
|
command: "bun --filter=@money/api dev"
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
command: |
|
command: |
|
||||||
@@ -51,13 +51,13 @@ processes:
|
|||||||
db:
|
db:
|
||||||
condition: process_healthy
|
condition: process_healthy
|
||||||
zero:
|
zero:
|
||||||
command: npx zero-cache-dev -p packages/shared/src/schema.ts
|
command: bunx zero-cache-dev -p packages/shared/src/schema.ts
|
||||||
depends_on:
|
depends_on:
|
||||||
migrate:
|
migrate:
|
||||||
condition: process_completed_successfully
|
condition: process_completed_successfully
|
||||||
|
|
||||||
studio:
|
studio:
|
||||||
command: npx drizzle-kit studio
|
command: bunx drizzle-kit studio
|
||||||
working_dir: ./packages/shared
|
working_dir: ./packages/shared
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ const moveDirectories = async (userInput) => {
|
|||||||
userInput === "y"
|
userInput === "y"
|
||||||
? `\n3. Delete the /${exampleDir} directory when you're done referencing it.`
|
? `\n3. Delete the /${exampleDir} directory when you're done referencing it.`
|
||||||
: ""
|
: ""
|
||||||
}`
|
}`,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`❌ Error during script execution: ${error.message}`);
|
console.error(`❌ Error during script execution: ${error.message}`);
|
||||||
@@ -108,5 +108,5 @@ rl.question(
|
|||||||
console.log("❌ Invalid input. Please enter 'Y' or 'N'.");
|
console.log("❌ Invalid input. Please enter 'Y' or 'N'.");
|
||||||
rl.close();
|
rl.close();
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -33,4 +33,3 @@ try {
|
|||||||
console.error("Failed to update .env.dev:", err);
|
console.error("Failed to update .env.dev:", err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user