Skip to content

Commit

Permalink
Merge pull request #30 from VaquitApp/feature/autocomplete-spending-c…
Browse files Browse the repository at this point in the history
…ategory

Feature/autocomplete spending category
  • Loading branch information
MegaRedHand authored May 30, 2024
2 parents 7b1ba38 + 2486b4a commit ecaad89
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { budgetService, groupService } from '$lib/server/api';
import { fixDateString } from '$lib/formatter';

export const load: PageServerLoad = async ({ params, url, cookies }) => {
const group_id = Number(url.searchParams.get('group_id'));
const group_id = Number(url.searchParams.get('groupId'));
const id = Number(params.id) || 0;
const now = new Date();
const next_month = new Date();
Expand Down
24 changes: 10 additions & 14 deletions my-app/src/routes/budgets/details/[[id=integer]]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,25 @@
export let data: PageData;
const edit = data.budget.id !== 0;
let timezoneOffset = 0;
let suggestions: Map<string, Budget> = new Map();
let budgetSuggestions: Map<string, Budget> = new Map();
let categories: Category[] = [];
async function onGroupUpdate(groupId: number) {
await Promise.all([updateSuggestions(groupId), updateCategories(groupId)]);
await Promise.all([updateBudgetSuggestions(groupId), updateCategories(groupId)]);
}
async function updateSuggestions(groupId: number) {
async function updateBudgetSuggestions(groupId: number) {
const newSuggestions: Map<string, Budget> = new Map();
if (groupId != 0) {
try {
const response = await fetch(`/api/budgets?groupId=${groupId}`);
const body: Budget[] = await response.json();
body.forEach((budget) => {
newSuggestions.set(formatSuggestion(budget), budget);
newSuggestions.set(budget.description, budget);
});
} catch {}
}
suggestions = newSuggestions;
budgetSuggestions = newSuggestions;
}
async function updateCategories(groupId: number) {
Expand All @@ -39,12 +39,8 @@
categories = [];
}
function formatSuggestion({ description, amount }: Budget) {
return `${description} (${formatMoney(amount)})`;
}
function autocomplete(value: string) {
const budget = suggestions.get(value);
const budget = budgetSuggestions.get(value);
if (!budget) return;
data.budget.amount = budget.amount;
data.budget.description = budget.description;
Expand Down Expand Up @@ -80,7 +76,7 @@
name="groupId"
required
aria-readonly={edit}
value={data.budget.group_id}
bind:value={data.budget.group_id}
on:change={(e) => onGroupUpdate(+e.currentTarget.value)}
>
{#each data.groups as group}
Expand All @@ -95,12 +91,12 @@
name="description"
placeholder="Descripción"
list="description-list"
value={data.budget.description}
bind:value={data.budget.description}
on:change={(e) => autocomplete(e.currentTarget.value)}
/>
<datalist id="description-list">
{#each suggestions.keys() as suggestion}
<option>{suggestion}</option>
{#each budgetSuggestions.values() as budget}
<option value={budget.description}>{formatMoney(budget.amount)}</option>
{/each}
</datalist>
</label>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ import type { Actions } from './$types';
import { groupService, spendingService } from '$lib/server/api';
import type { PageServerLoad } from './$types';
import { fixDateString } from '$lib/formatter';
import { getUserId } from '$lib/auth';

export const load: PageServerLoad = async ({ params, url, cookies }) => {
const group_id = Number(url.searchParams.get('groupId'));
const id = Number(params.id);
// TODO: load real spending
const spending: Spending = {
id,
description: '',
amount: 0,
owner_id: 0,
date: new Date().toJSON().slice(0, 16),
category_name: '',
group_id
};
const groups: Group[] = await groupService.list(cookies);
Expand All @@ -27,6 +29,8 @@ export const actions: Actions = {
const amount = Number(data.get('amount'));
const dateString = data.get('date')?.toString();
const group_id = Number(data.get('groupId'));
const category_name = data.get('categoryId')?.toString();
const owner_id = getUserId(cookies);

if (!description) {
throw error(400, 'Description is required');
Expand All @@ -37,10 +41,13 @@ export const actions: Actions = {
if (!dateString) {
throw error(400, 'Date is required');
}
if (!category_name) {
throw error(400, 'Category is required');
}

const timezoneOffset = Number(data.get('timezoneOffset')) || 0;
const date = fixDateString(dateString, timezoneOffset);
const spending: Spending = { id, amount, description, date, group_id };
const spending: Spending = { id, amount, description, date, group_id, category_name, owner_id };
try {
await spendingService.save(spending, cookies);
} catch {
Expand Down
53 changes: 40 additions & 13 deletions my-app/src/routes/spendings/details/[[id=integer]]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
export let data: PageServerData;
let timezoneOffset = 0;
let suggestions: Map<string, Spending> = new Map();
let categories: Category[] = [];
async function onGroupUpdate(groupId: number) {
await Promise.all([updateSuggestions(groupId), updateCategories(groupId)]);
}
async function updateSuggestions(groupId: number) {
const newSuggestions: Map<string, Spending> = new Map();
Expand All @@ -15,27 +20,35 @@
const response = await fetch(`/api/spendings?groupId=${groupId}`);
const body: Spending[] = await response.json();
body.forEach((spending) => {
newSuggestions.set(formatSuggestion(spending), spending);
newSuggestions.set(spending.description, spending);
});
} catch {}
}
suggestions = newSuggestions;
}
function formatSuggestion({ description, amount }: Spending) {
return `${description} (${formatMoney(amount)})`;
}
function autocomplete(value: string) {
const spending = suggestions.get(value);
if (!spending) return;
data.spending.amount = spending.amount;
data.spending.description = spending.description;
data.spending.category_name = spending.category_name;
}
async function updateCategories(groupId: number) {
if (groupId != 0) {
try {
const response = await fetch(`/api/categories?groupId=${groupId}`);
categories = await response.json();
return;
} catch {}
}
categories = [];
}
onMount(async () => {
timezoneOffset = new Date().getTimezoneOffset();
await updateSuggestions(data.spending.group_id);
await onGroupUpdate(data.spending.group_id);
});
</script>

Expand All @@ -59,14 +72,22 @@
<select
name="groupId"
required
value={data.spending.group_id}
on:change={(e) => updateSuggestions(+e.currentTarget.value)}
bind:value={data.spending.group_id}
on:change={(e) => onGroupUpdate(+e.currentTarget.value)}
>
{#each data.groups as group}
<option value={group.id}>{group.name}</option>
{/each}
</select>
</label>
<label>
Ingrese la categoría a la que pertenece el gasto
<select name="categoryId" required value={data.spending.category_name}>
{#each categories as category}
<option value={category.name}>{category.name}</option>
{/each}
</select>
</label>
<label>
Ingrese una descripción para el gasto
<input
Expand All @@ -75,18 +96,24 @@
placeholder="Descripción"
list="description-list"
required
value={data.spending.description}
bind:value={data.spending.description}
on:change={(e) => autocomplete(e.currentTarget.value)}
/>
<datalist id="description-list">
{#each suggestions.keys() as suggestion}
<option>{suggestion}</option>
{#each suggestions.values() as spending}
<option value={spending.description}>{formatMoney(spending.amount)}</option>
{/each}
</datalist>
</label>
<label>
Ingrese un monto para el gasto
<input type="text" name="amount" placeholder="Monto" required value={data.spending.amount} />
<input
type="text"
name="amount"
placeholder="Monto"
required
bind:value={data.spending.amount}
/>
</label>
<label>
Ingrese la fecha del gasto
Expand All @@ -95,7 +122,7 @@
name="date"
placeholder="Fecha"
required
value={data.spending.date}
bind:value={data.spending.date}
/>
</label>
<button>Crear</button>
Expand Down
1 change: 1 addition & 0 deletions my-app/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ declare global {
id: Id;
group_id: Id;
owner_id: int;
category_name: string;
description: string;
amount: number;
date: string;
Expand Down

0 comments on commit ecaad89

Please sign in to comment.