mirror of
https://github.com/whekin/household-bot.git
synced 2026-03-31 21:04:03 +00:00
feat(miniapp): add cycle-level billing controls
This commit is contained in:
@@ -42,6 +42,13 @@ import {
|
||||
createMiniAppUpdateSettingsHandler,
|
||||
createMiniAppUpsertUtilityCategoryHandler
|
||||
} from './miniapp-admin'
|
||||
import {
|
||||
createMiniAppAddUtilityBillHandler,
|
||||
createMiniAppBillingCycleHandler,
|
||||
createMiniAppCloseCycleHandler,
|
||||
createMiniAppOpenCycleHandler,
|
||||
createMiniAppRentUpdateHandler
|
||||
} from './miniapp-billing'
|
||||
import { createMiniAppLocalePreferenceHandler } from './miniapp-locale'
|
||||
|
||||
const runtime = getBotRuntimeConfig()
|
||||
@@ -351,6 +358,51 @@ const server = createBotWebhookServer({
|
||||
logger: getLogger('miniapp-admin')
|
||||
})
|
||||
: undefined,
|
||||
miniAppBillingCycle: householdOnboardingService
|
||||
? createMiniAppBillingCycleHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
botToken: runtime.telegramBotToken,
|
||||
onboardingService: householdOnboardingService,
|
||||
financeServiceForHousehold,
|
||||
logger: getLogger('miniapp-billing')
|
||||
})
|
||||
: undefined,
|
||||
miniAppOpenCycle: householdOnboardingService
|
||||
? createMiniAppOpenCycleHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
botToken: runtime.telegramBotToken,
|
||||
onboardingService: householdOnboardingService,
|
||||
financeServiceForHousehold,
|
||||
logger: getLogger('miniapp-billing')
|
||||
})
|
||||
: undefined,
|
||||
miniAppCloseCycle: householdOnboardingService
|
||||
? createMiniAppCloseCycleHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
botToken: runtime.telegramBotToken,
|
||||
onboardingService: householdOnboardingService,
|
||||
financeServiceForHousehold,
|
||||
logger: getLogger('miniapp-billing')
|
||||
})
|
||||
: undefined,
|
||||
miniAppRentUpdate: householdOnboardingService
|
||||
? createMiniAppRentUpdateHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
botToken: runtime.telegramBotToken,
|
||||
onboardingService: householdOnboardingService,
|
||||
financeServiceForHousehold,
|
||||
logger: getLogger('miniapp-billing')
|
||||
})
|
||||
: undefined,
|
||||
miniAppAddUtilityBill: householdOnboardingService
|
||||
? createMiniAppAddUtilityBillHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
botToken: runtime.telegramBotToken,
|
||||
onboardingService: householdOnboardingService,
|
||||
financeServiceForHousehold,
|
||||
logger: getLogger('miniapp-billing')
|
||||
})
|
||||
: undefined,
|
||||
miniAppLocalePreference: householdOnboardingService
|
||||
? createMiniAppLocalePreferenceHandler({
|
||||
allowedOrigins: runtime.miniAppAllowedOrigins,
|
||||
|
||||
355
apps/bot/src/miniapp-billing.test.ts
Normal file
355
apps/bot/src/miniapp-billing.test.ts
Normal file
@@ -0,0 +1,355 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
|
||||
import type { FinanceCommandService } from '@household/application'
|
||||
import { createHouseholdOnboardingService } from '@household/application'
|
||||
import { instantFromIso, Money } from '@household/domain'
|
||||
import type {
|
||||
HouseholdConfigurationRepository,
|
||||
HouseholdTopicBindingRecord
|
||||
} from '@household/ports'
|
||||
|
||||
import {
|
||||
createMiniAppAddUtilityBillHandler,
|
||||
createMiniAppBillingCycleHandler,
|
||||
createMiniAppOpenCycleHandler,
|
||||
createMiniAppRentUpdateHandler
|
||||
} from './miniapp-billing'
|
||||
import { buildMiniAppInitData } from './telegram-miniapp-test-helpers'
|
||||
|
||||
function onboardingRepository(): HouseholdConfigurationRepository {
|
||||
const household = {
|
||||
householdId: 'household-1',
|
||||
householdName: 'Kojori House',
|
||||
telegramChatId: '-100123',
|
||||
telegramChatType: 'supergroup',
|
||||
title: 'Kojori House',
|
||||
defaultLocale: 'ru' as const
|
||||
}
|
||||
|
||||
return {
|
||||
registerTelegramHouseholdChat: async () => ({
|
||||
status: 'existing',
|
||||
household
|
||||
}),
|
||||
getTelegramHouseholdChat: async () => household,
|
||||
getHouseholdChatByHouseholdId: async () => household,
|
||||
bindHouseholdTopic: async (input) =>
|
||||
({
|
||||
householdId: input.householdId,
|
||||
role: input.role,
|
||||
telegramThreadId: input.telegramThreadId,
|
||||
topicName: input.topicName?.trim() || null
|
||||
}) satisfies HouseholdTopicBindingRecord,
|
||||
getHouseholdTopicBinding: async () => null,
|
||||
findHouseholdTopicByTelegramContext: async () => null,
|
||||
listHouseholdTopicBindings: async () => [],
|
||||
listReminderTargets: async () => [],
|
||||
upsertHouseholdJoinToken: async (input) => ({
|
||||
householdId: household.householdId,
|
||||
householdName: household.householdName,
|
||||
token: input.token,
|
||||
createdByTelegramUserId: input.createdByTelegramUserId ?? null
|
||||
}),
|
||||
getHouseholdJoinToken: async () => null,
|
||||
getHouseholdByJoinToken: async () => null,
|
||||
upsertPendingHouseholdMember: async (input) => ({
|
||||
householdId: household.householdId,
|
||||
householdName: household.householdName,
|
||||
telegramUserId: input.telegramUserId,
|
||||
displayName: input.displayName,
|
||||
username: input.username?.trim() || null,
|
||||
languageCode: input.languageCode?.trim() || null,
|
||||
householdDefaultLocale: household.defaultLocale
|
||||
}),
|
||||
getPendingHouseholdMember: async () => null,
|
||||
findPendingHouseholdMemberByTelegramUserId: async () => null,
|
||||
ensureHouseholdMember: async (input) => ({
|
||||
id: `member-${input.telegramUserId}`,
|
||||
householdId: household.householdId,
|
||||
telegramUserId: input.telegramUserId,
|
||||
displayName: input.displayName,
|
||||
preferredLocale: input.preferredLocale ?? null,
|
||||
householdDefaultLocale: household.defaultLocale,
|
||||
isAdmin: input.isAdmin === true
|
||||
}),
|
||||
getHouseholdMember: async () => null,
|
||||
listHouseholdMembers: async () => [],
|
||||
getHouseholdBillingSettings: async (householdId) => ({
|
||||
householdId,
|
||||
rentAmountMinor: 70000n,
|
||||
rentCurrency: 'USD',
|
||||
rentDueDay: 20,
|
||||
rentWarningDay: 17,
|
||||
utilitiesDueDay: 4,
|
||||
utilitiesReminderDay: 3,
|
||||
timezone: 'Asia/Tbilisi'
|
||||
}),
|
||||
updateHouseholdBillingSettings: async (input) => ({
|
||||
householdId: input.householdId,
|
||||
rentAmountMinor: input.rentAmountMinor ?? 70000n,
|
||||
rentCurrency: input.rentCurrency ?? 'USD',
|
||||
rentDueDay: input.rentDueDay ?? 20,
|
||||
rentWarningDay: input.rentWarningDay ?? 17,
|
||||
utilitiesDueDay: input.utilitiesDueDay ?? 4,
|
||||
utilitiesReminderDay: input.utilitiesReminderDay ?? 3,
|
||||
timezone: input.timezone ?? 'Asia/Tbilisi'
|
||||
}),
|
||||
listHouseholdUtilityCategories: async () => [],
|
||||
upsertHouseholdUtilityCategory: async (input) => ({
|
||||
id: input.slug ?? 'utility-category-1',
|
||||
householdId: input.householdId,
|
||||
slug: input.slug ?? 'custom',
|
||||
name: input.name,
|
||||
sortOrder: input.sortOrder,
|
||||
isActive: input.isActive
|
||||
}),
|
||||
listHouseholdMembersByTelegramUserId: async () => [
|
||||
{
|
||||
id: 'member-123456',
|
||||
householdId: 'household-1',
|
||||
telegramUserId: '123456',
|
||||
displayName: 'Stan',
|
||||
preferredLocale: null,
|
||||
householdDefaultLocale: 'ru',
|
||||
isAdmin: true
|
||||
}
|
||||
],
|
||||
listPendingHouseholdMembers: async () => [],
|
||||
approvePendingHouseholdMember: async () => null,
|
||||
updateHouseholdDefaultLocale: async (_householdId, locale) => ({
|
||||
...household,
|
||||
defaultLocale: locale
|
||||
}),
|
||||
updateMemberPreferredLocale: async () => null,
|
||||
promoteHouseholdAdmin: async () => null
|
||||
}
|
||||
}
|
||||
|
||||
function createFinanceServiceStub(): FinanceCommandService {
|
||||
return {
|
||||
getMemberByTelegramUserId: async () => null,
|
||||
getOpenCycle: async () => ({
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
}),
|
||||
getAdminCycleState: async () => ({
|
||||
cycle: {
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
},
|
||||
rentRule: {
|
||||
amountMinor: 70000n,
|
||||
currency: 'USD'
|
||||
},
|
||||
utilityBills: [
|
||||
{
|
||||
id: 'utility-1',
|
||||
billName: 'Electricity',
|
||||
amount: Money.fromMinor(12000n, 'USD'),
|
||||
currency: 'USD',
|
||||
createdByMemberId: 'member-123456',
|
||||
createdAt: instantFromIso('2026-03-12T12:00:00.000Z')
|
||||
}
|
||||
]
|
||||
}),
|
||||
openCycle: async () => ({
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
}),
|
||||
closeCycle: async () => ({
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
}),
|
||||
setRent: async () => ({
|
||||
amount: Money.fromMinor(75000n, 'USD'),
|
||||
currency: 'USD',
|
||||
period: '2026-03'
|
||||
}),
|
||||
addUtilityBill: async () => ({
|
||||
amount: Money.fromMinor(4500n, 'USD'),
|
||||
currency: 'USD',
|
||||
period: '2026-03'
|
||||
}),
|
||||
generateDashboard: async () => null,
|
||||
generateStatement: async () => null
|
||||
}
|
||||
}
|
||||
|
||||
const authDate = Math.floor(Date.now() / 1000)
|
||||
|
||||
function initData() {
|
||||
return buildMiniAppInitData('test-bot-token', authDate, {
|
||||
id: 123456,
|
||||
first_name: 'Stan',
|
||||
username: 'stanislav',
|
||||
language_code: 'ru'
|
||||
})
|
||||
}
|
||||
|
||||
describe('createMiniAppBillingCycleHandler', () => {
|
||||
test('returns the current cycle state for an authenticated admin', async () => {
|
||||
const repository = onboardingRepository()
|
||||
const handler = createMiniAppBillingCycleHandler({
|
||||
allowedOrigins: ['http://localhost:5173'],
|
||||
botToken: 'test-bot-token',
|
||||
onboardingService: createHouseholdOnboardingService({
|
||||
repository
|
||||
}),
|
||||
financeServiceForHousehold: () => createFinanceServiceStub()
|
||||
})
|
||||
|
||||
const response = await handler.handler(
|
||||
new Request('http://localhost/api/miniapp/admin/billing-cycle', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: 'http://localhost:5173',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
initData: initData()
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {
|
||||
cycle: {
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
},
|
||||
rentRule: {
|
||||
amountMinor: '70000',
|
||||
currency: 'USD'
|
||||
},
|
||||
utilityBills: [
|
||||
{
|
||||
id: 'utility-1',
|
||||
billName: 'Electricity',
|
||||
amountMinor: '12000',
|
||||
currency: 'USD',
|
||||
createdByMemberId: 'member-123456',
|
||||
createdAt: '2026-03-12T12:00:00Z'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createMiniAppOpenCycleHandler', () => {
|
||||
test('opens a billing cycle for an authenticated admin', async () => {
|
||||
const repository = onboardingRepository()
|
||||
const handler = createMiniAppOpenCycleHandler({
|
||||
allowedOrigins: ['http://localhost:5173'],
|
||||
botToken: 'test-bot-token',
|
||||
onboardingService: createHouseholdOnboardingService({
|
||||
repository
|
||||
}),
|
||||
financeServiceForHousehold: () => createFinanceServiceStub()
|
||||
})
|
||||
|
||||
const response = await handler.handler(
|
||||
new Request('http://localhost/api/miniapp/admin/billing-cycle/open', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: 'http://localhost:5173',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
initData: initData(),
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const payload = (await response.json()) as { cycleState: { cycle: unknown } }
|
||||
|
||||
expect(payload.cycleState.cycle).toEqual({
|
||||
id: 'cycle-2026-03',
|
||||
period: '2026-03',
|
||||
currency: 'USD'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createMiniAppRentUpdateHandler', () => {
|
||||
test('updates rent for the current billing cycle', async () => {
|
||||
const repository = onboardingRepository()
|
||||
const handler = createMiniAppRentUpdateHandler({
|
||||
allowedOrigins: ['http://localhost:5173'],
|
||||
botToken: 'test-bot-token',
|
||||
onboardingService: createHouseholdOnboardingService({
|
||||
repository
|
||||
}),
|
||||
financeServiceForHousehold: () => createFinanceServiceStub()
|
||||
})
|
||||
|
||||
const response = await handler.handler(
|
||||
new Request('http://localhost/api/miniapp/admin/rent/update', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: 'http://localhost:5173',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
initData: initData(),
|
||||
amountMajor: '750',
|
||||
currency: 'USD'
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const payload = (await response.json()) as { cycleState: { rentRule: unknown } }
|
||||
|
||||
expect(payload.cycleState.rentRule).toEqual({
|
||||
amountMinor: '70000',
|
||||
currency: 'USD'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createMiniAppAddUtilityBillHandler', () => {
|
||||
test('adds a utility bill for the current billing cycle', async () => {
|
||||
const repository = onboardingRepository()
|
||||
const handler = createMiniAppAddUtilityBillHandler({
|
||||
allowedOrigins: ['http://localhost:5173'],
|
||||
botToken: 'test-bot-token',
|
||||
onboardingService: createHouseholdOnboardingService({
|
||||
repository
|
||||
}),
|
||||
financeServiceForHousehold: () => createFinanceServiceStub()
|
||||
})
|
||||
|
||||
const response = await handler.handler(
|
||||
new Request('http://localhost/api/miniapp/admin/utility-bills/add', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: 'http://localhost:5173',
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
initData: initData(),
|
||||
billName: 'Internet',
|
||||
amountMajor: '45',
|
||||
currency: 'USD'
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const payload = (await response.json()) as { cycleState: { utilityBills: unknown[] } }
|
||||
|
||||
expect(payload.cycleState.utilityBills).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
525
apps/bot/src/miniapp-billing.ts
Normal file
525
apps/bot/src/miniapp-billing.ts
Normal file
@@ -0,0 +1,525 @@
|
||||
import type { FinanceCommandService, HouseholdOnboardingService } from '@household/application'
|
||||
import { BillingPeriod } from '@household/domain'
|
||||
import type { Logger } from '@household/observability'
|
||||
import type { MiniAppSessionResult } from './miniapp-auth'
|
||||
|
||||
import {
|
||||
allowedMiniAppOrigin,
|
||||
createMiniAppSessionService,
|
||||
miniAppErrorResponse,
|
||||
miniAppJsonResponse,
|
||||
readMiniAppRequestPayload
|
||||
} from './miniapp-auth'
|
||||
|
||||
function serializeCycleState(
|
||||
state: Awaited<ReturnType<FinanceCommandService['getAdminCycleState']>>
|
||||
) {
|
||||
return {
|
||||
cycle: state.cycle,
|
||||
rentRule: state.rentRule
|
||||
? {
|
||||
amountMinor: state.rentRule.amountMinor.toString(),
|
||||
currency: state.rentRule.currency
|
||||
}
|
||||
: null,
|
||||
utilityBills: state.utilityBills.map((bill) => ({
|
||||
id: bill.id,
|
||||
billName: bill.billName,
|
||||
amountMinor: bill.amount.amountMinor.toString(),
|
||||
currency: bill.currency,
|
||||
createdByMemberId: bill.createdByMemberId,
|
||||
createdAt: bill.createdAt.toString()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async function authenticateAdminSession(
|
||||
request: Request,
|
||||
sessionService: ReturnType<typeof createMiniAppSessionService>,
|
||||
origin: string | undefined
|
||||
): Promise<
|
||||
| Response
|
||||
| {
|
||||
member: NonNullable<MiniAppSessionResult['member']>
|
||||
}
|
||||
> {
|
||||
const payload = await readMiniAppRequestPayload(request)
|
||||
if (!payload.initData) {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Missing initData' }, 400, origin)
|
||||
}
|
||||
|
||||
const session = await sessionService.authenticate(payload)
|
||||
if (!session) {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Invalid Telegram init data' }, 401, origin)
|
||||
}
|
||||
|
||||
if (!session.authorized || !session.member) {
|
||||
return miniAppJsonResponse(
|
||||
{ ok: false, error: 'Access limited to active household members' },
|
||||
403,
|
||||
origin
|
||||
)
|
||||
}
|
||||
|
||||
if (!session.member.isAdmin) {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Admin access required' }, 403, origin)
|
||||
}
|
||||
|
||||
return {
|
||||
member: session.member
|
||||
}
|
||||
}
|
||||
|
||||
async function parseJsonBody<T>(request: Request): Promise<T> {
|
||||
const text = await request.clone().text()
|
||||
if (text.trim().length === 0) {
|
||||
return {} as T
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text) as T
|
||||
} catch {
|
||||
throw new Error('Invalid JSON body')
|
||||
}
|
||||
}
|
||||
|
||||
async function readCycleQueryPayload(request: Request): Promise<{
|
||||
initData: string
|
||||
period?: string
|
||||
}> {
|
||||
const parsed = await parseJsonBody<{
|
||||
initData?: string
|
||||
period?: string
|
||||
}>(request)
|
||||
const initData = parsed.initData?.trim()
|
||||
if (!initData) {
|
||||
throw new Error('Missing initData')
|
||||
}
|
||||
const period = parsed.period?.trim()
|
||||
|
||||
return {
|
||||
initData,
|
||||
...(period
|
||||
? {
|
||||
period: BillingPeriod.fromString(period).toString()
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
async function readOpenCyclePayload(request: Request): Promise<{
|
||||
initData: string
|
||||
period: string
|
||||
currency?: string
|
||||
}> {
|
||||
const parsed = await parseJsonBody<{ initData?: string; period?: string; currency?: string }>(
|
||||
request
|
||||
)
|
||||
const initData = parsed.initData?.trim()
|
||||
if (!initData) {
|
||||
throw new Error('Missing initData')
|
||||
}
|
||||
if (typeof parsed.period !== 'string' || parsed.period.trim().length === 0) {
|
||||
throw new Error('Missing billing cycle period')
|
||||
}
|
||||
|
||||
const currency = parsed.currency?.trim()
|
||||
|
||||
return {
|
||||
initData,
|
||||
period: BillingPeriod.fromString(parsed.period.trim()).toString(),
|
||||
...(currency
|
||||
? {
|
||||
currency
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
async function readRentUpdatePayload(request: Request): Promise<{
|
||||
initData: string
|
||||
amountMajor: string
|
||||
currency?: string
|
||||
period?: string
|
||||
}> {
|
||||
const parsed = await parseJsonBody<{
|
||||
initData?: string
|
||||
amountMajor?: string
|
||||
currency?: string
|
||||
period?: string
|
||||
}>(request)
|
||||
const initData = parsed.initData?.trim()
|
||||
if (!initData) {
|
||||
throw new Error('Missing initData')
|
||||
}
|
||||
const amountMajor = parsed.amountMajor?.trim()
|
||||
if (!amountMajor) {
|
||||
throw new Error('Missing rent amount')
|
||||
}
|
||||
|
||||
const currency = parsed.currency?.trim()
|
||||
const period = parsed.period?.trim()
|
||||
|
||||
return {
|
||||
initData,
|
||||
amountMajor,
|
||||
...(currency
|
||||
? {
|
||||
currency
|
||||
}
|
||||
: {}),
|
||||
...(period
|
||||
? {
|
||||
period: BillingPeriod.fromString(period).toString()
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
async function readUtilityBillPayload(request: Request): Promise<{
|
||||
initData: string
|
||||
billName: string
|
||||
amountMajor: string
|
||||
currency?: string
|
||||
}> {
|
||||
const parsed = await parseJsonBody<{
|
||||
initData?: string
|
||||
billName?: string
|
||||
amountMajor?: string
|
||||
currency?: string
|
||||
}>(request)
|
||||
const initData = parsed.initData?.trim()
|
||||
if (!initData) {
|
||||
throw new Error('Missing initData')
|
||||
}
|
||||
const billName = parsed.billName?.trim()
|
||||
const amountMajor = parsed.amountMajor?.trim()
|
||||
|
||||
if (!billName) {
|
||||
throw new Error('Missing utility bill name')
|
||||
}
|
||||
|
||||
if (!amountMajor) {
|
||||
throw new Error('Missing utility bill amount')
|
||||
}
|
||||
|
||||
const currency = parsed.currency?.trim()
|
||||
|
||||
return {
|
||||
initData,
|
||||
billName,
|
||||
amountMajor,
|
||||
...(currency
|
||||
? {
|
||||
currency
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
export function createMiniAppBillingCycleHandler(options: {
|
||||
allowedOrigins: readonly string[]
|
||||
botToken: string
|
||||
financeServiceForHousehold: (householdId: string) => FinanceCommandService
|
||||
onboardingService: HouseholdOnboardingService
|
||||
logger?: Logger
|
||||
}): {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
} {
|
||||
const sessionService = createMiniAppSessionService({
|
||||
botToken: options.botToken,
|
||||
onboardingService: options.onboardingService
|
||||
})
|
||||
|
||||
return {
|
||||
handler: async (request) => {
|
||||
const origin = allowedMiniAppOrigin(request, options.allowedOrigins)
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return miniAppJsonResponse({ ok: true }, 204, origin)
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Method Not Allowed' }, 405, origin)
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await authenticateAdminSession(
|
||||
request.clone() as Request,
|
||||
sessionService,
|
||||
origin
|
||||
)
|
||||
if (auth instanceof Response) {
|
||||
return auth
|
||||
}
|
||||
|
||||
const payload = await readCycleQueryPayload(request)
|
||||
const cycleState = await options
|
||||
.financeServiceForHousehold(auth.member.householdId)
|
||||
.getAdminCycleState(payload.period)
|
||||
|
||||
return miniAppJsonResponse(
|
||||
{
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: serializeCycleState(cycleState)
|
||||
},
|
||||
200,
|
||||
origin
|
||||
)
|
||||
} catch (error) {
|
||||
return miniAppErrorResponse(error, origin, options.logger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createMiniAppOpenCycleHandler(options: {
|
||||
allowedOrigins: readonly string[]
|
||||
botToken: string
|
||||
financeServiceForHousehold: (householdId: string) => FinanceCommandService
|
||||
onboardingService: HouseholdOnboardingService
|
||||
logger?: Logger
|
||||
}): {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
} {
|
||||
const sessionService = createMiniAppSessionService({
|
||||
botToken: options.botToken,
|
||||
onboardingService: options.onboardingService
|
||||
})
|
||||
|
||||
return {
|
||||
handler: async (request) => {
|
||||
const origin = allowedMiniAppOrigin(request, options.allowedOrigins)
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return miniAppJsonResponse({ ok: true }, 204, origin)
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Method Not Allowed' }, 405, origin)
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await authenticateAdminSession(
|
||||
request.clone() as Request,
|
||||
sessionService,
|
||||
origin
|
||||
)
|
||||
if (auth instanceof Response) {
|
||||
return auth
|
||||
}
|
||||
|
||||
const payload = await readOpenCyclePayload(request)
|
||||
const service = options.financeServiceForHousehold(auth.member.householdId)
|
||||
await service.openCycle(payload.period, payload.currency)
|
||||
const cycleState = await service.getAdminCycleState(payload.period)
|
||||
|
||||
return miniAppJsonResponse(
|
||||
{
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: serializeCycleState(cycleState)
|
||||
},
|
||||
200,
|
||||
origin
|
||||
)
|
||||
} catch (error) {
|
||||
return miniAppErrorResponse(error, origin, options.logger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createMiniAppCloseCycleHandler(options: {
|
||||
allowedOrigins: readonly string[]
|
||||
botToken: string
|
||||
financeServiceForHousehold: (householdId: string) => FinanceCommandService
|
||||
onboardingService: HouseholdOnboardingService
|
||||
logger?: Logger
|
||||
}): {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
} {
|
||||
const sessionService = createMiniAppSessionService({
|
||||
botToken: options.botToken,
|
||||
onboardingService: options.onboardingService
|
||||
})
|
||||
|
||||
return {
|
||||
handler: async (request) => {
|
||||
const origin = allowedMiniAppOrigin(request, options.allowedOrigins)
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return miniAppJsonResponse({ ok: true }, 204, origin)
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Method Not Allowed' }, 405, origin)
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await authenticateAdminSession(
|
||||
request.clone() as Request,
|
||||
sessionService,
|
||||
origin
|
||||
)
|
||||
if (auth instanceof Response) {
|
||||
return auth
|
||||
}
|
||||
|
||||
const payload = await readCycleQueryPayload(request)
|
||||
const service = options.financeServiceForHousehold(auth.member.householdId)
|
||||
await service.closeCycle(payload.period)
|
||||
const cycleState = await service.getAdminCycleState()
|
||||
|
||||
return miniAppJsonResponse(
|
||||
{
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: serializeCycleState(cycleState)
|
||||
},
|
||||
200,
|
||||
origin
|
||||
)
|
||||
} catch (error) {
|
||||
return miniAppErrorResponse(error, origin, options.logger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createMiniAppRentUpdateHandler(options: {
|
||||
allowedOrigins: readonly string[]
|
||||
botToken: string
|
||||
financeServiceForHousehold: (householdId: string) => FinanceCommandService
|
||||
onboardingService: HouseholdOnboardingService
|
||||
logger?: Logger
|
||||
}): {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
} {
|
||||
const sessionService = createMiniAppSessionService({
|
||||
botToken: options.botToken,
|
||||
onboardingService: options.onboardingService
|
||||
})
|
||||
|
||||
return {
|
||||
handler: async (request) => {
|
||||
const origin = allowedMiniAppOrigin(request, options.allowedOrigins)
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return miniAppJsonResponse({ ok: true }, 204, origin)
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Method Not Allowed' }, 405, origin)
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await authenticateAdminSession(
|
||||
request.clone() as Request,
|
||||
sessionService,
|
||||
origin
|
||||
)
|
||||
if (auth instanceof Response) {
|
||||
return auth
|
||||
}
|
||||
|
||||
const payload = await readRentUpdatePayload(request)
|
||||
const service = options.financeServiceForHousehold(auth.member.householdId)
|
||||
const result = await service.setRent(payload.amountMajor, payload.currency, payload.period)
|
||||
if (!result) {
|
||||
return miniAppJsonResponse(
|
||||
{ ok: false, error: 'No billing cycle available' },
|
||||
404,
|
||||
origin
|
||||
)
|
||||
}
|
||||
|
||||
const cycleState = await service.getAdminCycleState(result.period)
|
||||
|
||||
return miniAppJsonResponse(
|
||||
{
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: serializeCycleState(cycleState)
|
||||
},
|
||||
200,
|
||||
origin
|
||||
)
|
||||
} catch (error) {
|
||||
return miniAppErrorResponse(error, origin, options.logger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createMiniAppAddUtilityBillHandler(options: {
|
||||
allowedOrigins: readonly string[]
|
||||
botToken: string
|
||||
financeServiceForHousehold: (householdId: string) => FinanceCommandService
|
||||
onboardingService: HouseholdOnboardingService
|
||||
logger?: Logger
|
||||
}): {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
} {
|
||||
const sessionService = createMiniAppSessionService({
|
||||
botToken: options.botToken,
|
||||
onboardingService: options.onboardingService
|
||||
})
|
||||
|
||||
return {
|
||||
handler: async (request) => {
|
||||
const origin = allowedMiniAppOrigin(request, options.allowedOrigins)
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return miniAppJsonResponse({ ok: true }, 204, origin)
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return miniAppJsonResponse({ ok: false, error: 'Method Not Allowed' }, 405, origin)
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await authenticateAdminSession(
|
||||
request.clone() as Request,
|
||||
sessionService,
|
||||
origin
|
||||
)
|
||||
if (auth instanceof Response) {
|
||||
return auth
|
||||
}
|
||||
|
||||
const payload = await readUtilityBillPayload(request)
|
||||
const service = options.financeServiceForHousehold(auth.member.householdId)
|
||||
const result = await service.addUtilityBill(
|
||||
payload.billName,
|
||||
payload.amountMajor,
|
||||
auth.member.id,
|
||||
payload.currency
|
||||
)
|
||||
|
||||
if (!result) {
|
||||
return miniAppJsonResponse(
|
||||
{ ok: false, error: 'No billing cycle available' },
|
||||
404,
|
||||
origin
|
||||
)
|
||||
}
|
||||
|
||||
const cycleState = await service.getAdminCycleState(result.period)
|
||||
|
||||
return miniAppJsonResponse(
|
||||
{
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: serializeCycleState(cycleState)
|
||||
},
|
||||
200,
|
||||
origin
|
||||
)
|
||||
} catch (error) {
|
||||
return miniAppErrorResponse(error, origin, options.logger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,51 @@ describe('createBotWebhookServer', () => {
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppBillingCycle: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, cycleState: {} }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppOpenCycle: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, cycleState: {} }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppCloseCycle: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, cycleState: {} }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppRentUpdate: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, cycleState: {} }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppAddUtilityBill: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, cycleState: {} }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
})
|
||||
},
|
||||
miniAppApproveMember: {
|
||||
handler: async () =>
|
||||
new Response(JSON.stringify({ ok: true, authorized: true, member: {} }), {
|
||||
@@ -259,6 +304,86 @@ describe('createBotWebhookServer', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app billing cycle request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/billing-cycle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initData: 'payload' })
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {}
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app open cycle request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/billing-cycle/open', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initData: 'payload' })
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {}
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app close cycle request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/billing-cycle/close', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initData: 'payload' })
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {}
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app rent update request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/rent/update', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initData: 'payload' })
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {}
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app utility bill add request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/utility-bills/add', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ initData: 'payload' })
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
ok: true,
|
||||
authorized: true,
|
||||
cycleState: {}
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts mini app approve member request', async () => {
|
||||
const response = await server.fetch(
|
||||
new Request('http://localhost/api/miniapp/admin/approve-member', {
|
||||
|
||||
@@ -56,6 +56,36 @@ export interface BotWebhookServerOptions {
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppBillingCycle?:
|
||||
| {
|
||||
path?: string
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppOpenCycle?:
|
||||
| {
|
||||
path?: string
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppCloseCycle?:
|
||||
| {
|
||||
path?: string
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppRentUpdate?:
|
||||
| {
|
||||
path?: string
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppAddUtilityBill?:
|
||||
| {
|
||||
path?: string
|
||||
handler: (request: Request) => Promise<Response>
|
||||
}
|
||||
| undefined
|
||||
miniAppLocalePreference?:
|
||||
| {
|
||||
path?: string
|
||||
@@ -106,6 +136,15 @@ export function createBotWebhookServer(options: BotWebhookServerOptions): {
|
||||
options.miniAppUpsertUtilityCategory?.path ?? '/api/miniapp/admin/utility-categories/upsert'
|
||||
const miniAppPromoteMemberPath =
|
||||
options.miniAppPromoteMember?.path ?? '/api/miniapp/admin/members/promote'
|
||||
const miniAppBillingCyclePath =
|
||||
options.miniAppBillingCycle?.path ?? '/api/miniapp/admin/billing-cycle'
|
||||
const miniAppOpenCyclePath =
|
||||
options.miniAppOpenCycle?.path ?? '/api/miniapp/admin/billing-cycle/open'
|
||||
const miniAppCloseCyclePath =
|
||||
options.miniAppCloseCycle?.path ?? '/api/miniapp/admin/billing-cycle/close'
|
||||
const miniAppRentUpdatePath = options.miniAppRentUpdate?.path ?? '/api/miniapp/admin/rent/update'
|
||||
const miniAppAddUtilityBillPath =
|
||||
options.miniAppAddUtilityBill?.path ?? '/api/miniapp/admin/utility-bills/add'
|
||||
const miniAppLocalePreferencePath =
|
||||
options.miniAppLocalePreference?.path ?? '/api/miniapp/preferences/locale'
|
||||
const schedulerPathPrefix = options.scheduler
|
||||
@@ -159,6 +198,26 @@ export function createBotWebhookServer(options: BotWebhookServerOptions): {
|
||||
return await options.miniAppPromoteMember.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppBillingCycle && url.pathname === miniAppBillingCyclePath) {
|
||||
return await options.miniAppBillingCycle.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppOpenCycle && url.pathname === miniAppOpenCyclePath) {
|
||||
return await options.miniAppOpenCycle.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppCloseCycle && url.pathname === miniAppCloseCyclePath) {
|
||||
return await options.miniAppCloseCycle.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppRentUpdate && url.pathname === miniAppRentUpdatePath) {
|
||||
return await options.miniAppRentUpdate.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppAddUtilityBill && url.pathname === miniAppAddUtilityBillPath) {
|
||||
return await options.miniAppAddUtilityBill.handler(request)
|
||||
}
|
||||
|
||||
if (options.miniAppLocalePreference && url.pathname === miniAppLocalePreferencePath) {
|
||||
return await options.miniAppLocalePreference.handler(request)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user