mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-06-10 07:16:01 +00:00
Refatoração estrutural sem mudanças funcionais. Saldo líquido: −428 linhas. Removido: - 14 funções/constantes mortas verificadas via grep no repo todo: validateCategoriaOwnership, getInstallmentAnticipationsAction, getAnticipationDetailsAction, formatDecimalForDb, currencyFormatterNoCents, optionalDecimalSchema, formatMonthLabel, getGoalProgressStatusColorClass, MONTH_PERIOD_PARAM, calculateRemainingInstallments, e 5 funções fetch* não usadas em inbox/queries.ts. - 1 tipo morto (ImportRow) + 2 órfãos consequentes (InstallmentAnticipationWithRelations, GoalProgressStatus convertido em interno). - ~30 export keywords desnecessários (símbolos usados apenas no próprio arquivo). - Re-exports mortos em barrels: EstablishmentLogoPicker, CategoryReportSkeleton, WidgetSkeleton, toNameKey. - Arquivo features/reports/types.ts (barrel inteiro era órfão). Padronizado (PT-BR→EN em identificadores expostos): - 4 constantes globais (LANCAMENTOS_* → TRANSACTIONS_*). - 12 tipos/interfaces (Lancamento*/Pagador*/Estabelecimento* → equivalentes EN). - 13 funções/components exportados (fetchPagador*, EstabelecimentoInput, PagadorInfoCard, etc.). - 5 props cross-file (preLancamentosCount → inboxPendingCount, pagadorAvatarUrl → payerAvatarUrl, etc.). - Mantidas em PT-BR conforme exceção do CLAUDE.md: variáveis locais (pagador, categoria, lancamento), accessor key pagadorName (persistida em preferências), strings de UI. Reorganizado: - transactions/: 14 helpers soltos na raiz movidos para lib/; barrel actions.ts reduzido de 76 linhas de wrappers para 14 linhas de re-exports puros; anticipation-actions.ts movido para actions/anticipation.ts. - dashboard/: 8 helpers soltos consolidados em dashboard/lib/. - reports/: 5 query files na raiz consolidados em reports/lib/. - payers/: detail-actions.ts (21KB) e detail-queries.ts movidos para payers/lib/. - shared/components/: 9 dos 16 componentes soltos agrupados em brand/, widgets/, feedback/. - shared/lib/fetch-json.ts movido para shared/utils/fetch-json.ts. Validação: pnpm exec tsc --noEmit (0 erros), biome check (0 issues), knip (sem unused). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
188 lines
4.2 KiB
TypeScript
188 lines
4.2 KiB
TypeScript
import { and, count, desc, eq } from "drizzle-orm";
|
|
import { cards, financialAccounts, inboxItems } from "@/db/schema";
|
|
import type {
|
|
InboxItem,
|
|
InboxPaginationState,
|
|
InboxStatus,
|
|
InboxStatusCounts,
|
|
SelectOption,
|
|
} from "@/features/inbox/components/types";
|
|
import {
|
|
buildOptionSets,
|
|
buildSluggedFilters,
|
|
} from "@/features/transactions/lib/page-helpers";
|
|
import {
|
|
fetchRecentEstablishments,
|
|
fetchTransactionFilterSources,
|
|
} from "@/features/transactions/queries";
|
|
import { db } from "@/shared/lib/db";
|
|
|
|
export async function fetchInboxItemsPage(
|
|
userId: string,
|
|
status: InboxStatus,
|
|
{
|
|
page,
|
|
pageSize,
|
|
sourceApp,
|
|
}: {
|
|
page: number;
|
|
pageSize: number;
|
|
sourceApp?: string | null;
|
|
},
|
|
): Promise<{
|
|
items: InboxItem[];
|
|
pagination: InboxPaginationState;
|
|
}> {
|
|
const where = and(
|
|
eq(inboxItems.userId, userId),
|
|
eq(inboxItems.status, status),
|
|
sourceApp ? eq(inboxItems.sourceAppName, sourceApp) : undefined,
|
|
);
|
|
|
|
const [countRow] = await db
|
|
.select({ total: count() })
|
|
.from(inboxItems)
|
|
.where(where);
|
|
|
|
const totalItems = Number(countRow?.total ?? 0);
|
|
const totalPages = Math.max(Math.ceil(totalItems / pageSize), 1);
|
|
const currentPage = Math.min(page, totalPages);
|
|
const offset = (currentPage - 1) * pageSize;
|
|
|
|
const items = await db
|
|
.select()
|
|
.from(inboxItems)
|
|
.where(where)
|
|
.orderBy(desc(inboxItems.notificationTimestamp), desc(inboxItems.createdAt))
|
|
.limit(pageSize)
|
|
.offset(offset);
|
|
|
|
return {
|
|
items,
|
|
pagination: {
|
|
page: currentPage,
|
|
pageSize,
|
|
totalItems,
|
|
totalPages,
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function fetchInboxSourceApps(
|
|
userId: string,
|
|
status: InboxStatus,
|
|
): Promise<string[]> {
|
|
const rows = await db
|
|
.selectDistinct({ name: inboxItems.sourceAppName })
|
|
.from(inboxItems)
|
|
.where(and(eq(inboxItems.userId, userId), eq(inboxItems.status, status)));
|
|
|
|
return rows
|
|
.map((row) => row.name)
|
|
.filter((name): name is string => name !== null)
|
|
.sort();
|
|
}
|
|
|
|
export async function fetchInboxStatusCounts(
|
|
userId: string,
|
|
): Promise<InboxStatusCounts> {
|
|
const rows = await db
|
|
.select({
|
|
status: inboxItems.status,
|
|
total: count(),
|
|
})
|
|
.from(inboxItems)
|
|
.where(eq(inboxItems.userId, userId))
|
|
.groupBy(inboxItems.status);
|
|
|
|
const counts: InboxStatusCounts = {
|
|
pending: 0,
|
|
processed: 0,
|
|
discarded: 0,
|
|
};
|
|
|
|
for (const row of rows) {
|
|
if (row.status in counts) {
|
|
counts[row.status as InboxStatus] = Number(row.total ?? 0);
|
|
}
|
|
}
|
|
|
|
return counts;
|
|
}
|
|
|
|
export async function fetchAppLogoMap(
|
|
userId: string,
|
|
): Promise<Record<string, string>> {
|
|
const [userCartoes, userContas] = await Promise.all([
|
|
db
|
|
.select({ name: cards.name, logo: cards.logo })
|
|
.from(cards)
|
|
.where(eq(cards.userId, userId)),
|
|
db
|
|
.select({ name: financialAccounts.name, logo: financialAccounts.logo })
|
|
.from(financialAccounts)
|
|
.where(eq(financialAccounts.userId, userId)),
|
|
]);
|
|
|
|
const logoMap: Record<string, string> = {};
|
|
|
|
for (const item of [...userCartoes, ...userContas]) {
|
|
if (item.logo) {
|
|
logoMap[item.name.toLowerCase()] = item.logo;
|
|
}
|
|
}
|
|
|
|
return logoMap;
|
|
}
|
|
|
|
export async function fetchPendingInboxCount(userId: string): Promise<number> {
|
|
const [result] = await db
|
|
.select({ total: count() })
|
|
.from(inboxItems)
|
|
.where(
|
|
and(eq(inboxItems.userId, userId), eq(inboxItems.status, "pending")),
|
|
);
|
|
|
|
return Number(result?.total ?? 0);
|
|
}
|
|
|
|
/**
|
|
* Fetch all data needed for the TransactionDialog in inbox context
|
|
*/
|
|
export async function fetchInboxDialogData(userId: string): Promise<{
|
|
payerOptions: SelectOption[];
|
|
splitPayerOptions: SelectOption[];
|
|
defaultPayerId: string | null;
|
|
accountOptions: SelectOption[];
|
|
cardOptions: SelectOption[];
|
|
categoryOptions: SelectOption[];
|
|
estabelecimentos: string[];
|
|
}> {
|
|
const filterSources = await fetchTransactionFilterSources(userId);
|
|
const sluggedFilters = buildSluggedFilters(filterSources);
|
|
|
|
const {
|
|
payerOptions,
|
|
splitPayerOptions,
|
|
defaultPayerId,
|
|
accountOptions,
|
|
cardOptions,
|
|
categoryOptions,
|
|
} = buildOptionSets({
|
|
...sluggedFilters,
|
|
payerRows: filterSources.payerRows,
|
|
});
|
|
|
|
const estabelecimentos = await fetchRecentEstablishments(userId);
|
|
|
|
return {
|
|
payerOptions,
|
|
splitPayerOptions,
|
|
defaultPayerId,
|
|
accountOptions,
|
|
cardOptions,
|
|
categoryOptions,
|
|
estabelecimentos,
|
|
};
|
|
}
|