Compare commits
5 Commits
3949c9add1
...
feat/payme
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e06bc12097 | ||
|
|
f490eecd11 | ||
|
|
ab69711e87 | ||
| c7e685ea08 | |||
|
|
c8477de5d2 |
@@ -16,3 +16,23 @@ SMTP_FROM=Playzer <no-reply@example.com>
|
|||||||
# Google OAuth
|
# Google OAuth
|
||||||
GOOGLE_CLIENT_ID=your-google-client-id
|
GOOGLE_CLIENT_ID=your-google-client-id
|
||||||
GOOGLE_CLIENT_SECRET=your-google-client-secret
|
GOOGLE_CLIENT_SECRET=your-google-client-secret
|
||||||
|
|
||||||
|
# Billing / Subscriptions
|
||||||
|
BILLING_ENV=sandbox
|
||||||
|
FRONTEND_BASE_URL=http://localhost:5173
|
||||||
|
|
||||||
|
# Stripe
|
||||||
|
STRIPE_SECRET_KEY=sk_test_your-stripe-secret-key
|
||||||
|
STRIPE_WEBHOOK_SECRET=whsec_your-webhook-secret
|
||||||
|
# Price IDs por plan y moneda (ajustar según tus products/prices en Stripe)
|
||||||
|
STRIPE_PRICE_ID_USD_BASIC=price_basic_usd
|
||||||
|
STRIPE_PRICE_ID_USD_ADVANCED=price_advanced_usd
|
||||||
|
STRIPE_PRICE_ID_USD_ENTERPRISE=price_enterprise_usd
|
||||||
|
|
||||||
|
# Mercado Pago (Argentina)
|
||||||
|
MERCADOPAGO_ACCESS_TOKEN=TEST-your-access-token
|
||||||
|
MERCADOPAGO_WEBHOOK_SECRET=your-webhook-secret
|
||||||
|
# Plan IDs por plan (ajustar según tus planes de suscripción en MP)
|
||||||
|
MERCADOPAGO_PLAN_ID_ARS_BASIC=2c938084...
|
||||||
|
MERCADOPAGO_PLAN_ID_ARS_ADVANCED=2c938084...
|
||||||
|
MERCADOPAGO_PLAN_ID_ARS_ENTERPRISE=2c938084...
|
||||||
|
|||||||
@@ -24,12 +24,14 @@
|
|||||||
"dotenv": "^17.4.1",
|
"dotenv": "^17.4.1",
|
||||||
"hono": "4.12.10",
|
"hono": "4.12.10",
|
||||||
"mailtrap": "^4.5.1",
|
"mailtrap": "^4.5.1",
|
||||||
|
"mercadopago": "^3.1.0",
|
||||||
"nodemailer": "^8.0.5",
|
"nodemailer": "^8.0.5",
|
||||||
"pg": "^8.20.0",
|
"pg": "^8.20.0",
|
||||||
"pino": "10.3.1",
|
"pino": "10.3.1",
|
||||||
"pino-pretty": "13.1.3",
|
"pino-pretty": "13.1.3",
|
||||||
"pino-std-serializers": "7.1.0",
|
"pino-std-serializers": "7.1.0",
|
||||||
"prisma": "^7",
|
"prisma": "^7",
|
||||||
|
"stripe": "^22.2.2",
|
||||||
"uuid": "^13.0.0"
|
"uuid": "^13.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
52
apps/backend/prisma/billing.prisma
Normal file
52
apps/backend/prisma/billing.prisma
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
enum BillingProvider {
|
||||||
|
STRIPE
|
||||||
|
MERCADOPAGO
|
||||||
|
PAYPAL
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BillingStatus {
|
||||||
|
TRIAL
|
||||||
|
ACTIVE
|
||||||
|
PAST_DUE
|
||||||
|
CANCELED
|
||||||
|
SUSPENDED
|
||||||
|
}
|
||||||
|
|
||||||
|
model ComplexBilling {
|
||||||
|
complexId String @id @map("complex_id") @db.Uuid
|
||||||
|
status BillingStatus @default(TRIAL)
|
||||||
|
planCode String @map("plan_code") @db.VarChar(10)
|
||||||
|
currency String @db.VarChar(3)
|
||||||
|
provider BillingProvider?
|
||||||
|
providerCustomerId String? @map("provider_customer_id")
|
||||||
|
providerSubscriptionId String? @map("provider_subscription_id")
|
||||||
|
providerPreapprovalId String? @map("provider_preapproval_id")
|
||||||
|
currentPeriodStart DateTime? @map("current_period_start")
|
||||||
|
currentPeriodEnd DateTime? @map("current_period_end")
|
||||||
|
trialEndsAt DateTime? @map("trial_ends_at")
|
||||||
|
canceledAt DateTime? @map("canceled_at")
|
||||||
|
suspendedAt DateTime? @map("suspended_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
complex Complex @relation(fields: [complexId], references: [id], onDelete: Cascade)
|
||||||
|
events BillingEvent[]
|
||||||
|
|
||||||
|
@@map("complex_billings")
|
||||||
|
}
|
||||||
|
|
||||||
|
model BillingEvent {
|
||||||
|
id String @id @db.Uuid
|
||||||
|
complexId String @map("complex_id") @db.Uuid
|
||||||
|
eventType String @map("event_type") @db.VarChar(100)
|
||||||
|
provider BillingProvider
|
||||||
|
providerEventId String? @unique @map("provider_event_id")
|
||||||
|
providerData Json? @map("provider_data")
|
||||||
|
previousStatus BillingStatus? @map("previous_status")
|
||||||
|
newStatus BillingStatus? @map("new_status")
|
||||||
|
processedAt DateTime @default(now()) @map("processed_at")
|
||||||
|
billing ComplexBilling @relation(fields: [complexId], references: [complexId])
|
||||||
|
|
||||||
|
@@index([provider, providerEventId])
|
||||||
|
@@index([complexId])
|
||||||
|
@@map("billing_events")
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ model Complex {
|
|||||||
invitations ComplexInvitation[]
|
invitations ComplexInvitation[]
|
||||||
courts Court[]
|
courts Court[]
|
||||||
recurringGroups RecurringBookingGroup[]
|
recurringGroups RecurringBookingGroup[]
|
||||||
|
billing ComplexBilling?
|
||||||
|
|
||||||
@@index([planCode])
|
@@index([planCode])
|
||||||
@@index([complexSlug])
|
@@index([complexSlug])
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "BillingProvider" AS ENUM ('STRIPE', 'MERCADOPAGO', 'PAYPAL');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "BillingStatus" AS ENUM ('TRIAL', 'ACTIVE', 'PAST_DUE', 'CANCELED', 'SUSPENDED');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "complex_billings" (
|
||||||
|
"complex_id" UUID NOT NULL,
|
||||||
|
"status" "BillingStatus" NOT NULL DEFAULT 'TRIAL',
|
||||||
|
"plan_code" VARCHAR(10) NOT NULL,
|
||||||
|
"currency" VARCHAR(3) NOT NULL,
|
||||||
|
"provider" "BillingProvider",
|
||||||
|
"provider_customer_id" TEXT,
|
||||||
|
"provider_subscription_id" TEXT,
|
||||||
|
"provider_preapproval_id" TEXT,
|
||||||
|
"current_period_start" TIMESTAMP(3),
|
||||||
|
"current_period_end" TIMESTAMP(3),
|
||||||
|
"trial_ends_at" TIMESTAMP(3),
|
||||||
|
"canceled_at" TIMESTAMP(3),
|
||||||
|
"suspended_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "complex_billings_pkey" PRIMARY KEY ("complex_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "billing_events" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"complex_id" UUID NOT NULL,
|
||||||
|
"event_type" VARCHAR(100) NOT NULL,
|
||||||
|
"provider" "BillingProvider" NOT NULL,
|
||||||
|
"provider_event_id" TEXT,
|
||||||
|
"provider_data" JSONB,
|
||||||
|
"previous_status" "BillingStatus",
|
||||||
|
"new_status" "BillingStatus",
|
||||||
|
"processed_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "billing_events_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "billing_events_provider_event_id_key" ON "billing_events"("provider_event_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_events_provider_provider_event_id_idx" ON "billing_events"("provider", "provider_event_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_events_complex_id_idx" ON "billing_events"("complex_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "complex_billings" ADD CONSTRAINT "complex_billings_complex_id_fkey" FOREIGN KEY ("complex_id") REFERENCES "complexes"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "billing_events" ADD CONSTRAINT "billing_events_complex_id_fkey" FOREIGN KEY ("complex_id") REFERENCES "complex_billings"("complex_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
@@ -37,6 +37,16 @@ export type Account = Prisma.AccountModel
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
export type Verification = Prisma.VerificationModel
|
export type Verification = Prisma.VerificationModel
|
||||||
|
/**
|
||||||
|
* Model ComplexBilling
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type ComplexBilling = Prisma.ComplexBillingModel
|
||||||
|
/**
|
||||||
|
* Model BillingEvent
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type BillingEvent = Prisma.BillingEventModel
|
||||||
/**
|
/**
|
||||||
* Model Complex
|
* Model Complex
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -61,6 +61,16 @@ export type Account = Prisma.AccountModel
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
export type Verification = Prisma.VerificationModel
|
export type Verification = Prisma.VerificationModel
|
||||||
|
/**
|
||||||
|
* Model ComplexBilling
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type ComplexBilling = Prisma.ComplexBillingModel
|
||||||
|
/**
|
||||||
|
* Model BillingEvent
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export type BillingEvent = Prisma.BillingEventModel
|
||||||
/**
|
/**
|
||||||
* Model Complex
|
* Model Complex
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -187,6 +187,20 @@ export type UuidFilter<$PrismaModel = never> = {
|
|||||||
not?: Prisma.NestedUuidFilter<$PrismaModel> | string
|
not?: Prisma.NestedUuidFilter<$PrismaModel> | string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type EnumBillingStatusFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel> | $Enums.BillingStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingProviderNullableFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel> | $Enums.BillingProvider | null
|
||||||
|
}
|
||||||
|
|
||||||
export type UuidWithAggregatesFilter<$PrismaModel = never> = {
|
export type UuidWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
||||||
@@ -202,6 +216,111 @@ export type UuidWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedStringFilter<$PrismaModel>
|
_max?: Prisma.NestedStringFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type EnumBillingStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingStatusWithAggregatesFilter<$PrismaModel> | $Enums.BillingStatus
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingProviderNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingProviderNullableWithAggregatesFilter<$PrismaModel> | $Enums.BillingProvider | null
|
||||||
|
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingProviderFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel> | $Enums.BillingProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
export type JsonNullableFilter<$PrismaModel = never> =
|
||||||
|
| Prisma.PatchUndefined<
|
||||||
|
Prisma.Either<Required<JsonNullableFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonNullableFilterBase<$PrismaModel>>, 'path'>>,
|
||||||
|
Required<JsonNullableFilterBase<$PrismaModel>>
|
||||||
|
>
|
||||||
|
| Prisma.OptionalFlat<Omit<Required<JsonNullableFilterBase<$PrismaModel>>, 'path'>>
|
||||||
|
|
||||||
|
export type JsonNullableFilterBase<$PrismaModel = never> = {
|
||||||
|
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
path?: string[]
|
||||||
|
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
|
||||||
|
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingStatusNullableFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel> | $Enums.BillingStatus | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingProviderWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingProviderWithAggregatesFilter<$PrismaModel> | $Enums.BillingProvider
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type JsonNullableWithAggregatesFilter<$PrismaModel = never> =
|
||||||
|
| Prisma.PatchUndefined<
|
||||||
|
Prisma.Either<Required<JsonNullableWithAggregatesFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonNullableWithAggregatesFilterBase<$PrismaModel>>, 'path'>>,
|
||||||
|
Required<JsonNullableWithAggregatesFilterBase<$PrismaModel>>
|
||||||
|
>
|
||||||
|
| Prisma.OptionalFlat<Omit<Required<JsonNullableWithAggregatesFilterBase<$PrismaModel>>, 'path'>>
|
||||||
|
|
||||||
|
export type JsonNullableWithAggregatesFilterBase<$PrismaModel = never> = {
|
||||||
|
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
path?: string[]
|
||||||
|
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
|
||||||
|
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedJsonNullableFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedJsonNullableFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EnumBillingStatusNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingStatusNullableWithAggregatesFilter<$PrismaModel> | $Enums.BillingStatus | null
|
||||||
|
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
export type EnumComplexUserRoleFilter<$PrismaModel = never> = {
|
export type EnumComplexUserRoleFilter<$PrismaModel = never> = {
|
||||||
equals?: $Enums.ComplexUserRole | Prisma.EnumComplexUserRoleFieldRefInput<$PrismaModel>
|
equals?: $Enums.ComplexUserRole | Prisma.EnumComplexUserRoleFieldRefInput<$PrismaModel>
|
||||||
in?: $Enums.ComplexUserRole[] | Prisma.ListEnumComplexUserRoleFieldRefInput<$PrismaModel>
|
in?: $Enums.ComplexUserRole[] | Prisma.ListEnumComplexUserRoleFieldRefInput<$PrismaModel>
|
||||||
@@ -604,6 +723,20 @@ export type NestedUuidFilter<$PrismaModel = never> = {
|
|||||||
not?: Prisma.NestedUuidFilter<$PrismaModel> | string
|
not?: Prisma.NestedUuidFilter<$PrismaModel> | string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingStatusFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel> | $Enums.BillingStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingProviderNullableFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel> | $Enums.BillingProvider | null
|
||||||
|
}
|
||||||
|
|
||||||
export type NestedUuidWithAggregatesFilter<$PrismaModel = never> = {
|
export type NestedUuidWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
||||||
@@ -618,6 +751,84 @@ export type NestedUuidWithAggregatesFilter<$PrismaModel = never> = {
|
|||||||
_max?: Prisma.NestedStringFilter<$PrismaModel>
|
_max?: Prisma.NestedStringFilter<$PrismaModel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingStatusWithAggregatesFilter<$PrismaModel> | $Enums.BillingStatus
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingStatusFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingProviderNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingProviderNullableWithAggregatesFilter<$PrismaModel> | $Enums.BillingProvider | null
|
||||||
|
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingProviderNullableFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingProviderFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel> | $Enums.BillingProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingStatusNullableFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel> | $Enums.BillingStatus | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingProviderWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingProvider | Prisma.EnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
in?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
notIn?: $Enums.BillingProvider[] | Prisma.ListEnumBillingProviderFieldRefInput<$PrismaModel>
|
||||||
|
not?: Prisma.NestedEnumBillingProviderWithAggregatesFilter<$PrismaModel> | $Enums.BillingProvider
|
||||||
|
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingProviderFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedJsonNullableFilter<$PrismaModel = never> =
|
||||||
|
| Prisma.PatchUndefined<
|
||||||
|
Prisma.Either<Required<NestedJsonNullableFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonNullableFilterBase<$PrismaModel>>, 'path'>>,
|
||||||
|
Required<NestedJsonNullableFilterBase<$PrismaModel>>
|
||||||
|
>
|
||||||
|
| Prisma.OptionalFlat<Omit<Required<NestedJsonNullableFilterBase<$PrismaModel>>, 'path'>>
|
||||||
|
|
||||||
|
export type NestedJsonNullableFilterBase<$PrismaModel = never> = {
|
||||||
|
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
path?: string[]
|
||||||
|
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
|
||||||
|
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
|
||||||
|
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
|
||||||
|
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
|
||||||
|
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NestedEnumBillingStatusNullableWithAggregatesFilter<$PrismaModel = never> = {
|
||||||
|
equals?: $Enums.BillingStatus | Prisma.EnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
in?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
notIn?: $Enums.BillingStatus[] | Prisma.ListEnumBillingStatusFieldRefInput<$PrismaModel> | null
|
||||||
|
not?: Prisma.NestedEnumBillingStatusNullableWithAggregatesFilter<$PrismaModel> | $Enums.BillingStatus | null
|
||||||
|
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
|
||||||
|
_min?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel>
|
||||||
|
_max?: Prisma.NestedEnumBillingStatusNullableFilter<$PrismaModel>
|
||||||
|
}
|
||||||
|
|
||||||
export type NestedEnumComplexUserRoleFilter<$PrismaModel = never> = {
|
export type NestedEnumComplexUserRoleFilter<$PrismaModel = never> = {
|
||||||
equals?: $Enums.ComplexUserRole | Prisma.EnumComplexUserRoleFieldRefInput<$PrismaModel>
|
equals?: $Enums.ComplexUserRole | Prisma.EnumComplexUserRoleFieldRefInput<$PrismaModel>
|
||||||
in?: $Enums.ComplexUserRole[] | Prisma.ListEnumComplexUserRoleFieldRefInput<$PrismaModel>
|
in?: $Enums.ComplexUserRole[] | Prisma.ListEnumComplexUserRoleFieldRefInput<$PrismaModel>
|
||||||
|
|||||||
@@ -9,6 +9,26 @@
|
|||||||
* 🟢 You can import this file directly.
|
* 🟢 You can import this file directly.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
export const BillingProvider = {
|
||||||
|
STRIPE: 'STRIPE',
|
||||||
|
MERCADOPAGO: 'MERCADOPAGO',
|
||||||
|
PAYPAL: 'PAYPAL'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type BillingProvider = (typeof BillingProvider)[keyof typeof BillingProvider]
|
||||||
|
|
||||||
|
|
||||||
|
export const BillingStatus = {
|
||||||
|
TRIAL: 'TRIAL',
|
||||||
|
ACTIVE: 'ACTIVE',
|
||||||
|
PAST_DUE: 'PAST_DUE',
|
||||||
|
CANCELED: 'CANCELED',
|
||||||
|
SUSPENDED: 'SUSPENDED'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type BillingStatus = (typeof BillingStatus)[keyof typeof BillingStatus]
|
||||||
|
|
||||||
|
|
||||||
export const ComplexUserRole = {
|
export const ComplexUserRole = {
|
||||||
ADMIN: 'ADMIN',
|
ADMIN: 'ADMIN',
|
||||||
EMPLOYEE: 'EMPLOYEE'
|
EMPLOYEE: 'EMPLOYEE'
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -388,6 +388,8 @@ export const ModelName = {
|
|||||||
Session: 'Session',
|
Session: 'Session',
|
||||||
Account: 'Account',
|
Account: 'Account',
|
||||||
Verification: 'Verification',
|
Verification: 'Verification',
|
||||||
|
ComplexBilling: 'ComplexBilling',
|
||||||
|
BillingEvent: 'BillingEvent',
|
||||||
Complex: 'Complex',
|
Complex: 'Complex',
|
||||||
ComplexUser: 'ComplexUser',
|
ComplexUser: 'ComplexUser',
|
||||||
ComplexInvitation: 'ComplexInvitation',
|
ComplexInvitation: 'ComplexInvitation',
|
||||||
@@ -416,7 +418,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
|||||||
omit: GlobalOmitOptions
|
omit: GlobalOmitOptions
|
||||||
}
|
}
|
||||||
meta: {
|
meta: {
|
||||||
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtMaintenance" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "courtBookingLog" | "recurringBookingGroup" | "passwordResetRequest" | "plan"
|
modelProps: "user" | "session" | "account" | "verification" | "complexBilling" | "billingEvent" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtMaintenance" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "courtBookingLog" | "recurringBookingGroup" | "passwordResetRequest" | "plan"
|
||||||
txIsolationLevel: TransactionIsolationLevel
|
txIsolationLevel: TransactionIsolationLevel
|
||||||
}
|
}
|
||||||
model: {
|
model: {
|
||||||
@@ -716,6 +718,154 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ComplexBilling: {
|
||||||
|
payload: Prisma.$ComplexBillingPayload<ExtArgs>
|
||||||
|
fields: Prisma.ComplexBillingFieldRefs
|
||||||
|
operations: {
|
||||||
|
findUnique: {
|
||||||
|
args: Prisma.ComplexBillingFindUniqueArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload> | null
|
||||||
|
}
|
||||||
|
findUniqueOrThrow: {
|
||||||
|
args: Prisma.ComplexBillingFindUniqueOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
findFirst: {
|
||||||
|
args: Prisma.ComplexBillingFindFirstArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload> | null
|
||||||
|
}
|
||||||
|
findFirstOrThrow: {
|
||||||
|
args: Prisma.ComplexBillingFindFirstOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
findMany: {
|
||||||
|
args: Prisma.ComplexBillingFindManyArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>[]
|
||||||
|
}
|
||||||
|
create: {
|
||||||
|
args: Prisma.ComplexBillingCreateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
createMany: {
|
||||||
|
args: Prisma.ComplexBillingCreateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
createManyAndReturn: {
|
||||||
|
args: Prisma.ComplexBillingCreateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>[]
|
||||||
|
}
|
||||||
|
delete: {
|
||||||
|
args: Prisma.ComplexBillingDeleteArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
update: {
|
||||||
|
args: Prisma.ComplexBillingUpdateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
deleteMany: {
|
||||||
|
args: Prisma.ComplexBillingDeleteManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateMany: {
|
||||||
|
args: Prisma.ComplexBillingUpdateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateManyAndReturn: {
|
||||||
|
args: Prisma.ComplexBillingUpdateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>[]
|
||||||
|
}
|
||||||
|
upsert: {
|
||||||
|
args: Prisma.ComplexBillingUpsertArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexBillingPayload>
|
||||||
|
}
|
||||||
|
aggregate: {
|
||||||
|
args: Prisma.ComplexBillingAggregateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.AggregateComplexBilling>
|
||||||
|
}
|
||||||
|
groupBy: {
|
||||||
|
args: Prisma.ComplexBillingGroupByArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.ComplexBillingGroupByOutputType>[]
|
||||||
|
}
|
||||||
|
count: {
|
||||||
|
args: Prisma.ComplexBillingCountArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.ComplexBillingCountAggregateOutputType> | number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BillingEvent: {
|
||||||
|
payload: Prisma.$BillingEventPayload<ExtArgs>
|
||||||
|
fields: Prisma.BillingEventFieldRefs
|
||||||
|
operations: {
|
||||||
|
findUnique: {
|
||||||
|
args: Prisma.BillingEventFindUniqueArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload> | null
|
||||||
|
}
|
||||||
|
findUniqueOrThrow: {
|
||||||
|
args: Prisma.BillingEventFindUniqueOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
findFirst: {
|
||||||
|
args: Prisma.BillingEventFindFirstArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload> | null
|
||||||
|
}
|
||||||
|
findFirstOrThrow: {
|
||||||
|
args: Prisma.BillingEventFindFirstOrThrowArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
findMany: {
|
||||||
|
args: Prisma.BillingEventFindManyArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>[]
|
||||||
|
}
|
||||||
|
create: {
|
||||||
|
args: Prisma.BillingEventCreateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
createMany: {
|
||||||
|
args: Prisma.BillingEventCreateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
createManyAndReturn: {
|
||||||
|
args: Prisma.BillingEventCreateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>[]
|
||||||
|
}
|
||||||
|
delete: {
|
||||||
|
args: Prisma.BillingEventDeleteArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
update: {
|
||||||
|
args: Prisma.BillingEventUpdateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
deleteMany: {
|
||||||
|
args: Prisma.BillingEventDeleteManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateMany: {
|
||||||
|
args: Prisma.BillingEventUpdateManyArgs<ExtArgs>
|
||||||
|
result: BatchPayload
|
||||||
|
}
|
||||||
|
updateManyAndReturn: {
|
||||||
|
args: Prisma.BillingEventUpdateManyAndReturnArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>[]
|
||||||
|
}
|
||||||
|
upsert: {
|
||||||
|
args: Prisma.BillingEventUpsertArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.PayloadToResult<Prisma.$BillingEventPayload>
|
||||||
|
}
|
||||||
|
aggregate: {
|
||||||
|
args: Prisma.BillingEventAggregateArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.AggregateBillingEvent>
|
||||||
|
}
|
||||||
|
groupBy: {
|
||||||
|
args: Prisma.BillingEventGroupByArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.BillingEventGroupByOutputType>[]
|
||||||
|
}
|
||||||
|
count: {
|
||||||
|
args: Prisma.BillingEventCountArgs<ExtArgs>
|
||||||
|
result: runtime.Types.Utils.Optional<Prisma.BillingEventCountAggregateOutputType> | number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Complex: {
|
Complex: {
|
||||||
payload: Prisma.$ComplexPayload<ExtArgs>
|
payload: Prisma.$ComplexPayload<ExtArgs>
|
||||||
fields: Prisma.ComplexFieldRefs
|
fields: Prisma.ComplexFieldRefs
|
||||||
@@ -1785,6 +1935,42 @@ export const VerificationScalarFieldEnum = {
|
|||||||
export type VerificationScalarFieldEnum = (typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
|
export type VerificationScalarFieldEnum = (typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const ComplexBillingScalarFieldEnum = {
|
||||||
|
complexId: 'complexId',
|
||||||
|
status: 'status',
|
||||||
|
planCode: 'planCode',
|
||||||
|
currency: 'currency',
|
||||||
|
provider: 'provider',
|
||||||
|
providerCustomerId: 'providerCustomerId',
|
||||||
|
providerSubscriptionId: 'providerSubscriptionId',
|
||||||
|
providerPreapprovalId: 'providerPreapprovalId',
|
||||||
|
currentPeriodStart: 'currentPeriodStart',
|
||||||
|
currentPeriodEnd: 'currentPeriodEnd',
|
||||||
|
trialEndsAt: 'trialEndsAt',
|
||||||
|
canceledAt: 'canceledAt',
|
||||||
|
suspendedAt: 'suspendedAt',
|
||||||
|
createdAt: 'createdAt',
|
||||||
|
updatedAt: 'updatedAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type ComplexBillingScalarFieldEnum = (typeof ComplexBillingScalarFieldEnum)[keyof typeof ComplexBillingScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const BillingEventScalarFieldEnum = {
|
||||||
|
id: 'id',
|
||||||
|
complexId: 'complexId',
|
||||||
|
eventType: 'eventType',
|
||||||
|
provider: 'provider',
|
||||||
|
providerEventId: 'providerEventId',
|
||||||
|
providerData: 'providerData',
|
||||||
|
previousStatus: 'previousStatus',
|
||||||
|
newStatus: 'newStatus',
|
||||||
|
processedAt: 'processedAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type BillingEventScalarFieldEnum = (typeof BillingEventScalarFieldEnum)[keyof typeof BillingEventScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
export const ComplexScalarFieldEnum = {
|
export const ComplexScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
complexName: 'complexName',
|
complexName: 'complexName',
|
||||||
@@ -1991,6 +2177,14 @@ export const SortOrder = {
|
|||||||
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
|
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
|
||||||
|
|
||||||
|
|
||||||
|
export const NullableJsonNullValueInput = {
|
||||||
|
DbNull: DbNull,
|
||||||
|
JsonNull: JsonNull
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type NullableJsonNullValueInput = (typeof NullableJsonNullValueInput)[keyof typeof NullableJsonNullValueInput]
|
||||||
|
|
||||||
|
|
||||||
export const JsonNullValueInput = {
|
export const JsonNullValueInput = {
|
||||||
JsonNull: JsonNull
|
JsonNull: JsonNull
|
||||||
} as const
|
} as const
|
||||||
@@ -2078,6 +2272,48 @@ export type ListFloatFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaMode
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'BillingStatus'
|
||||||
|
*/
|
||||||
|
export type EnumBillingStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BillingStatus'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'BillingStatus[]'
|
||||||
|
*/
|
||||||
|
export type ListEnumBillingStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BillingStatus[]'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'BillingProvider'
|
||||||
|
*/
|
||||||
|
export type EnumBillingProviderFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BillingProvider'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'BillingProvider[]'
|
||||||
|
*/
|
||||||
|
export type ListEnumBillingProviderFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BillingProvider[]'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'Json'
|
||||||
|
*/
|
||||||
|
export type JsonFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Json'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reference to a field of type 'QueryMode'
|
||||||
|
*/
|
||||||
|
export type EnumQueryModeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QueryMode'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reference to a field of type 'ComplexUserRole'
|
* Reference to a field of type 'ComplexUserRole'
|
||||||
*/
|
*/
|
||||||
@@ -2161,20 +2397,6 @@ export type EnumRecurringBookingGroupStatusFieldRefInput<$PrismaModel> = FieldRe
|
|||||||
export type ListEnumRecurringBookingGroupStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'RecurringBookingGroupStatus[]'>
|
export type ListEnumRecurringBookingGroupStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'RecurringBookingGroupStatus[]'>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reference to a field of type 'Json'
|
|
||||||
*/
|
|
||||||
export type JsonFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Json'>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reference to a field of type 'QueryMode'
|
|
||||||
*/
|
|
||||||
export type EnumQueryModeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QueryMode'>
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Batch Payload for updateMany & deleteMany & createMany
|
* Batch Payload for updateMany & deleteMany & createMany
|
||||||
*/
|
*/
|
||||||
@@ -2274,6 +2496,8 @@ export type GlobalOmitConfig = {
|
|||||||
session?: Prisma.SessionOmit
|
session?: Prisma.SessionOmit
|
||||||
account?: Prisma.AccountOmit
|
account?: Prisma.AccountOmit
|
||||||
verification?: Prisma.VerificationOmit
|
verification?: Prisma.VerificationOmit
|
||||||
|
complexBilling?: Prisma.ComplexBillingOmit
|
||||||
|
billingEvent?: Prisma.BillingEventOmit
|
||||||
complex?: Prisma.ComplexOmit
|
complex?: Prisma.ComplexOmit
|
||||||
complexUser?: Prisma.ComplexUserOmit
|
complexUser?: Prisma.ComplexUserOmit
|
||||||
complexInvitation?: Prisma.ComplexInvitationOmit
|
complexInvitation?: Prisma.ComplexInvitationOmit
|
||||||
|
|||||||
@@ -55,6 +55,8 @@ export const ModelName = {
|
|||||||
Session: 'Session',
|
Session: 'Session',
|
||||||
Account: 'Account',
|
Account: 'Account',
|
||||||
Verification: 'Verification',
|
Verification: 'Verification',
|
||||||
|
ComplexBilling: 'ComplexBilling',
|
||||||
|
BillingEvent: 'BillingEvent',
|
||||||
Complex: 'Complex',
|
Complex: 'Complex',
|
||||||
ComplexUser: 'ComplexUser',
|
ComplexUser: 'ComplexUser',
|
||||||
ComplexInvitation: 'ComplexInvitation',
|
ComplexInvitation: 'ComplexInvitation',
|
||||||
@@ -154,6 +156,42 @@ export const VerificationScalarFieldEnum = {
|
|||||||
export type VerificationScalarFieldEnum = (typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
|
export type VerificationScalarFieldEnum = (typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const ComplexBillingScalarFieldEnum = {
|
||||||
|
complexId: 'complexId',
|
||||||
|
status: 'status',
|
||||||
|
planCode: 'planCode',
|
||||||
|
currency: 'currency',
|
||||||
|
provider: 'provider',
|
||||||
|
providerCustomerId: 'providerCustomerId',
|
||||||
|
providerSubscriptionId: 'providerSubscriptionId',
|
||||||
|
providerPreapprovalId: 'providerPreapprovalId',
|
||||||
|
currentPeriodStart: 'currentPeriodStart',
|
||||||
|
currentPeriodEnd: 'currentPeriodEnd',
|
||||||
|
trialEndsAt: 'trialEndsAt',
|
||||||
|
canceledAt: 'canceledAt',
|
||||||
|
suspendedAt: 'suspendedAt',
|
||||||
|
createdAt: 'createdAt',
|
||||||
|
updatedAt: 'updatedAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type ComplexBillingScalarFieldEnum = (typeof ComplexBillingScalarFieldEnum)[keyof typeof ComplexBillingScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
|
export const BillingEventScalarFieldEnum = {
|
||||||
|
id: 'id',
|
||||||
|
complexId: 'complexId',
|
||||||
|
eventType: 'eventType',
|
||||||
|
provider: 'provider',
|
||||||
|
providerEventId: 'providerEventId',
|
||||||
|
providerData: 'providerData',
|
||||||
|
previousStatus: 'previousStatus',
|
||||||
|
newStatus: 'newStatus',
|
||||||
|
processedAt: 'processedAt'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type BillingEventScalarFieldEnum = (typeof BillingEventScalarFieldEnum)[keyof typeof BillingEventScalarFieldEnum]
|
||||||
|
|
||||||
|
|
||||||
export const ComplexScalarFieldEnum = {
|
export const ComplexScalarFieldEnum = {
|
||||||
id: 'id',
|
id: 'id',
|
||||||
complexName: 'complexName',
|
complexName: 'complexName',
|
||||||
@@ -360,6 +398,14 @@ export const SortOrder = {
|
|||||||
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
|
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
|
||||||
|
|
||||||
|
|
||||||
|
export const NullableJsonNullValueInput = {
|
||||||
|
DbNull: DbNull,
|
||||||
|
JsonNull: JsonNull
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type NullableJsonNullValueInput = (typeof NullableJsonNullValueInput)[keyof typeof NullableJsonNullValueInput]
|
||||||
|
|
||||||
|
|
||||||
export const JsonNullValueInput = {
|
export const JsonNullValueInput = {
|
||||||
JsonNull: JsonNull
|
JsonNull: JsonNull
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export type * from './models/User'
|
|||||||
export type * from './models/Session'
|
export type * from './models/Session'
|
||||||
export type * from './models/Account'
|
export type * from './models/Account'
|
||||||
export type * from './models/Verification'
|
export type * from './models/Verification'
|
||||||
|
export type * from './models/ComplexBilling'
|
||||||
|
export type * from './models/BillingEvent'
|
||||||
export type * from './models/Complex'
|
export type * from './models/Complex'
|
||||||
export type * from './models/ComplexUser'
|
export type * from './models/ComplexUser'
|
||||||
export type * from './models/ComplexInvitation'
|
export type * from './models/ComplexInvitation'
|
||||||
|
|||||||
@@ -235,6 +235,7 @@ export type ComplexWhereInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationListRelationFilter
|
invitations?: Prisma.ComplexInvitationListRelationFilter
|
||||||
courts?: Prisma.CourtListRelationFilter
|
courts?: Prisma.CourtListRelationFilter
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupListRelationFilter
|
recurringGroups?: Prisma.RecurringBookingGroupListRelationFilter
|
||||||
|
billing?: Prisma.XOR<Prisma.ComplexBillingNullableScalarRelationFilter, Prisma.ComplexBillingWhereInput> | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexOrderByWithRelationInput = {
|
export type ComplexOrderByWithRelationInput = {
|
||||||
@@ -254,6 +255,7 @@ export type ComplexOrderByWithRelationInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationOrderByRelationAggregateInput
|
invitations?: Prisma.ComplexInvitationOrderByRelationAggregateInput
|
||||||
courts?: Prisma.CourtOrderByRelationAggregateInput
|
courts?: Prisma.CourtOrderByRelationAggregateInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupOrderByRelationAggregateInput
|
recurringGroups?: Prisma.RecurringBookingGroupOrderByRelationAggregateInput
|
||||||
|
billing?: Prisma.ComplexBillingOrderByWithRelationInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexWhereUniqueInput = Prisma.AtLeast<{
|
export type ComplexWhereUniqueInput = Prisma.AtLeast<{
|
||||||
@@ -276,6 +278,7 @@ export type ComplexWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
invitations?: Prisma.ComplexInvitationListRelationFilter
|
invitations?: Prisma.ComplexInvitationListRelationFilter
|
||||||
courts?: Prisma.CourtListRelationFilter
|
courts?: Prisma.CourtListRelationFilter
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupListRelationFilter
|
recurringGroups?: Prisma.RecurringBookingGroupListRelationFilter
|
||||||
|
billing?: Prisma.XOR<Prisma.ComplexBillingNullableScalarRelationFilter, Prisma.ComplexBillingWhereInput> | null
|
||||||
}, "id" | "complexSlug">
|
}, "id" | "complexSlug">
|
||||||
|
|
||||||
export type ComplexOrderByWithAggregationInput = {
|
export type ComplexOrderByWithAggregationInput = {
|
||||||
@@ -328,6 +331,7 @@ export type ComplexCreateInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateInput = {
|
export type ComplexUncheckedCreateInput = {
|
||||||
@@ -346,6 +350,7 @@ export type ComplexUncheckedCreateInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUpdateInput = {
|
export type ComplexUpdateInput = {
|
||||||
@@ -364,6 +369,7 @@ export type ComplexUpdateInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateInput = {
|
export type ComplexUncheckedUpdateInput = {
|
||||||
@@ -382,6 +388,7 @@ export type ComplexUncheckedUpdateInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateManyInput = {
|
export type ComplexCreateManyInput = {
|
||||||
@@ -425,6 +432,11 @@ export type ComplexUncheckedUpdateManyInput = {
|
|||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ComplexScalarRelationFilter = {
|
||||||
|
is?: Prisma.ComplexWhereInput
|
||||||
|
isNot?: Prisma.ComplexWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
export type ComplexCountOrderByAggregateInput = {
|
export type ComplexCountOrderByAggregateInput = {
|
||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
complexName?: Prisma.SortOrder
|
complexName?: Prisma.SortOrder
|
||||||
@@ -467,11 +479,6 @@ export type ComplexMinOrderByAggregateInput = {
|
|||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexScalarRelationFilter = {
|
|
||||||
is?: Prisma.ComplexWhereInput
|
|
||||||
isNot?: Prisma.ComplexWhereInput
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ComplexListRelationFilter = {
|
export type ComplexListRelationFilter = {
|
||||||
every?: Prisma.ComplexWhereInput
|
every?: Prisma.ComplexWhereInput
|
||||||
some?: Prisma.ComplexWhereInput
|
some?: Prisma.ComplexWhereInput
|
||||||
@@ -482,6 +489,20 @@ export type ComplexOrderByRelationAggregateInput = {
|
|||||||
_count?: Prisma.SortOrder
|
_count?: Prisma.SortOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ComplexCreateNestedOneWithoutBillingInput = {
|
||||||
|
create?: Prisma.XOR<Prisma.ComplexCreateWithoutBillingInput, Prisma.ComplexUncheckedCreateWithoutBillingInput>
|
||||||
|
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutBillingInput
|
||||||
|
connect?: Prisma.ComplexWhereUniqueInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUpdateOneRequiredWithoutBillingNestedInput = {
|
||||||
|
create?: Prisma.XOR<Prisma.ComplexCreateWithoutBillingInput, Prisma.ComplexUncheckedCreateWithoutBillingInput>
|
||||||
|
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutBillingInput
|
||||||
|
upsert?: Prisma.ComplexUpsertWithoutBillingInput
|
||||||
|
connect?: Prisma.ComplexWhereUniqueInput
|
||||||
|
update?: Prisma.XOR<Prisma.XOR<Prisma.ComplexUpdateToOneWithWhereWithoutBillingInput, Prisma.ComplexUpdateWithoutBillingInput>, Prisma.ComplexUncheckedUpdateWithoutBillingInput>
|
||||||
|
}
|
||||||
|
|
||||||
export type ComplexCreateNestedOneWithoutUsersInput = {
|
export type ComplexCreateNestedOneWithoutUsersInput = {
|
||||||
create?: Prisma.XOR<Prisma.ComplexCreateWithoutUsersInput, Prisma.ComplexUncheckedCreateWithoutUsersInput>
|
create?: Prisma.XOR<Prisma.ComplexCreateWithoutUsersInput, Prisma.ComplexUncheckedCreateWithoutUsersInput>
|
||||||
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutUsersInput
|
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutUsersInput
|
||||||
@@ -580,6 +601,94 @@ export type ComplexUncheckedUpdateManyWithoutPlanNestedInput = {
|
|||||||
deleteMany?: Prisma.ComplexScalarWhereInput | Prisma.ComplexScalarWhereInput[]
|
deleteMany?: Prisma.ComplexScalarWhereInput | Prisma.ComplexScalarWhereInput[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ComplexCreateWithoutBillingInput = {
|
||||||
|
id: string
|
||||||
|
complexName: string
|
||||||
|
physicalAddress?: string | null
|
||||||
|
city?: string | null
|
||||||
|
state?: string | null
|
||||||
|
country?: string | null
|
||||||
|
complexSlug: string
|
||||||
|
adminEmail: string
|
||||||
|
createdAt?: Date | string
|
||||||
|
updatedAt?: Date | string
|
||||||
|
plan?: Prisma.PlanCreateNestedOneWithoutComplexesInput
|
||||||
|
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||||
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUncheckedCreateWithoutBillingInput = {
|
||||||
|
id: string
|
||||||
|
complexName: string
|
||||||
|
physicalAddress?: string | null
|
||||||
|
city?: string | null
|
||||||
|
state?: string | null
|
||||||
|
country?: string | null
|
||||||
|
complexSlug: string
|
||||||
|
adminEmail: string
|
||||||
|
planCode?: string | null
|
||||||
|
createdAt?: Date | string
|
||||||
|
updatedAt?: Date | string
|
||||||
|
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexCreateOrConnectWithoutBillingInput = {
|
||||||
|
where: Prisma.ComplexWhereUniqueInput
|
||||||
|
create: Prisma.XOR<Prisma.ComplexCreateWithoutBillingInput, Prisma.ComplexUncheckedCreateWithoutBillingInput>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUpsertWithoutBillingInput = {
|
||||||
|
update: Prisma.XOR<Prisma.ComplexUpdateWithoutBillingInput, Prisma.ComplexUncheckedUpdateWithoutBillingInput>
|
||||||
|
create: Prisma.XOR<Prisma.ComplexCreateWithoutBillingInput, Prisma.ComplexUncheckedCreateWithoutBillingInput>
|
||||||
|
where?: Prisma.ComplexWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUpdateToOneWithWhereWithoutBillingInput = {
|
||||||
|
where?: Prisma.ComplexWhereInput
|
||||||
|
data: Prisma.XOR<Prisma.ComplexUpdateWithoutBillingInput, Prisma.ComplexUncheckedUpdateWithoutBillingInput>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUpdateWithoutBillingInput = {
|
||||||
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
complexName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
physicalAddress?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
city?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
state?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
country?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
complexSlug?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
adminEmail?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
plan?: Prisma.PlanUpdateOneWithoutComplexesNestedInput
|
||||||
|
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||||
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ComplexUncheckedUpdateWithoutBillingInput = {
|
||||||
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
complexName?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
physicalAddress?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
city?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
state?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
country?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
complexSlug?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
adminEmail?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
|
planCode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||||
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
|
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
}
|
||||||
|
|
||||||
export type ComplexCreateWithoutUsersInput = {
|
export type ComplexCreateWithoutUsersInput = {
|
||||||
id: string
|
id: string
|
||||||
complexName: string
|
complexName: string
|
||||||
@@ -595,6 +704,7 @@ export type ComplexCreateWithoutUsersInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateWithoutUsersInput = {
|
export type ComplexUncheckedCreateWithoutUsersInput = {
|
||||||
@@ -612,6 +722,7 @@ export type ComplexUncheckedCreateWithoutUsersInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateOrConnectWithoutUsersInput = {
|
export type ComplexCreateOrConnectWithoutUsersInput = {
|
||||||
@@ -645,6 +756,7 @@ export type ComplexUpdateWithoutUsersInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateWithoutUsersInput = {
|
export type ComplexUncheckedUpdateWithoutUsersInput = {
|
||||||
@@ -662,6 +774,7 @@ export type ComplexUncheckedUpdateWithoutUsersInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateWithoutInvitationsInput = {
|
export type ComplexCreateWithoutInvitationsInput = {
|
||||||
@@ -679,6 +792,7 @@ export type ComplexCreateWithoutInvitationsInput = {
|
|||||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateWithoutInvitationsInput = {
|
export type ComplexUncheckedCreateWithoutInvitationsInput = {
|
||||||
@@ -696,6 +810,7 @@ export type ComplexUncheckedCreateWithoutInvitationsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateOrConnectWithoutInvitationsInput = {
|
export type ComplexCreateOrConnectWithoutInvitationsInput = {
|
||||||
@@ -729,6 +844,7 @@ export type ComplexUpdateWithoutInvitationsInput = {
|
|||||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateWithoutInvitationsInput = {
|
export type ComplexUncheckedUpdateWithoutInvitationsInput = {
|
||||||
@@ -746,6 +862,7 @@ export type ComplexUncheckedUpdateWithoutInvitationsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateWithoutCourtsInput = {
|
export type ComplexCreateWithoutCourtsInput = {
|
||||||
@@ -763,6 +880,7 @@ export type ComplexCreateWithoutCourtsInput = {
|
|||||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateWithoutCourtsInput = {
|
export type ComplexUncheckedCreateWithoutCourtsInput = {
|
||||||
@@ -780,6 +898,7 @@ export type ComplexUncheckedCreateWithoutCourtsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateOrConnectWithoutCourtsInput = {
|
export type ComplexCreateOrConnectWithoutCourtsInput = {
|
||||||
@@ -813,6 +932,7 @@ export type ComplexUpdateWithoutCourtsInput = {
|
|||||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateWithoutCourtsInput = {
|
export type ComplexUncheckedUpdateWithoutCourtsInput = {
|
||||||
@@ -830,6 +950,7 @@ export type ComplexUncheckedUpdateWithoutCourtsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateWithoutRecurringGroupsInput = {
|
export type ComplexCreateWithoutRecurringGroupsInput = {
|
||||||
@@ -847,6 +968,7 @@ export type ComplexCreateWithoutRecurringGroupsInput = {
|
|||||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateWithoutRecurringGroupsInput = {
|
export type ComplexUncheckedCreateWithoutRecurringGroupsInput = {
|
||||||
@@ -864,6 +986,7 @@ export type ComplexUncheckedCreateWithoutRecurringGroupsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateOrConnectWithoutRecurringGroupsInput = {
|
export type ComplexCreateOrConnectWithoutRecurringGroupsInput = {
|
||||||
@@ -897,6 +1020,7 @@ export type ComplexUpdateWithoutRecurringGroupsInput = {
|
|||||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateWithoutRecurringGroupsInput = {
|
export type ComplexUncheckedUpdateWithoutRecurringGroupsInput = {
|
||||||
@@ -914,6 +1038,7 @@ export type ComplexUncheckedUpdateWithoutRecurringGroupsInput = {
|
|||||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateWithoutPlanInput = {
|
export type ComplexCreateWithoutPlanInput = {
|
||||||
@@ -931,6 +1056,7 @@ export type ComplexCreateWithoutPlanInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedCreateWithoutPlanInput = {
|
export type ComplexUncheckedCreateWithoutPlanInput = {
|
||||||
@@ -948,6 +1074,7 @@ export type ComplexUncheckedCreateWithoutPlanInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedCreateNestedManyWithoutComplexInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedCreateNestedOneWithoutComplexInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexCreateOrConnectWithoutPlanInput = {
|
export type ComplexCreateOrConnectWithoutPlanInput = {
|
||||||
@@ -1021,6 +1148,7 @@ export type ComplexUpdateWithoutPlanInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateWithoutPlanInput = {
|
export type ComplexUncheckedUpdateWithoutPlanInput = {
|
||||||
@@ -1038,6 +1166,7 @@ export type ComplexUncheckedUpdateWithoutPlanInput = {
|
|||||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
recurringGroups?: Prisma.RecurringBookingGroupUncheckedUpdateManyWithoutComplexNestedInput
|
||||||
|
billing?: Prisma.ComplexBillingUncheckedUpdateOneWithoutComplexNestedInput
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ComplexUncheckedUpdateManyWithoutPlanInput = {
|
export type ComplexUncheckedUpdateManyWithoutPlanInput = {
|
||||||
@@ -1128,6 +1257,7 @@ export type ComplexSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
|||||||
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
||||||
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
||||||
recurringGroups?: boolean | Prisma.Complex$recurringGroupsArgs<ExtArgs>
|
recurringGroups?: boolean | Prisma.Complex$recurringGroupsArgs<ExtArgs>
|
||||||
|
billing?: boolean | Prisma.Complex$billingArgs<ExtArgs>
|
||||||
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
||||||
}, ExtArgs["result"]["complex"]>
|
}, ExtArgs["result"]["complex"]>
|
||||||
|
|
||||||
@@ -1182,6 +1312,7 @@ export type ComplexInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
|||||||
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
||||||
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
||||||
recurringGroups?: boolean | Prisma.Complex$recurringGroupsArgs<ExtArgs>
|
recurringGroups?: boolean | Prisma.Complex$recurringGroupsArgs<ExtArgs>
|
||||||
|
billing?: boolean | Prisma.Complex$billingArgs<ExtArgs>
|
||||||
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
export type ComplexIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type ComplexIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
@@ -1199,6 +1330,7 @@ export type $ComplexPayload<ExtArgs extends runtime.Types.Extensions.InternalArg
|
|||||||
invitations: Prisma.$ComplexInvitationPayload<ExtArgs>[]
|
invitations: Prisma.$ComplexInvitationPayload<ExtArgs>[]
|
||||||
courts: Prisma.$CourtPayload<ExtArgs>[]
|
courts: Prisma.$CourtPayload<ExtArgs>[]
|
||||||
recurringGroups: Prisma.$RecurringBookingGroupPayload<ExtArgs>[]
|
recurringGroups: Prisma.$RecurringBookingGroupPayload<ExtArgs>[]
|
||||||
|
billing: Prisma.$ComplexBillingPayload<ExtArgs> | null
|
||||||
}
|
}
|
||||||
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
||||||
id: string
|
id: string
|
||||||
@@ -1611,6 +1743,7 @@ export interface Prisma__ComplexClient<T, Null = never, ExtArgs extends runtime.
|
|||||||
invitations<T extends Prisma.Complex$invitationsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$invitationsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ComplexInvitationPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
invitations<T extends Prisma.Complex$invitationsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$invitationsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ComplexInvitationPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||||
courts<T extends Prisma.Complex$courtsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$courtsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$CourtPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
courts<T extends Prisma.Complex$courtsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$courtsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$CourtPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||||
recurringGroups<T extends Prisma.Complex$recurringGroupsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$recurringGroupsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$RecurringBookingGroupPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
recurringGroups<T extends Prisma.Complex$recurringGroupsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$recurringGroupsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$RecurringBookingGroupPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||||
|
billing<T extends Prisma.Complex$billingArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$billingArgs<ExtArgs>>): Prisma.Prisma__ComplexBillingClient<runtime.Types.Result.GetResult<Prisma.$ComplexBillingPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||||
/**
|
/**
|
||||||
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
||||||
* @param onfulfilled The callback to execute when the Promise is resolved.
|
* @param onfulfilled The callback to execute when the Promise is resolved.
|
||||||
@@ -2166,6 +2299,25 @@ export type Complex$recurringGroupsArgs<ExtArgs extends runtime.Types.Extensions
|
|||||||
distinct?: Prisma.RecurringBookingGroupScalarFieldEnum | Prisma.RecurringBookingGroupScalarFieldEnum[]
|
distinct?: Prisma.RecurringBookingGroupScalarFieldEnum | Prisma.RecurringBookingGroupScalarFieldEnum[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complex.billing
|
||||||
|
*/
|
||||||
|
export type Complex$billingArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
|
/**
|
||||||
|
* Select specific fields to fetch from the ComplexBilling
|
||||||
|
*/
|
||||||
|
select?: Prisma.ComplexBillingSelect<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Omit specific fields from the ComplexBilling
|
||||||
|
*/
|
||||||
|
omit?: Prisma.ComplexBillingOmit<ExtArgs> | null
|
||||||
|
/**
|
||||||
|
* Choose, which related nodes to fetch as well
|
||||||
|
*/
|
||||||
|
include?: Prisma.ComplexBillingInclude<ExtArgs> | null
|
||||||
|
where?: Prisma.ComplexBillingWhereInput
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Complex without action
|
* Complex without action
|
||||||
*/
|
*/
|
||||||
|
|||||||
176
apps/backend/src/lib/booking-utils.ts
Normal file
176
apps/backend/src/lib/booking-utils.ts
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
import type { DayOfWeek } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export type Slot = {
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const BOOKING_CODE_LENGTH = 6;
|
||||||
|
|
||||||
|
export const DAY_OF_WEEK_BY_INDEX: DayOfWeek[] = [
|
||||||
|
'SUNDAY',
|
||||||
|
'MONDAY',
|
||||||
|
'TUESDAY',
|
||||||
|
'WEDNESDAY',
|
||||||
|
'THURSDAY',
|
||||||
|
'FRIDAY',
|
||||||
|
'SATURDAY',
|
||||||
|
];
|
||||||
|
|
||||||
|
export function toMinutes(value: string): number {
|
||||||
|
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
||||||
|
return hours * 60 + minutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function minutesToTime(minutes: number): string {
|
||||||
|
const safeMinutes = Math.max(0, minutes);
|
||||||
|
const hours = Math.floor(safeMinutes / 60);
|
||||||
|
const mins = safeMinutes % 60;
|
||||||
|
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseIsoDate(date: string): { bookingDate: Date; dayOfWeek: DayOfWeek } {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new Error('La fecha debe tener formato YYYY-MM-DD.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
|
||||||
|
const bookingDate = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
|
||||||
|
if (
|
||||||
|
Number.isNaN(bookingDate.getTime()) ||
|
||||||
|
bookingDate.getUTCFullYear() !== year ||
|
||||||
|
bookingDate.getUTCMonth() + 1 !== month ||
|
||||||
|
bookingDate.getUTCDate() !== day
|
||||||
|
) {
|
||||||
|
throw new Error('La fecha enviada no es valida.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[bookingDate.getUTCDay()];
|
||||||
|
|
||||||
|
if (!dayOfWeek) {
|
||||||
|
throw new Error('No se pudo resolver el dia de la semana.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { bookingDate, dayOfWeek };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatIsoDate(date: Date): string {
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDayOfWeekValue(date: Date): DayOfWeek {
|
||||||
|
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()];
|
||||||
|
if (!dayOfWeek) {
|
||||||
|
throw new Error('No se pudo resolver el dia de la semana.');
|
||||||
|
}
|
||||||
|
return dayOfWeek;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateBookingCode(): string {
|
||||||
|
let code = '';
|
||||||
|
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
||||||
|
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSlots(
|
||||||
|
availability: Array<{ startTime: string; endTime: string }>,
|
||||||
|
slotDurationMinutes: number
|
||||||
|
): Slot[] {
|
||||||
|
const slots: Slot[] = [];
|
||||||
|
for (const range of availability) {
|
||||||
|
const start = toMinutes(range.startTime);
|
||||||
|
const end = toMinutes(range.endTime);
|
||||||
|
for (
|
||||||
|
let current = start;
|
||||||
|
current + slotDurationMinutes <= end;
|
||||||
|
current += slotDurationMinutes
|
||||||
|
) {
|
||||||
|
slots.push({
|
||||||
|
startTime: minutesToTime(current),
|
||||||
|
endTime: minutesToTime(current + slotDurationMinutes),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasOverlap(slot: Slot, existing: Slot): boolean {
|
||||||
|
return slot.startTime < existing.endTime && slot.endTime > existing.startTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
type PriceableCourt = {
|
||||||
|
basePrice: unknown;
|
||||||
|
priceRules: Array<{
|
||||||
|
dayOfWeek: DayOfWeek | null;
|
||||||
|
startTime: string | null;
|
||||||
|
endTime: string | null;
|
||||||
|
price: unknown;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resolveSlotPrice(court: PriceableCourt, dayOfWeek: DayOfWeek, slot: Slot): number {
|
||||||
|
const slotStart = toMinutes(slot.startTime);
|
||||||
|
const slotEnd = toMinutes(slot.endTime);
|
||||||
|
|
||||||
|
const matchingRules = court.priceRules
|
||||||
|
.filter((rule) => {
|
||||||
|
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) return false;
|
||||||
|
if (!rule.startTime || !rule.endTime) return true;
|
||||||
|
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
|
||||||
|
})
|
||||||
|
.sort((first, second) => {
|
||||||
|
const firstSpecificity =
|
||||||
|
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
|
||||||
|
const secondSpecificity =
|
||||||
|
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
|
||||||
|
return secondSpecificity - firstSpecificity;
|
||||||
|
});
|
||||||
|
|
||||||
|
return Number(matchingRules[0]?.price ?? court.basePrice);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertAvailabilityRanges(
|
||||||
|
availability: Array<{
|
||||||
|
dayOfWeek: DayOfWeek;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
}>
|
||||||
|
) {
|
||||||
|
const grouped = new Map<DayOfWeek, Array<{ start: number; end: number }>>();
|
||||||
|
|
||||||
|
for (const range of availability) {
|
||||||
|
const start = toMinutes(range.startTime);
|
||||||
|
const end = toMinutes(range.endTime);
|
||||||
|
|
||||||
|
if (start >= end) {
|
||||||
|
throw new Error(`El rango ${range.startTime}-${range.endTime} es invalido.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = grouped.get(range.dayOfWeek) ?? [];
|
||||||
|
current.push({ start, end });
|
||||||
|
grouped.set(range.dayOfWeek, current);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ranges of grouped.values()) {
|
||||||
|
ranges.sort((a, b) => a.start - b.start);
|
||||||
|
|
||||||
|
for (let index = 1; index < ranges.length; index += 1) {
|
||||||
|
const previous = ranges[index - 1];
|
||||||
|
const current = ranges[index];
|
||||||
|
|
||||||
|
if (previous.end > current.start) {
|
||||||
|
throw new Error('Hay rangos horarios superpuestos para el mismo dia.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
41
apps/backend/src/lib/complex-access.ts
Normal file
41
apps/backend/src/lib/complex-access.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export class ComplexAccessError extends Error {
|
||||||
|
status: 403 | 404;
|
||||||
|
|
||||||
|
constructor(message: string, status: 403 | 404 = 403) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'ComplexAccessError';
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureComplexAccess(complexId: string, userId: string) {
|
||||||
|
const complexUser = await db.complexUser.findUnique({
|
||||||
|
where: {
|
||||||
|
complexId_userId: {
|
||||||
|
complexId,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
complexName: true,
|
||||||
|
plan: {
|
||||||
|
select: {
|
||||||
|
rules: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!complexUser) {
|
||||||
|
throw new ComplexAccessError('No tienes permisos para administrar este complejo.', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
return complexUser.complex;
|
||||||
|
}
|
||||||
31
apps/backend/src/lib/slug.ts
Normal file
31
apps/backend/src/lib/slug.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
export function slugify(value: string): string {
|
||||||
|
return value
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[\u0300-\u036f]/g, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.trim()
|
||||||
|
.replace(/[^a-z0-9\s-]/g, '')
|
||||||
|
.replace(/\s+/g, '-')
|
||||||
|
.replace(/-+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function buildUniqueSlug(
|
||||||
|
source: string,
|
||||||
|
findExisting: (slug: string) => Promise<{ id: string } | null>
|
||||||
|
): Promise<string> {
|
||||||
|
const base = slugify(source);
|
||||||
|
const fallback = base.length > 0 ? base : `resource-${uuidv7().slice(0, 8)}`;
|
||||||
|
|
||||||
|
let candidate = fallback;
|
||||||
|
let index = 1;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const existing = await findExisting(candidate);
|
||||||
|
if (!existing) return candidate;
|
||||||
|
|
||||||
|
index += 1;
|
||||||
|
candidate = `${fallback}-${index}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||||
import { cancelRecurringGroupHandler } from '@/modules/admin-booking/handlers/cancel-recurring-group.handler';
|
import { cancelRecurringGroupHandler } from '@/modules/admin-booking/features/cancel-recurring-group/cancel-recurring-group.handler';
|
||||||
import { createAdminBookingHandler } from '@/modules/admin-booking/handlers/create-admin-booking.handler';
|
import { createAdminBookingHandler } from '@/modules/admin-booking/features/create-admin-booking/create-admin-booking.handler';
|
||||||
import { createAdminRecurringBookingHandler } from '@/modules/admin-booking/handlers/create-admin-recurring-booking.handler';
|
import { createAdminRecurringBookingHandler } from '@/modules/admin-booking/features/create-admin-recurring-booking/create-admin-recurring-booking.handler';
|
||||||
import { listAdminBookingsHandler } from '@/modules/admin-booking/handlers/list-admin-bookings.handler';
|
import { listAdminBookingsHandler } from '@/modules/admin-booking/features/list-admin-bookings/list-admin-bookings.handler';
|
||||||
import { listRecurringGroupsHandler } from '@/modules/admin-booking/handlers/list-recurring-groups.handler';
|
import { listRecurringGroupsHandler } from '@/modules/admin-booking/features/list-recurring-groups/list-recurring-groups.handler';
|
||||||
import { rescheduleAdminBookingHandler } from '@/modules/admin-booking/handlers/reschedule-admin-booking.handler';
|
import { rescheduleAdminBookingHandler } from '@/modules/admin-booking/features/reschedule-admin-booking/reschedule-admin-booking.handler';
|
||||||
import { updateAdminBookingStatusHandler } from '@/modules/admin-booking/handlers/update-admin-booking-status.handler';
|
import { updateAdminBookingStatusHandler } from '@/modules/admin-booking/features/update-admin-booking-status/update-admin-booking-status.handler';
|
||||||
import { updateRecurringGroupHandler } from '@/modules/admin-booking/handlers/update-recurring-group.handler';
|
import { updateRecurringGroupHandler } from '@/modules/admin-booking/features/update-recurring-group/update-recurring-group.handler';
|
||||||
import type { AppEnv } from '@/types/hono';
|
import type { AppEnv } from '@/types/hono';
|
||||||
import { zValidator } from '@hono/zod-validator';
|
import { zValidator } from '@hono/zod-validator';
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
export async function cancelRecurringGroup(
|
||||||
|
userId: string,
|
||||||
|
groupId: string
|
||||||
|
): Promise<Result<{ ok: boolean }>> {
|
||||||
|
const group = await db.recurringBookingGroup.findUnique({
|
||||||
|
where: { id: groupId },
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
users: { where: { userId }, select: { userId: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!group) {
|
||||||
|
return err(Errors.notFound('Grupo de reservas no encontrado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (group.complex.users.length === 0) {
|
||||||
|
return err(Errors.forbidden('No tienes permisos para administrar este complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (group.status === 'CANCELLED') {
|
||||||
|
return err(Errors.conflict('El grupo ya fue cancelado anteriormente.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||||
|
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
await tx.recurringBookingGroup.update({
|
||||||
|
where: { id: groupId },
|
||||||
|
data: { status: 'CANCELLED' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const futureBookings = await tx.courtBooking.findMany({
|
||||||
|
where: {
|
||||||
|
recurringGroupId: groupId,
|
||||||
|
bookingDate: { gte: todayStart },
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const booking of futureBookings) {
|
||||||
|
await tx.courtBookingLog.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
courtId: booking.courtId,
|
||||||
|
bookingDate: booking.bookingDate,
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
customerEmail: booking.customerEmail,
|
||||||
|
previousStatus: booking.status,
|
||||||
|
newStatus: 'CANCELLED',
|
||||||
|
changedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.courtBooking.delete({ where: { id: booking.id } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { cancelRecurringGroup } from './cancel-recurring-group.business';
|
||||||
|
|
||||||
|
type GroupIdParams = { groupId: string };
|
||||||
|
|
||||||
|
export async function cancelRecurringGroupHandler(c: AppContext) {
|
||||||
|
const { groupId } = c.req.valid('param' as never) as GroupIdParams;
|
||||||
|
const user = c.get('user');
|
||||||
|
|
||||||
|
return handleResult(c, await cancelRecurringGroup(user.id, groupId));
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import { isSlotInPast } from '@/lib/slot-validator';
|
||||||
|
import { evaluatePlanUsage, parsePlanRules } from '@/modules/plan/services/plan-rules.service';
|
||||||
|
import type { AdminBooking, CreateAdminBookingInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
import { AdminBookingServiceError } from '../../shared/errors';
|
||||||
|
import {
|
||||||
|
buildSlots,
|
||||||
|
ensureComplexAccess,
|
||||||
|
getDayOfWeek,
|
||||||
|
mapBookingResponse,
|
||||||
|
minutesToTime,
|
||||||
|
parseIsoDate,
|
||||||
|
resolvePrice,
|
||||||
|
toMinutes,
|
||||||
|
} from '../../shared/helpers';
|
||||||
|
|
||||||
|
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const BOOKING_CODE_LENGTH = 6;
|
||||||
|
|
||||||
|
function generateBookingCode(): string {
|
||||||
|
let code = '';
|
||||||
|
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
||||||
|
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAdminBooking(
|
||||||
|
userId: string,
|
||||||
|
complexId: string,
|
||||||
|
input: CreateAdminBookingInput
|
||||||
|
): Promise<Result<AdminBooking>> {
|
||||||
|
const complexResult = await ensureComplexAccess(complexId, userId);
|
||||||
|
if (!complexResult.ok) return err(complexResult.error);
|
||||||
|
const complex = complexResult.value;
|
||||||
|
|
||||||
|
const adminUser = await db.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { emailVerified: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!adminUser?.emailVerified) {
|
||||||
|
return err(Errors.forbidden('Debés verificar tu email para poder crear reservas.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const dateResult = parseIsoDate(input.date);
|
||||||
|
if (!dateResult.ok) return err(dateResult.error);
|
||||||
|
const bookingDate = dateResult.value;
|
||||||
|
|
||||||
|
const dayOfWeekResult = getDayOfWeek(bookingDate);
|
||||||
|
if (!dayOfWeekResult.ok) return err(dayOfWeekResult.error);
|
||||||
|
const dayOfWeek = dayOfWeekResult.value;
|
||||||
|
|
||||||
|
const court = await db.court.findFirst({
|
||||||
|
where: { id: input.courtId, complexId },
|
||||||
|
include: {
|
||||||
|
availabilities: {
|
||||||
|
where: { dayOfWeek },
|
||||||
|
orderBy: { startTime: 'asc' },
|
||||||
|
},
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
priceRules: {
|
||||||
|
where: { isActive: true },
|
||||||
|
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!court) {
|
||||||
|
return err(Errors.notFound('La cancha seleccionada no existe en el complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
||||||
|
const selectedStartMinutes = toMinutes(input.startTime);
|
||||||
|
const selectedEndMinutes = selectedStartMinutes + court.slotDurationMinutes;
|
||||||
|
const selectedSlot = { startTime: input.startTime, endTime: minutesToTime(selectedEndMinutes) };
|
||||||
|
|
||||||
|
const slotExists = validSlots.some(
|
||||||
|
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!slotExists) {
|
||||||
|
return err(Errors.conflict('El horario seleccionado no esta disponible para esa cancha.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSlotInPast(bookingDate, input.startTime, court.slotDurationMinutes)) {
|
||||||
|
return err(Errors.validation('No se pueden crear reservas en el pasado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const booking = await db.$transaction(async (tx) => {
|
||||||
|
if (complex.plan) {
|
||||||
|
const rules = parsePlanRules(complex.plan.rules);
|
||||||
|
const bookingsForDate = await tx.courtBooking.count({
|
||||||
|
where: {
|
||||||
|
bookingDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
court: { complexId },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const courtsCount = await tx.court.count({ where: { complexId } });
|
||||||
|
|
||||||
|
const violations = evaluatePlanUsage(rules, {
|
||||||
|
courtsCount,
|
||||||
|
bookingsToday: bookingsForDate,
|
||||||
|
});
|
||||||
|
const maxBookingsViolation = violations.find(
|
||||||
|
(v) => v.code === 'MAX_BOOKINGS_PER_DAY_REACHED'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (maxBookingsViolation) {
|
||||||
|
throw new AdminBookingServiceError(maxBookingsViolation.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlappingBooking = await tx.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
startTime: { lt: selectedSlot.endTime },
|
||||||
|
endTime: { gt: selectedSlot.startTime },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (overlappingBooking) {
|
||||||
|
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.courtBooking.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: generateBookingCode(),
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
customerName: input.customerName.trim(),
|
||||||
|
customerPhone: input.customerPhone.trim(),
|
||||||
|
customerEmail: input.customerEmail?.trim() ?? '',
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
recurringGroupId: null,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const price = resolvePrice(court, dayOfWeek, selectedSlot.startTime, selectedSlot.endTime);
|
||||||
|
return ok(mapBookingResponse({ ...booking, price }));
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
return err(Errors.conflict(error.message));
|
||||||
|
}
|
||||||
|
|
||||||
|
const prismaError = error as { code?: string; meta?: { target?: string[] | string } };
|
||||||
|
if (prismaError.code === 'P2002') {
|
||||||
|
const targets = Array.isArray(prismaError.meta?.target)
|
||||||
|
? prismaError.meta?.target
|
||||||
|
: [prismaError.meta?.target];
|
||||||
|
const isBookingCodeCollision = targets.some((target) =>
|
||||||
|
String(target).includes('booking_code')
|
||||||
|
);
|
||||||
|
if (isBookingCodeCollision) continue;
|
||||||
|
return err(Errors.conflict('El horario seleccionado ya fue reservado.'));
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return err(Errors.conflict('No se pudo generar un codigo de reserva unico. Intenta nuevamente.'));
|
||||||
|
}
|
||||||
@@ -1,11 +1,9 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
import { db } from '@/lib/prisma';
|
import { db } from '@/lib/prisma';
|
||||||
import {
|
|
||||||
AdminBookingServiceError,
|
|
||||||
createAdminBooking,
|
|
||||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { CreateAdminBookingInput } from '@repo/api-contract';
|
import type { CreateAdminBookingInput } from '@repo/api-contract';
|
||||||
|
import { createAdminBooking } from './create-admin-booking.business';
|
||||||
|
|
||||||
type ComplexIdParams = { complexId: string };
|
type ComplexIdParams = { complexId: string };
|
||||||
|
|
||||||
@@ -14,8 +12,10 @@ export async function createAdminBookingHandler(c: AppContext) {
|
|||||||
const payload = c.req.valid('json' as never) as CreateAdminBookingInput;
|
const payload = c.req.valid('json' as never) as CreateAdminBookingInput;
|
||||||
const user = c.get('user');
|
const user = c.get('user');
|
||||||
|
|
||||||
try {
|
const result = await createAdminBooking(user.id, complexId, payload);
|
||||||
const booking = await createAdminBooking(user.id, complexId, payload);
|
|
||||||
|
if (result.ok) {
|
||||||
|
const booking = result.value;
|
||||||
|
|
||||||
const complex = await db.complex.findUnique({
|
const complex = await db.complex.findUnique({
|
||||||
where: { id: complexId },
|
where: { id: complexId },
|
||||||
@@ -35,12 +35,7 @@ export async function createAdminBookingHandler(c: AppContext) {
|
|||||||
customerEmail: booking.customerEmail,
|
customerEmail: booking.customerEmail,
|
||||||
price: booking.price,
|
price: booking.price,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return c.json(booking, 201);
|
return handleResult(c, result, 201);
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
import { DayOfWeek as DayOfWeekEnum } from '@/generated/prisma/enums';
|
||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import { isSlotInPast } from '@/lib/slot-validator';
|
||||||
|
import {
|
||||||
|
evaluatePlanUsage,
|
||||||
|
isFeatureEnabled,
|
||||||
|
parsePlanRules,
|
||||||
|
} from '@/modules/plan/services/plan-rules.service';
|
||||||
|
import type { CreateRecurringBookingInput, RecurringBookingGroup } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
import { AdminBookingServiceError } from '../../shared/errors';
|
||||||
|
import {
|
||||||
|
buildSlots,
|
||||||
|
ensureComplexAccess,
|
||||||
|
formatIsoDate,
|
||||||
|
minutesToTime,
|
||||||
|
parseIsoDate,
|
||||||
|
toMinutes,
|
||||||
|
} from '../../shared/helpers';
|
||||||
|
|
||||||
|
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const BOOKING_CODE_LENGTH = 6;
|
||||||
|
const MAX_RECURRING_WEEKS = 52;
|
||||||
|
|
||||||
|
const DAY_OF_WEEK_BY_INDEX = [
|
||||||
|
DayOfWeekEnum.SUNDAY,
|
||||||
|
DayOfWeekEnum.MONDAY,
|
||||||
|
DayOfWeekEnum.TUESDAY,
|
||||||
|
DayOfWeekEnum.WEDNESDAY,
|
||||||
|
DayOfWeekEnum.THURSDAY,
|
||||||
|
DayOfWeekEnum.FRIDAY,
|
||||||
|
DayOfWeekEnum.SATURDAY,
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
type DayOfWeek = (typeof DAY_OF_WEEK_BY_INDEX)[number];
|
||||||
|
|
||||||
|
function generateBookingCode(): string {
|
||||||
|
let code = '';
|
||||||
|
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
||||||
|
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
function* generateRecurringDates(
|
||||||
|
startDate: Date,
|
||||||
|
endDate: Date | null,
|
||||||
|
dayOfWeek: number
|
||||||
|
): Generator<Date> {
|
||||||
|
const current = new Date(startDate);
|
||||||
|
current.setUTCDate(current.getUTCDate() + ((dayOfWeek - current.getUTCDay() + 7) % 7));
|
||||||
|
|
||||||
|
if (current < startDate) {
|
||||||
|
current.setUTCDate(current.getUTCDate() + 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxDate = endDate ?? new Date(startDate);
|
||||||
|
if (!endDate) {
|
||||||
|
maxDate.setUTCDate(maxDate.getUTCDate() + MAX_RECURRING_WEEKS * 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
while (current <= maxDate) {
|
||||||
|
yield new Date(current);
|
||||||
|
current.setUTCDate(current.getUTCDate() + 7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDayOfWeekValue(date: Date): Result<DayOfWeek> {
|
||||||
|
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()];
|
||||||
|
if (!dayOfWeek) {
|
||||||
|
return err(Errors.validation('No se pudo resolver el dia de la semana.'));
|
||||||
|
}
|
||||||
|
return ok(dayOfWeek);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAdminRecurringBooking(
|
||||||
|
userId: string,
|
||||||
|
complexId: string,
|
||||||
|
input: CreateRecurringBookingInput
|
||||||
|
): Promise<Result<RecurringBookingGroup>> {
|
||||||
|
const complexResult = await ensureComplexAccess(complexId, userId);
|
||||||
|
if (!complexResult.ok) return err(complexResult.error);
|
||||||
|
const complex = complexResult.value;
|
||||||
|
|
||||||
|
const adminUser = await db.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { emailVerified: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!adminUser?.emailVerified) {
|
||||||
|
return err(Errors.forbidden('Debés verificar tu email para poder crear reservas.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!complex.plan) {
|
||||||
|
return err(Errors.forbidden('El complejo no tiene un plan asignado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const rules = parsePlanRules(complex.plan.rules);
|
||||||
|
|
||||||
|
if (!isFeatureEnabled(rules, 'fixedSlots')) {
|
||||||
|
return err(
|
||||||
|
Errors.forbidden(
|
||||||
|
'Tu plan no permite la creación de turnos fijos. Comunicate con el administrador.'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const startDateResult = parseIsoDate(input.date);
|
||||||
|
if (!startDateResult.ok) return err(startDateResult.error);
|
||||||
|
const startDate = startDateResult.value;
|
||||||
|
|
||||||
|
const dayOfWeekResult = getDayOfWeekValue(startDate);
|
||||||
|
if (!dayOfWeekResult.ok) return err(dayOfWeekResult.error);
|
||||||
|
const dayOfWeek = dayOfWeekResult.value;
|
||||||
|
|
||||||
|
const endDateResult = input.recurringEndDate ? parseIsoDate(input.recurringEndDate) : null;
|
||||||
|
if (endDateResult && !endDateResult.ok) return err(endDateResult.error);
|
||||||
|
const endDate = endDateResult?.value ?? null;
|
||||||
|
|
||||||
|
if (endDate && endDate <= startDate) {
|
||||||
|
return err(Errors.validation('La fecha de fin debe ser posterior a la fecha de inicio.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const court = await db.court.findFirst({
|
||||||
|
where: { id: input.courtId, complexId },
|
||||||
|
include: {
|
||||||
|
availabilities: {
|
||||||
|
where: { dayOfWeek },
|
||||||
|
orderBy: { startTime: 'asc' },
|
||||||
|
},
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
priceRules: {
|
||||||
|
where: { isActive: true },
|
||||||
|
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!court) {
|
||||||
|
return err(Errors.notFound('La cancha seleccionada no existe en el complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
||||||
|
const selectedEndMinutes = toMinutes(input.startTime) + court.slotDurationMinutes;
|
||||||
|
const selectedSlot = { startTime: input.startTime, endTime: minutesToTime(selectedEndMinutes) };
|
||||||
|
|
||||||
|
const slotExists = validSlots.some(
|
||||||
|
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!slotExists) {
|
||||||
|
return err(Errors.conflict('El horario seleccionado no esta disponible para esa cancha.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSlotInPast(startDate, input.startTime, court.slotDurationMinutes)) {
|
||||||
|
return err(Errors.validation('La fecha de inicio no puede estar en el pasado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const recurringDates = Array.from(
|
||||||
|
generateRecurringDates(startDate, endDate, startDate.getUTCDay())
|
||||||
|
);
|
||||||
|
|
||||||
|
if (recurringDates.length === 0) {
|
||||||
|
return err(
|
||||||
|
Errors.validation(
|
||||||
|
'No se generaron fechas para la reserva periódica. Verifica las fechas ingresadas.'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const result = await db.$transaction(async (tx) => {
|
||||||
|
const groupId = uuidv7();
|
||||||
|
|
||||||
|
const bookingsForDate = await tx.courtBooking.count({
|
||||||
|
where: {
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
bookingDate: startDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
court: { complexId },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const courtsCount = await tx.court.count({ where: { complexId } });
|
||||||
|
const violations = evaluatePlanUsage(rules, {
|
||||||
|
courtsCount,
|
||||||
|
bookingsToday: bookingsForDate,
|
||||||
|
});
|
||||||
|
const maxBookingsViolation = violations.find(
|
||||||
|
(v) => v.code === 'MAX_BOOKINGS_PER_DAY_REACHED'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (maxBookingsViolation) {
|
||||||
|
throw new AdminBookingServiceError(maxBookingsViolation.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const group = await tx.recurringBookingGroup.create({
|
||||||
|
data: {
|
||||||
|
id: groupId,
|
||||||
|
complexId,
|
||||||
|
courtId: court.id,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
dayOfWeek,
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
customerName: input.customerName.trim(),
|
||||||
|
customerPhone: input.customerPhone.trim(),
|
||||||
|
customerEmail: input.customerEmail?.trim() ?? '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const createdBookings = [];
|
||||||
|
|
||||||
|
for (const date of recurringDates) {
|
||||||
|
if (isSlotInPast(date, input.startTime, court.slotDurationMinutes)) continue;
|
||||||
|
|
||||||
|
const overlappingBooking = await tx.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate: date,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
startTime: { lt: selectedSlot.endTime },
|
||||||
|
endTime: { gt: selectedSlot.startTime },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (overlappingBooking) {
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
`El horario seleccionado ya fue reservado para el dia ${formatIsoDate(date)}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const booking = await tx.courtBooking.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: generateBookingCode(),
|
||||||
|
courtId: court.id,
|
||||||
|
bookingDate: date,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
customerName: input.customerName.trim(),
|
||||||
|
customerPhone: input.customerPhone.trim(),
|
||||||
|
customerEmail: input.customerEmail?.trim() ?? '',
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
recurringGroupId: groupId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
createdBookings.push(booking);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { group, bookings: createdBookings };
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
id: result.group.id,
|
||||||
|
complexId,
|
||||||
|
courtId: court.id,
|
||||||
|
startTime: result.group.startTime,
|
||||||
|
endTime: result.group.endTime,
|
||||||
|
dayOfWeek: result.group.dayOfWeek,
|
||||||
|
startDate: formatIsoDate(result.group.startDate),
|
||||||
|
endDate: result.group.endDate ? formatIsoDate(result.group.endDate) : null,
|
||||||
|
status: 'ACTIVE' as const,
|
||||||
|
customerName: result.group.customerName,
|
||||||
|
customerPhone: result.group.customerPhone,
|
||||||
|
customerEmail: result.group.customerEmail,
|
||||||
|
bookings: result.bookings.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
bookingCode: b.bookingCode,
|
||||||
|
complexId: b.court.complex.id,
|
||||||
|
complexName: b.court.complex.complexName,
|
||||||
|
courtId: b.court.id,
|
||||||
|
courtName: b.court.name,
|
||||||
|
sport: { id: b.court.sport.id, name: b.court.sport.name, slug: b.court.sport.slug },
|
||||||
|
date: formatIsoDate(b.bookingDate),
|
||||||
|
startTime: b.startTime,
|
||||||
|
endTime: b.endTime,
|
||||||
|
customerName: b.customerName,
|
||||||
|
customerPhone: b.customerPhone,
|
||||||
|
customerEmail: b.customerEmail,
|
||||||
|
price: 0,
|
||||||
|
status: b.status as 'CONFIRMED',
|
||||||
|
recurringGroupId: result.group.id,
|
||||||
|
createdAt: b.createdAt.toISOString(),
|
||||||
|
updatedAt: b.updatedAt.toISOString(),
|
||||||
|
})),
|
||||||
|
createdAt: result.group.createdAt.toISOString(),
|
||||||
|
updatedAt: result.group.updatedAt.toISOString(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AdminBookingServiceError) {
|
||||||
|
return err(Errors.conflict(error.message));
|
||||||
|
}
|
||||||
|
|
||||||
|
const prismaError = error as { code?: string; meta?: { target?: string[] | string } };
|
||||||
|
if (prismaError.code === 'P2002') {
|
||||||
|
const targets = Array.isArray(prismaError.meta?.target)
|
||||||
|
? prismaError.meta?.target
|
||||||
|
: [prismaError.meta?.target];
|
||||||
|
const isBookingCodeCollision = targets.some((target) =>
|
||||||
|
String(target).includes('booking_code')
|
||||||
|
);
|
||||||
|
if (isBookingCodeCollision) continue;
|
||||||
|
return err(Errors.conflict('El horario seleccionado ya fue reservado.'));
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return err(Errors.conflict('No se pudo generar un codigo de reserva unico. Intenta nuevamente.'));
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { AdminBookingServiceError } from '@/modules/admin-booking/services/admin-booking.service';
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
import { createAdminRecurringBooking } from '@/modules/admin-booking/services/admin-recurring-booking.service';
|
|
||||||
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
import { sendBookingConfirmation } from '@/services/booking-email.service';
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { CreateRecurringBookingInput } from '@repo/api-contract';
|
import type { CreateRecurringBookingInput } from '@repo/api-contract';
|
||||||
|
import { createAdminRecurringBooking } from './create-admin-recurring-booking.business';
|
||||||
|
|
||||||
type ComplexIdParams = { complexId: string };
|
type ComplexIdParams = { complexId: string };
|
||||||
|
|
||||||
@@ -11,8 +11,10 @@ export async function createAdminRecurringBookingHandler(c: AppContext) {
|
|||||||
const payload = c.req.valid('json' as never) as CreateRecurringBookingInput;
|
const payload = c.req.valid('json' as never) as CreateRecurringBookingInput;
|
||||||
const user = c.get('user');
|
const user = c.get('user');
|
||||||
|
|
||||||
try {
|
const result = await createAdminRecurringBooking(user.id, complexId, payload);
|
||||||
const group = await createAdminRecurringBooking(user.id, complexId, payload);
|
|
||||||
|
if (result.ok) {
|
||||||
|
const group = result.value;
|
||||||
|
|
||||||
const firstBooking = group.bookings[0];
|
const firstBooking = group.bookings[0];
|
||||||
if (firstBooking?.customerEmail) {
|
if (firstBooking?.customerEmail) {
|
||||||
@@ -29,12 +31,7 @@ export async function createAdminRecurringBookingHandler(c: AppContext) {
|
|||||||
price: firstBooking.price,
|
price: firstBooking.price,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c.json(group, 201);
|
return handleResult(c, result, 201);
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import type { ListAdminBookingsQuery } from '@repo/api-contract';
|
||||||
|
import { ensureComplexAccess, mapBookingResponse, parseIsoDate } from '../../shared/helpers';
|
||||||
|
|
||||||
|
export async function listAdminBookings(
|
||||||
|
userId: string,
|
||||||
|
complexId: string,
|
||||||
|
query: ListAdminBookingsQuery
|
||||||
|
): Promise<Result<{ bookings: unknown[] }>> {
|
||||||
|
const accessResult = await ensureComplexAccess(complexId, userId);
|
||||||
|
if (!accessResult.ok) return err(accessResult.error);
|
||||||
|
|
||||||
|
const dateResult = parseIsoDate(query.fromDate);
|
||||||
|
if (!dateResult.ok) return err(dateResult.error);
|
||||||
|
const fromDate = dateResult.value;
|
||||||
|
|
||||||
|
const bookings = await db.courtBooking.findMany({
|
||||||
|
where: {
|
||||||
|
bookingDate: { gte: fromDate },
|
||||||
|
court: { complexId },
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ bookingDate: 'asc' }, { startTime: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ bookings: bookings.map((b) => mapBookingResponse(b)) });
|
||||||
|
}
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
import {
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
AdminBookingServiceError,
|
|
||||||
listAdminBookings,
|
|
||||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { ListAdminBookingsQuery } from '@repo/api-contract';
|
import type { ListAdminBookingsQuery } from '@repo/api-contract';
|
||||||
|
import { listAdminBookings } from './list-admin-bookings.business';
|
||||||
|
|
||||||
type ComplexIdParams = { complexId: string };
|
type ComplexIdParams = { complexId: string };
|
||||||
|
|
||||||
@@ -12,13 +10,5 @@ export async function listAdminBookingsHandler(c: AppContext) {
|
|||||||
const query = c.req.valid('query' as never) as ListAdminBookingsQuery;
|
const query = c.req.valid('query' as never) as ListAdminBookingsQuery;
|
||||||
const user = c.get('user');
|
const user = c.get('user');
|
||||||
|
|
||||||
try {
|
return handleResult(c, await listAdminBookings(user.id, complexId, query));
|
||||||
const response = await listAdminBookings(user.id, complexId, query);
|
|
||||||
return c.json(response);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { ok } from '@/lib/result';
|
||||||
|
import { formatIsoDate } from '../../shared/helpers';
|
||||||
|
|
||||||
|
export async function listRecurringGroups(complexId: string): Promise<
|
||||||
|
Result<
|
||||||
|
Array<{
|
||||||
|
id: string;
|
||||||
|
complexId: string;
|
||||||
|
courtId: string;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
dayOfWeek: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string | null;
|
||||||
|
status: string;
|
||||||
|
customerName: string;
|
||||||
|
customerPhone: string;
|
||||||
|
customerEmail: string;
|
||||||
|
bookings: Array<{
|
||||||
|
id: string;
|
||||||
|
bookingCode: string;
|
||||||
|
complexId: string;
|
||||||
|
complexName: string;
|
||||||
|
courtId: string;
|
||||||
|
courtName: string;
|
||||||
|
sport: { id: string; name: string; slug: string };
|
||||||
|
date: string;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
customerName: string;
|
||||||
|
customerPhone: string;
|
||||||
|
customerEmail: string;
|
||||||
|
price: number;
|
||||||
|
status: string;
|
||||||
|
recurringGroupId: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}>;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}>
|
||||||
|
>
|
||||||
|
> {
|
||||||
|
const groups = await db.recurringBookingGroup.findMany({
|
||||||
|
where: { complexId, status: 'ACTIVE' },
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
bookings: {
|
||||||
|
orderBy: { bookingDate: 'asc' },
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok(
|
||||||
|
groups.map((group) => ({
|
||||||
|
id: group.id,
|
||||||
|
complexId: group.complexId,
|
||||||
|
courtId: group.courtId,
|
||||||
|
startTime: group.startTime,
|
||||||
|
endTime: group.endTime,
|
||||||
|
dayOfWeek: group.dayOfWeek,
|
||||||
|
startDate: formatIsoDate(group.startDate),
|
||||||
|
endDate: group.endDate ? formatIsoDate(group.endDate) : null,
|
||||||
|
status: group.status,
|
||||||
|
customerName: group.customerName,
|
||||||
|
customerPhone: group.customerPhone,
|
||||||
|
customerEmail: group.customerEmail,
|
||||||
|
bookings: group.bookings.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
bookingCode: b.bookingCode,
|
||||||
|
complexId: b.court.complex.id,
|
||||||
|
complexName: b.court.complex.complexName,
|
||||||
|
courtId: b.court.id,
|
||||||
|
courtName: b.court.name,
|
||||||
|
sport: { id: b.court.sport.id, name: b.court.sport.name, slug: b.court.sport.slug },
|
||||||
|
date: formatIsoDate(b.bookingDate),
|
||||||
|
startTime: b.startTime,
|
||||||
|
endTime: b.endTime,
|
||||||
|
customerName: b.customerName,
|
||||||
|
customerPhone: b.customerPhone,
|
||||||
|
customerEmail: b.customerEmail,
|
||||||
|
price: 0,
|
||||||
|
status: b.status,
|
||||||
|
recurringGroupId: b.recurringGroupId,
|
||||||
|
createdAt: b.createdAt.toISOString(),
|
||||||
|
updatedAt: b.updatedAt.toISOString(),
|
||||||
|
})),
|
||||||
|
createdAt: group.createdAt.toISOString(),
|
||||||
|
updatedAt: group.updatedAt.toISOString(),
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { listRecurringGroups } from './list-recurring-groups.business';
|
||||||
|
|
||||||
|
type ComplexIdParams = { complexId: string };
|
||||||
|
|
||||||
|
export async function listRecurringGroupsHandler(c: AppContext) {
|
||||||
|
const { complexId } = c.req.valid('param' as never) as ComplexIdParams;
|
||||||
|
|
||||||
|
const result = await listRecurringGroups(complexId);
|
||||||
|
return handleResult(
|
||||||
|
c,
|
||||||
|
result.ok
|
||||||
|
? ({ ok: true as const, value: { groups: result.value } } as Result<{ groups: unknown }>)
|
||||||
|
: result
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import { isSlotInPast } from '@/lib/slot-validator';
|
||||||
|
import type { AdminBooking, RescheduleAdminBookingInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
import {
|
||||||
|
buildSlots,
|
||||||
|
getDayOfWeek,
|
||||||
|
mapBookingResponse,
|
||||||
|
minutesToTime,
|
||||||
|
resolvePrice,
|
||||||
|
toMinutes,
|
||||||
|
} from '../../shared/helpers';
|
||||||
|
|
||||||
|
export async function rescheduleAdminBooking(
|
||||||
|
userId: string,
|
||||||
|
bookingId: string,
|
||||||
|
input: RescheduleAdminBookingInput
|
||||||
|
): Promise<Result<AdminBooking>> {
|
||||||
|
const booking = await db.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
id: bookingId,
|
||||||
|
court: {
|
||||||
|
complex: { users: { some: { userId } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
complexId: true,
|
||||||
|
slotDurationMinutes: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!booking) {
|
||||||
|
return err(Errors.notFound('Reserva no encontrada.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (booking.status !== 'CONFIRMED') {
|
||||||
|
return err(Errors.conflict('Solo se pueden reprogramar reservas en estado confirmada.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetCourtId = input.courtId ?? booking.courtId;
|
||||||
|
const targetStartTime = input.startTime ?? booking.startTime;
|
||||||
|
|
||||||
|
if (targetCourtId === booking.courtId && targetStartTime === booking.startTime) {
|
||||||
|
return err(Errors.validation('Debe proporcionar al menos una cancha o un horario diferente.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const dayOfWeekResult = getDayOfWeek(booking.bookingDate);
|
||||||
|
if (!dayOfWeekResult.ok) return err(dayOfWeekResult.error);
|
||||||
|
const dayOfWeek = dayOfWeekResult.value;
|
||||||
|
|
||||||
|
const targetCourt = await db.court.findFirst({
|
||||||
|
where: { id: targetCourtId, complexId: booking.court.complexId },
|
||||||
|
include: {
|
||||||
|
availabilities: {
|
||||||
|
where: { dayOfWeek },
|
||||||
|
orderBy: { startTime: 'asc' },
|
||||||
|
},
|
||||||
|
priceRules: {
|
||||||
|
where: { isActive: true },
|
||||||
|
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
||||||
|
},
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!targetCourt) {
|
||||||
|
return err(Errors.notFound('La cancha seleccionada no existe en el complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetCourt.sport.id !== booking.court.sport.id) {
|
||||||
|
return err(
|
||||||
|
Errors.conflict('La cancha seleccionada no es del mismo deporte que la reserva original.')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetCourt.isUnderMaintenance) {
|
||||||
|
return err(Errors.conflict('La cancha seleccionada se encuentra en mantenimiento.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const validSlots = buildSlots(targetCourt.availabilities, targetCourt.slotDurationMinutes);
|
||||||
|
const selectedEndMinutes = toMinutes(targetStartTime) + targetCourt.slotDurationMinutes;
|
||||||
|
const selectedSlot = { startTime: targetStartTime, endTime: minutesToTime(selectedEndMinutes) };
|
||||||
|
|
||||||
|
const slotExists = validSlots.some(
|
||||||
|
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!slotExists) {
|
||||||
|
return err(Errors.conflict('El horario seleccionado no está disponible para esa cancha.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSlotInPast(booking.bookingDate, targetStartTime, targetCourt.slotDurationMinutes)) {
|
||||||
|
return err(Errors.validation('No se pueden reprogramar reservas en el pasado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlappingBooking = await db.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
id: { not: bookingId },
|
||||||
|
courtId: targetCourtId,
|
||||||
|
bookingDate: booking.bookingDate,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
startTime: { lt: selectedSlot.endTime },
|
||||||
|
endTime: { gt: selectedSlot.startTime },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (overlappingBooking) {
|
||||||
|
return err(Errors.conflict('El horario seleccionado ya fue reservado por otra reserva.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const newPrice = resolvePrice(
|
||||||
|
targetCourt,
|
||||||
|
dayOfWeek,
|
||||||
|
selectedSlot.startTime,
|
||||||
|
selectedSlot.endTime
|
||||||
|
);
|
||||||
|
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
await tx.courtBookingLog.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
courtId: booking.court.id,
|
||||||
|
bookingDate: booking.bookingDate,
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
customerEmail: booking.customerEmail,
|
||||||
|
previousStatus: booking.status,
|
||||||
|
newStatus: booking.status,
|
||||||
|
previousCourtId: booking.court.id,
|
||||||
|
previousStartTime: booking.startTime,
|
||||||
|
previousEndTime: booking.endTime,
|
||||||
|
changedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.courtBooking.update({
|
||||||
|
where: { id: booking.id },
|
||||||
|
data: {
|
||||||
|
courtId: targetCourtId,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const updatedBooking = {
|
||||||
|
...booking,
|
||||||
|
startTime: selectedSlot.startTime,
|
||||||
|
endTime: selectedSlot.endTime,
|
||||||
|
price: newPrice,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (targetCourtId !== booking.courtId) {
|
||||||
|
updatedBooking.court = {
|
||||||
|
id: targetCourt.id,
|
||||||
|
name: targetCourt.name,
|
||||||
|
slotDurationMinutes: targetCourt.slotDurationMinutes,
|
||||||
|
sport: targetCourt.sport,
|
||||||
|
complex: booking.court.complex,
|
||||||
|
} as typeof booking.court;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(mapBookingResponse(updatedBooking));
|
||||||
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
import { db } from '@/lib/prisma';
|
import { db } from '@/lib/prisma';
|
||||||
import { sseManager } from '@/lib/sse';
|
import { sseManager } from '@/lib/sse';
|
||||||
import {
|
|
||||||
AdminBookingServiceError,
|
|
||||||
rescheduleAdminBooking,
|
|
||||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { sendBookingRescheduled } from '@/services/booking-email.service';
|
import { sendBookingRescheduled } from '@/services/booking-email.service';
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { RescheduleAdminBookingInput } from '@repo/api-contract';
|
import type { RescheduleAdminBookingInput } from '@repo/api-contract';
|
||||||
|
import { rescheduleAdminBooking } from './reschedule-admin-booking.business';
|
||||||
|
|
||||||
type BookingIdParams = { id: string };
|
type BookingIdParams = { id: string };
|
||||||
|
|
||||||
@@ -25,8 +23,10 @@ export async function rescheduleAdminBookingHandler(c: AppContext) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
const result = await rescheduleAdminBooking(user.id, id, payload);
|
||||||
const booking = await rescheduleAdminBooking(user.id, id, payload);
|
|
||||||
|
if (result.ok) {
|
||||||
|
const booking = result.value;
|
||||||
|
|
||||||
if (previous) {
|
if (previous) {
|
||||||
void sendBookingRescheduled({
|
void sendBookingRescheduled({
|
||||||
@@ -49,12 +49,7 @@ export async function rescheduleAdminBookingHandler(c: AppContext) {
|
|||||||
`complex:${booking.complexId}`,
|
`complex:${booking.complexId}`,
|
||||||
JSON.stringify({ type: 'reschedule', booking })
|
JSON.stringify({ type: 'reschedule', booking })
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return c.json(booking);
|
return handleResult(c, result);
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import type { UpdateAdminBookingStatusInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
import { mapBookingResponse } from '../../shared/helpers';
|
||||||
|
|
||||||
|
export async function updateAdminBookingStatus(
|
||||||
|
userId: string,
|
||||||
|
bookingId: string,
|
||||||
|
input: UpdateAdminBookingStatusInput
|
||||||
|
): Promise<Result<ReturnType<typeof mapBookingResponse>>> {
|
||||||
|
const booking = await db.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
id: bookingId,
|
||||||
|
court: {
|
||||||
|
complex: { users: { some: { userId } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!booking) {
|
||||||
|
return err(Errors.notFound('Reserva no encontrada.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.status === 'CANCELLED' && booking.status !== 'CONFIRMED') {
|
||||||
|
return err(Errors.conflict('Solo se pueden cancelar reservas en estado confirmada.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.status === 'COMPLETED' && booking.status !== 'CONFIRMED') {
|
||||||
|
return err(Errors.conflict('Solo se pueden marcar como cumplidas las reservas confirmadas.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.status === 'NOSHOW' && booking.status !== 'CONFIRMED') {
|
||||||
|
return err(Errors.conflict('Solo se pueden marcar como no show las reservas confirmadas.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.courtBookingLog.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
courtId: booking.court.id,
|
||||||
|
bookingDate: booking.bookingDate,
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
customerEmail: booking.customerEmail,
|
||||||
|
previousStatus: booking.status,
|
||||||
|
newStatus: input.status,
|
||||||
|
changedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.status === 'COMPLETED' || input.status === 'NOSHOW') {
|
||||||
|
await db.courtBooking.update({
|
||||||
|
where: { id: booking.id },
|
||||||
|
data: { status: input.status },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await db.courtBooking.delete({ where: { id: booking.id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(mapBookingResponse({ ...booking, status: input.status }));
|
||||||
|
}
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
import {
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
AdminBookingServiceError,
|
|
||||||
updateAdminBookingStatus,
|
|
||||||
} from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { sendBookingCancelled, sendBookingNoShow } from '@/services/booking-email.service';
|
import { sendBookingCancelled, sendBookingNoShow } from '@/services/booking-email.service';
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { UpdateAdminBookingStatusInput } from '@repo/api-contract';
|
import type { UpdateAdminBookingStatusInput } from '@repo/api-contract';
|
||||||
|
import { updateAdminBookingStatus } from './update-admin-booking-status.business';
|
||||||
|
|
||||||
type BookingIdParams = { id: string };
|
type BookingIdParams = { id: string };
|
||||||
|
|
||||||
@@ -13,8 +11,10 @@ export async function updateAdminBookingStatusHandler(c: AppContext) {
|
|||||||
const payload = c.req.valid('json' as never) as UpdateAdminBookingStatusInput;
|
const payload = c.req.valid('json' as never) as UpdateAdminBookingStatusInput;
|
||||||
const user = c.get('user');
|
const user = c.get('user');
|
||||||
|
|
||||||
try {
|
const result = await updateAdminBookingStatus(user.id, id, payload);
|
||||||
const booking = await updateAdminBookingStatus(user.id, id, payload);
|
|
||||||
|
if (result.ok) {
|
||||||
|
const booking = result.value;
|
||||||
|
|
||||||
if (payload.status === 'CANCELLED') {
|
if (payload.status === 'CANCELLED') {
|
||||||
void sendBookingCancelled({
|
void sendBookingCancelled({
|
||||||
@@ -41,12 +41,7 @@ export async function updateAdminBookingStatusHandler(c: AppContext) {
|
|||||||
customerEmail: booking.customerEmail,
|
customerEmail: booking.customerEmail,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c.json(booking);
|
return handleResult(c, result);
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import { isSlotInPast } from '@/lib/slot-validator';
|
||||||
|
import type { RecurringBookingGroup, UpdateRecurringGroupInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
import { AdminBookingServiceError } from '../../shared/errors';
|
||||||
|
import { buildSlots, formatIsoDate, minutesToTime, toMinutes } from '../../shared/helpers';
|
||||||
|
|
||||||
|
const DAY_INDEX_BY_VALUE: Record<string, number> = {
|
||||||
|
SUNDAY: 0,
|
||||||
|
MONDAY: 1,
|
||||||
|
TUESDAY: 2,
|
||||||
|
WEDNESDAY: 3,
|
||||||
|
THURSDAY: 4,
|
||||||
|
FRIDAY: 5,
|
||||||
|
SATURDAY: 6,
|
||||||
|
};
|
||||||
|
|
||||||
|
const MAX_RECURRING_WEEKS = 52;
|
||||||
|
|
||||||
|
function generateBookingCode(): string {
|
||||||
|
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
let code = '';
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
code += alphabet[randomInt(0, alphabet.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
function* generateRecurringDates(
|
||||||
|
startDate: Date,
|
||||||
|
endDate: Date | null,
|
||||||
|
dayOfWeek: number
|
||||||
|
): Generator<Date> {
|
||||||
|
const current = new Date(startDate);
|
||||||
|
current.setUTCDate(current.getUTCDate() + ((dayOfWeek - current.getUTCDay() + 7) % 7));
|
||||||
|
|
||||||
|
if (current < startDate) {
|
||||||
|
current.setUTCDate(current.getUTCDate() + 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxDate = endDate ?? new Date(startDate);
|
||||||
|
if (!endDate) {
|
||||||
|
maxDate.setUTCDate(maxDate.getUTCDate() + MAX_RECURRING_WEEKS * 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
while (current <= maxDate) {
|
||||||
|
yield new Date(current);
|
||||||
|
current.setUTCDate(current.getUTCDate() + 7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateRecurringGroup(
|
||||||
|
userId: string,
|
||||||
|
groupId: string,
|
||||||
|
input: UpdateRecurringGroupInput
|
||||||
|
): Promise<Result<RecurringBookingGroup>> {
|
||||||
|
const group = await db.recurringBookingGroup.findUnique({
|
||||||
|
where: { id: groupId },
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
users: { where: { userId }, select: { userId: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!group) {
|
||||||
|
return err(Errors.notFound('Grupo de turnos fijos no encontrado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (group.complex.users.length === 0) {
|
||||||
|
return err(Errors.forbidden('No tienes permisos para administrar este complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (group.status === 'CANCELLED') {
|
||||||
|
return err(Errors.conflict('No se puede editar un grupo cancelado.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const courtId = input.courtId ?? group.courtId;
|
||||||
|
const dayOfWeek = input.dayOfWeek ?? group.dayOfWeek;
|
||||||
|
const startTime = input.startTime ?? group.startTime;
|
||||||
|
|
||||||
|
const scheduleChanged =
|
||||||
|
input.courtId !== undefined || input.dayOfWeek !== undefined || input.startTime !== undefined;
|
||||||
|
|
||||||
|
if (scheduleChanged) {
|
||||||
|
const court = await db.court.findFirst({
|
||||||
|
where: { id: courtId, complexId: group.complexId },
|
||||||
|
include: {
|
||||||
|
availabilities: {
|
||||||
|
where: { dayOfWeek: dayOfWeek as typeof group.dayOfWeek },
|
||||||
|
orderBy: { startTime: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!court) {
|
||||||
|
return err(Errors.notFound('La cancha seleccionada no existe en el complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
||||||
|
const selectedEndMinutes = toMinutes(startTime) + court.slotDurationMinutes;
|
||||||
|
const endTime = minutesToTime(selectedEndMinutes);
|
||||||
|
|
||||||
|
const slotExists = validSlots.some(
|
||||||
|
(slot) => slot.startTime === startTime && slot.endTime === endTime
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!slotExists) {
|
||||||
|
return err(Errors.conflict('El horario seleccionado no esta disponible para esa cancha.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const todayStart = new Date(
|
||||||
|
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
await tx.recurringBookingGroup.update({
|
||||||
|
where: { id: groupId },
|
||||||
|
data: {
|
||||||
|
courtId,
|
||||||
|
dayOfWeek: dayOfWeek as typeof group.dayOfWeek,
|
||||||
|
startTime,
|
||||||
|
endTime,
|
||||||
|
customerName: input.customerName?.trim() ?? group.customerName,
|
||||||
|
customerPhone: input.customerPhone?.trim() ?? group.customerPhone,
|
||||||
|
customerEmail: input.customerEmail?.trim() ?? group.customerEmail,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const futureBookings = await tx.courtBooking.findMany({
|
||||||
|
where: {
|
||||||
|
recurringGroupId: groupId,
|
||||||
|
bookingDate: { gte: todayStart },
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const booking of futureBookings) {
|
||||||
|
await tx.courtBookingLog.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
courtId: booking.courtId,
|
||||||
|
bookingDate: booking.bookingDate,
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
customerEmail: booking.customerEmail,
|
||||||
|
previousStatus: booking.status,
|
||||||
|
newStatus: 'CANCELLED',
|
||||||
|
changedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.courtBooking.delete({ where: { id: booking.id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const dayIndex = DAY_INDEX_BY_VALUE[dayOfWeek] ?? 0;
|
||||||
|
const recurringDates = Array.from(
|
||||||
|
generateRecurringDates(todayStart, group.endDate, dayIndex)
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const date of recurringDates) {
|
||||||
|
const overlappingBooking = await tx.courtBooking.findFirst({
|
||||||
|
where: {
|
||||||
|
courtId,
|
||||||
|
bookingDate: date,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
startTime: { lt: endTime },
|
||||||
|
endTime: { gt: startTime },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (overlappingBooking) {
|
||||||
|
throw new AdminBookingServiceError(
|
||||||
|
`El horario seleccionado ya fue reservado para el dia ${formatIsoDate(date)}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.courtBooking.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
bookingCode: generateBookingCode(),
|
||||||
|
courtId,
|
||||||
|
bookingDate: date,
|
||||||
|
startTime,
|
||||||
|
endTime,
|
||||||
|
customerName: input.customerName?.trim() ?? group.customerName,
|
||||||
|
customerPhone: input.customerPhone?.trim() ?? group.customerPhone,
|
||||||
|
customerEmail: input.customerEmail?.trim() ?? group.customerEmail,
|
||||||
|
status: 'CONFIRMED',
|
||||||
|
recurringGroupId: groupId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (txError) {
|
||||||
|
if (txError instanceof AdminBookingServiceError) {
|
||||||
|
return err(Errors.conflict(txError.message));
|
||||||
|
}
|
||||||
|
throw txError;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await db.recurringBookingGroup.update({
|
||||||
|
where: { id: groupId },
|
||||||
|
data: {
|
||||||
|
...(input.customerName !== undefined && { customerName: input.customerName.trim() }),
|
||||||
|
...(input.customerPhone !== undefined && { customerPhone: input.customerPhone.trim() }),
|
||||||
|
...(input.customerEmail !== undefined && { customerEmail: input.customerEmail.trim() }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const todayStart = new Date(
|
||||||
|
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateData: Record<string, string> = {};
|
||||||
|
if (input.customerName !== undefined) updateData.customerName = input.customerName.trim();
|
||||||
|
if (input.customerPhone !== undefined) updateData.customerPhone = input.customerPhone.trim();
|
||||||
|
if (input.customerEmail !== undefined) updateData.customerEmail = input.customerEmail.trim();
|
||||||
|
|
||||||
|
if (Object.keys(updateData).length > 0) {
|
||||||
|
await db.courtBooking.updateMany({
|
||||||
|
where: { recurringGroupId: groupId, bookingDate: { gte: todayStart } },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await db.recurringBookingGroup.findUnique({
|
||||||
|
where: { id: groupId },
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
bookings: {
|
||||||
|
orderBy: { bookingDate: 'asc' },
|
||||||
|
include: {
|
||||||
|
court: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
sport: { select: { id: true, name: true, slug: true } },
|
||||||
|
complex: { select: { id: true, complexName: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!updated) {
|
||||||
|
return err(Errors.conflict('Error al actualizar el grupo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
id: updated.id,
|
||||||
|
complexId: updated.complexId,
|
||||||
|
courtId: updated.courtId,
|
||||||
|
startTime: updated.startTime,
|
||||||
|
endTime: updated.endTime,
|
||||||
|
dayOfWeek: updated.dayOfWeek,
|
||||||
|
startDate: formatIsoDate(updated.startDate),
|
||||||
|
endDate: updated.endDate ? formatIsoDate(updated.endDate) : null,
|
||||||
|
status: updated.status,
|
||||||
|
customerName: updated.customerName,
|
||||||
|
customerPhone: updated.customerPhone,
|
||||||
|
customerEmail: updated.customerEmail,
|
||||||
|
bookings: updated.bookings.map((b) => ({
|
||||||
|
id: b.id,
|
||||||
|
bookingCode: b.bookingCode,
|
||||||
|
complexId: b.court.complex.id,
|
||||||
|
complexName: b.court.complex.complexName,
|
||||||
|
courtId: b.court.id,
|
||||||
|
courtName: b.court.name,
|
||||||
|
sport: { id: b.court.sport.id, name: b.court.sport.name, slug: b.court.sport.slug },
|
||||||
|
date: formatIsoDate(b.bookingDate),
|
||||||
|
startTime: b.startTime,
|
||||||
|
endTime: b.endTime,
|
||||||
|
customerName: b.customerName,
|
||||||
|
customerPhone: b.customerPhone,
|
||||||
|
customerEmail: b.customerEmail,
|
||||||
|
price: 0,
|
||||||
|
status: b.status,
|
||||||
|
recurringGroupId: b.recurringGroupId,
|
||||||
|
createdAt: b.createdAt.toISOString(),
|
||||||
|
updatedAt: b.updatedAt.toISOString(),
|
||||||
|
})),
|
||||||
|
createdAt: updated.createdAt.toISOString(),
|
||||||
|
updatedAt: updated.updatedAt.toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import type { UpdateRecurringGroupInput } from '@repo/api-contract';
|
||||||
|
import { updateRecurringGroup } from './update-recurring-group.business';
|
||||||
|
|
||||||
|
type GroupIdParams = { groupId: string };
|
||||||
|
|
||||||
|
export async function updateRecurringGroupHandler(c: AppContext) {
|
||||||
|
const { groupId } = c.req.valid('param' as never) as GroupIdParams;
|
||||||
|
const payload = c.req.valid('json' as never) as UpdateRecurringGroupInput;
|
||||||
|
const user = c.get('user');
|
||||||
|
|
||||||
|
return handleResult(c, await updateRecurringGroup(user.id, groupId, payload));
|
||||||
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { AdminBookingServiceError } from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { cancelRecurringGroup } from '@/modules/admin-booking/services/admin-recurring-booking.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
|
|
||||||
type GroupIdParams = { groupId: string };
|
|
||||||
|
|
||||||
export async function cancelRecurringGroupHandler(c: AppContext) {
|
|
||||||
const { groupId } = c.req.valid('param' as never) as GroupIdParams;
|
|
||||||
const user = c.get('user');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await cancelRecurringGroup(user.id, groupId);
|
|
||||||
return c.json(result);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { AdminBookingServiceError } from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { listRecurringGroups } from '@/modules/admin-booking/services/admin-recurring-booking.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
|
|
||||||
type ComplexIdParams = { complexId: string };
|
|
||||||
|
|
||||||
export async function listRecurringGroupsHandler(c: AppContext) {
|
|
||||||
const { complexId } = c.req.valid('param' as never) as ComplexIdParams;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const groups = await listRecurringGroups(complexId);
|
|
||||||
return c.json({ groups });
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { AdminBookingServiceError } from '@/modules/admin-booking/services/admin-booking.service';
|
|
||||||
import { updateRecurringGroup } from '@/modules/admin-booking/services/admin-recurring-booking.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
import type { UpdateRecurringGroupInput } from '@repo/api-contract';
|
|
||||||
|
|
||||||
type GroupIdParams = { groupId: string };
|
|
||||||
|
|
||||||
export async function updateRecurringGroupHandler(c: AppContext) {
|
|
||||||
const { groupId } = c.req.valid('param' as never) as GroupIdParams;
|
|
||||||
const payload = c.req.valid('json' as never) as UpdateRecurringGroupInput;
|
|
||||||
const user = c.get('user');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const group = await updateRecurringGroup(user.id, groupId, payload);
|
|
||||||
return c.json(group);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
return c.json({ message: error.message }, error.status);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,794 +0,0 @@
|
|||||||
import { randomInt } from 'node:crypto';
|
|
||||||
import { CourtBookingStatus } from '@/generated/prisma/enums';
|
|
||||||
import { db } from '@/lib/prisma';
|
|
||||||
import { isSlotInPast } from '@/lib/slot-validator';
|
|
||||||
import { evaluatePlanUsage, parsePlanRules } from '@/modules/plan/services/plan-rules.service';
|
|
||||||
import type { DayOfWeek } from '@repo/api-contract';
|
|
||||||
import type {
|
|
||||||
AdminBooking,
|
|
||||||
CreateAdminBookingInput,
|
|
||||||
ListAdminBookingsQuery,
|
|
||||||
RescheduleAdminBookingInput,
|
|
||||||
UpdateAdminBookingStatusInput,
|
|
||||||
} from '@repo/api-contract';
|
|
||||||
import { v7 as uuidv7 } from 'uuid';
|
|
||||||
|
|
||||||
type Slot = {
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const DAY_OF_WEEK_BY_INDEX = [
|
|
||||||
'SUNDAY',
|
|
||||||
'MONDAY',
|
|
||||||
'TUESDAY',
|
|
||||||
'WEDNESDAY',
|
|
||||||
'THURSDAY',
|
|
||||||
'FRIDAY',
|
|
||||||
'SATURDAY',
|
|
||||||
] as const;
|
|
||||||
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
||||||
const BOOKING_CODE_LENGTH = 6;
|
|
||||||
|
|
||||||
export class AdminBookingServiceError extends Error {
|
|
||||||
status: 400 | 403 | 404 | 409;
|
|
||||||
|
|
||||||
constructor(message: string, status: 400 | 403 | 404 | 409) {
|
|
||||||
super(message);
|
|
||||||
this.name = 'AdminBookingServiceError';
|
|
||||||
this.status = status;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toMinutes(value: string): number {
|
|
||||||
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
|
||||||
return hours * 60 + minutes;
|
|
||||||
}
|
|
||||||
|
|
||||||
function minutesToTime(minutes: number): string {
|
|
||||||
const safeMinutes = Math.max(0, minutes);
|
|
||||||
const hours = Math.floor(safeMinutes / 60);
|
|
||||||
const mins = safeMinutes % 60;
|
|
||||||
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseIsoDate(date: string): Date {
|
|
||||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
|
|
||||||
|
|
||||||
if (!match) {
|
|
||||||
throw new AdminBookingServiceError('La fecha debe tener formato YYYY-MM-DD.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const year = Number(match[1]);
|
|
||||||
const month = Number(match[2]);
|
|
||||||
const day = Number(match[3]);
|
|
||||||
|
|
||||||
const bookingDate = new Date(Date.UTC(year, month - 1, day));
|
|
||||||
|
|
||||||
if (
|
|
||||||
Number.isNaN(bookingDate.getTime()) ||
|
|
||||||
bookingDate.getUTCFullYear() !== year ||
|
|
||||||
bookingDate.getUTCMonth() + 1 !== month ||
|
|
||||||
bookingDate.getUTCDate() !== day
|
|
||||||
) {
|
|
||||||
throw new AdminBookingServiceError('La fecha enviada no es valida.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
return bookingDate;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDayOfWeek(date: Date) {
|
|
||||||
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()];
|
|
||||||
|
|
||||||
if (!dayOfWeek) {
|
|
||||||
throw new AdminBookingServiceError('No se pudo resolver el dia de la semana.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
return dayOfWeek;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatIsoDate(date: Date): string {
|
|
||||||
return date.toISOString().slice(0, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
function generateBookingCode(): string {
|
|
||||||
let code = '';
|
|
||||||
|
|
||||||
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
|
||||||
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
|
||||||
}
|
|
||||||
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildSlots(
|
|
||||||
availability: Array<{
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
}>,
|
|
||||||
slotDurationMinutes: number
|
|
||||||
): Slot[] {
|
|
||||||
const slots: Slot[] = [];
|
|
||||||
|
|
||||||
for (const range of availability) {
|
|
||||||
const start = toMinutes(range.startTime);
|
|
||||||
const end = toMinutes(range.endTime);
|
|
||||||
|
|
||||||
for (
|
|
||||||
let current = start;
|
|
||||||
current + slotDurationMinutes <= end;
|
|
||||||
current += slotDurationMinutes
|
|
||||||
) {
|
|
||||||
slots.push({
|
|
||||||
startTime: minutesToTime(current),
|
|
||||||
endTime: minutesToTime(current + slotDurationMinutes),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return slots;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureComplexAccess(complexId: string, userId: string) {
|
|
||||||
const complexUser = await db.complexUser.findUnique({
|
|
||||||
where: {
|
|
||||||
complexId_userId: {
|
|
||||||
complexId,
|
|
||||||
userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
plan: {
|
|
||||||
select: {
|
|
||||||
rules: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!complexUser) {
|
|
||||||
throw new AdminBookingServiceError('No tienes permisos para administrar este complejo.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
return complexUser.complex;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePrice(
|
|
||||||
court: {
|
|
||||||
basePrice: unknown;
|
|
||||||
priceRules: Array<{
|
|
||||||
dayOfWeek: string | null;
|
|
||||||
startTime: string | null;
|
|
||||||
endTime: string | null;
|
|
||||||
price: unknown;
|
|
||||||
}>;
|
|
||||||
},
|
|
||||||
dayOfWeek: string,
|
|
||||||
startTime: string,
|
|
||||||
endTime: string
|
|
||||||
): number {
|
|
||||||
const slotStart = toMinutes(startTime);
|
|
||||||
const slotEnd = toMinutes(endTime);
|
|
||||||
|
|
||||||
const matchingRules = court.priceRules
|
|
||||||
.filter((rule) => {
|
|
||||||
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) return false;
|
|
||||||
if (!rule.startTime || !rule.endTime) return true;
|
|
||||||
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
|
|
||||||
})
|
|
||||||
.sort((first, second) => {
|
|
||||||
const firstSpecificity =
|
|
||||||
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
|
|
||||||
const secondSpecificity =
|
|
||||||
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
|
|
||||||
return secondSpecificity - firstSpecificity;
|
|
||||||
});
|
|
||||||
|
|
||||||
return Number(matchingRules[0]?.price ?? court.basePrice);
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapBookingResponse(booking: {
|
|
||||||
id: string;
|
|
||||||
bookingCode: string;
|
|
||||||
bookingDate: Date;
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
customerName: string;
|
|
||||||
customerPhone: string;
|
|
||||||
customerEmail: string;
|
|
||||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
|
|
||||||
recurringGroupId: string | null;
|
|
||||||
createdAt: Date;
|
|
||||||
updatedAt: Date;
|
|
||||||
court: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
complex: {
|
|
||||||
id: string;
|
|
||||||
complexName: string;
|
|
||||||
};
|
|
||||||
sport: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
slug: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
price?: number;
|
|
||||||
}): AdminBooking {
|
|
||||||
return {
|
|
||||||
id: booking.id,
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
complexId: booking.court.complex.id,
|
|
||||||
complexName: booking.court.complex.complexName,
|
|
||||||
courtId: booking.court.id,
|
|
||||||
courtName: booking.court.name,
|
|
||||||
sport: {
|
|
||||||
id: booking.court.sport.id,
|
|
||||||
name: booking.court.sport.name,
|
|
||||||
slug: booking.court.sport.slug,
|
|
||||||
},
|
|
||||||
date: formatIsoDate(booking.bookingDate),
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
price: booking.price ?? 0,
|
|
||||||
status: booking.status,
|
|
||||||
recurringGroupId: booking.recurringGroupId,
|
|
||||||
createdAt: booking.createdAt.toISOString(),
|
|
||||||
updatedAt: booking.updatedAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function listAdminBookings(
|
|
||||||
userId: string,
|
|
||||||
complexId: string,
|
|
||||||
query: ListAdminBookingsQuery
|
|
||||||
) {
|
|
||||||
await ensureComplexAccess(complexId, userId);
|
|
||||||
const fromDate = parseIsoDate(query.fromDate);
|
|
||||||
|
|
||||||
const bookings = await db.courtBooking.findMany({
|
|
||||||
where: {
|
|
||||||
bookingDate: {
|
|
||||||
gte: fromDate,
|
|
||||||
},
|
|
||||||
court: {
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: [{ bookingDate: 'asc' }, { startTime: 'asc' }, { createdAt: 'asc' }],
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = bookings.map((booking) => mapBookingResponse(booking));
|
|
||||||
|
|
||||||
return {
|
|
||||||
bookings: response,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createAdminBooking(
|
|
||||||
userId: string,
|
|
||||||
complexId: string,
|
|
||||||
input: CreateAdminBookingInput
|
|
||||||
) {
|
|
||||||
const complex = await ensureComplexAccess(complexId, userId);
|
|
||||||
|
|
||||||
const adminUser = await db.user.findUnique({
|
|
||||||
where: { id: userId },
|
|
||||||
select: { emailVerified: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!adminUser?.emailVerified) {
|
|
||||||
throw new AdminBookingServiceError('Debés verificar tu email para poder crear reservas.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
const bookingDate = parseIsoDate(input.date);
|
|
||||||
const dayOfWeek = getDayOfWeek(bookingDate);
|
|
||||||
|
|
||||||
const court = await db.court.findFirst({
|
|
||||||
where: {
|
|
||||||
id: input.courtId,
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
availabilities: {
|
|
||||||
where: {
|
|
||||||
dayOfWeek,
|
|
||||||
},
|
|
||||||
orderBy: {
|
|
||||||
startTime: 'asc',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
priceRules: {
|
|
||||||
where: { isActive: true },
|
|
||||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!court) {
|
|
||||||
throw new AdminBookingServiceError('La cancha seleccionada no existe en el complejo.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
|
||||||
const selectedStartMinutes = toMinutes(input.startTime);
|
|
||||||
const selectedEndMinutes = selectedStartMinutes + court.slotDurationMinutes;
|
|
||||||
const selectedSlot = {
|
|
||||||
startTime: input.startTime,
|
|
||||||
endTime: minutesToTime(selectedEndMinutes),
|
|
||||||
};
|
|
||||||
|
|
||||||
const slotExists = validSlots.some(
|
|
||||||
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!slotExists) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'El horario seleccionado no esta disponible para esa cancha.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isSlotInPast(bookingDate, input.startTime, court.slotDurationMinutes)) {
|
|
||||||
throw new AdminBookingServiceError('No se pueden crear reservas en el pasado.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
||||||
try {
|
|
||||||
const booking = await db.$transaction(async (tx) => {
|
|
||||||
if (complex.plan) {
|
|
||||||
const rules = parsePlanRules(complex.plan.rules);
|
|
||||||
const bookingsForDate = await tx.courtBooking.count({
|
|
||||||
where: {
|
|
||||||
bookingDate,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
court: {
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const courtsCount = await tx.court.count({
|
|
||||||
where: {
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const violations = evaluatePlanUsage(rules, {
|
|
||||||
courtsCount,
|
|
||||||
bookingsToday: bookingsForDate,
|
|
||||||
});
|
|
||||||
|
|
||||||
const maxBookingsViolation = violations.find(
|
|
||||||
(violation) => violation.code === 'MAX_BOOKINGS_PER_DAY_REACHED'
|
|
||||||
);
|
|
||||||
|
|
||||||
if (maxBookingsViolation) {
|
|
||||||
throw new AdminBookingServiceError(maxBookingsViolation.message, 409);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const overlappingBooking = await tx.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
courtId: court.id,
|
|
||||||
bookingDate,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
startTime: {
|
|
||||||
lt: selectedSlot.endTime,
|
|
||||||
},
|
|
||||||
endTime: {
|
|
||||||
gt: selectedSlot.startTime,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (overlappingBooking) {
|
|
||||||
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
return tx.courtBooking.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: generateBookingCode(),
|
|
||||||
courtId: court.id,
|
|
||||||
bookingDate,
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
endTime: selectedSlot.endTime,
|
|
||||||
customerName: input.customerName.trim(),
|
|
||||||
customerPhone: input.customerPhone.trim(),
|
|
||||||
customerEmail: input.customerEmail?.trim() ?? '',
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
recurringGroupId: null,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const price = resolvePrice(court, dayOfWeek, selectedSlot.startTime, selectedSlot.endTime);
|
|
||||||
|
|
||||||
return mapBookingResponse({ ...booking, price });
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const prismaError = error as {
|
|
||||||
code?: string;
|
|
||||||
meta?: {
|
|
||||||
target?: string[] | string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
if (prismaError.code === 'P2002') {
|
|
||||||
const targets = Array.isArray(prismaError.meta?.target)
|
|
||||||
? prismaError.meta?.target
|
|
||||||
: [prismaError.meta?.target];
|
|
||||||
const isBookingCodeCollision = targets.some((target) =>
|
|
||||||
String(target).includes('booking_code')
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isBookingCodeCollision) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'No se pudo generar un codigo de reserva unico. Intenta nuevamente.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateAdminBookingStatus(
|
|
||||||
userId: string,
|
|
||||||
bookingId: string,
|
|
||||||
input: UpdateAdminBookingStatusInput
|
|
||||||
) {
|
|
||||||
const booking = await db.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
id: bookingId,
|
|
||||||
court: {
|
|
||||||
complex: {
|
|
||||||
users: {
|
|
||||||
some: {
|
|
||||||
userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!booking) {
|
|
||||||
throw new AdminBookingServiceError('Reserva no encontrada.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.status === 'CANCELLED' && booking.status !== 'CONFIRMED') {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Solo se pueden cancelar reservas en estado confirmada.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.status === 'COMPLETED' && booking.status !== 'CONFIRMED') {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Solo se pueden marcar como cumplidas las reservas confirmadas.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.status === 'NOSHOW' && booking.status !== 'CONFIRMED') {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Solo se pueden marcar como no show las reservas confirmadas.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.courtBookingLog.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
courtId: booking.court.id,
|
|
||||||
bookingDate: booking.bookingDate,
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
previousStatus: booking.status,
|
|
||||||
newStatus: input.status,
|
|
||||||
changedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (input.status === 'COMPLETED' || input.status === 'NOSHOW') {
|
|
||||||
await db.courtBooking.update({
|
|
||||||
where: { id: booking.id },
|
|
||||||
data: {
|
|
||||||
status: input.status,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// if the booking is cancelled we delete it to free up the slot, but we keep a log of it with the cancelled status
|
|
||||||
await db.courtBooking.delete({
|
|
||||||
where: { id: booking.id },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapBookingResponse({ ...booking, status: input.status });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function rescheduleAdminBooking(
|
|
||||||
userId: string,
|
|
||||||
bookingId: string,
|
|
||||||
input: RescheduleAdminBookingInput
|
|
||||||
): Promise<AdminBooking> {
|
|
||||||
const booking = await db.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
id: bookingId,
|
|
||||||
court: {
|
|
||||||
complex: {
|
|
||||||
users: {
|
|
||||||
some: { userId },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
complexId: true,
|
|
||||||
slotDurationMinutes: true,
|
|
||||||
sport: {
|
|
||||||
select: { id: true, name: true, slug: true },
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: { id: true, complexName: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!booking) {
|
|
||||||
throw new AdminBookingServiceError('Reserva no encontrada.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (booking.status !== 'CONFIRMED') {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Solo se pueden reprogramar reservas en estado confirmada.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const targetCourtId = input.courtId ?? booking.courtId;
|
|
||||||
const targetStartTime = input.startTime ?? booking.startTime;
|
|
||||||
|
|
||||||
if (targetCourtId === booking.courtId && targetStartTime === booking.startTime) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Debe proporcionar al menos una cancha o un horario diferente.',
|
|
||||||
400
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const dayOfWeek = getDayOfWeek(booking.bookingDate);
|
|
||||||
|
|
||||||
const targetCourt = await db.court.findFirst({
|
|
||||||
where: {
|
|
||||||
id: targetCourtId,
|
|
||||||
complexId: booking.court.complexId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
availabilities: {
|
|
||||||
where: { dayOfWeek },
|
|
||||||
orderBy: { startTime: 'asc' },
|
|
||||||
},
|
|
||||||
priceRules: {
|
|
||||||
where: { isActive: true },
|
|
||||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
|
||||||
},
|
|
||||||
sport: {
|
|
||||||
select: { id: true, name: true, slug: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!targetCourt) {
|
|
||||||
throw new AdminBookingServiceError('La cancha seleccionada no existe en el complejo.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (targetCourt.sport.id !== booking.court.sport.id) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'La cancha seleccionada no es del mismo deporte que la reserva original.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (targetCourt.isUnderMaintenance) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'La cancha seleccionada se encuentra en mantenimiento.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validSlots = buildSlots(targetCourt.availabilities, targetCourt.slotDurationMinutes);
|
|
||||||
const selectedEndMinutes = toMinutes(targetStartTime) + targetCourt.slotDurationMinutes;
|
|
||||||
const selectedSlot = {
|
|
||||||
startTime: targetStartTime,
|
|
||||||
endTime: minutesToTime(selectedEndMinutes),
|
|
||||||
};
|
|
||||||
|
|
||||||
const slotExists = validSlots.some(
|
|
||||||
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!slotExists) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'El horario seleccionado no está disponible para esa cancha.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isSlotInPast(booking.bookingDate, targetStartTime, targetCourt.slotDurationMinutes)) {
|
|
||||||
throw new AdminBookingServiceError('No se pueden reprogramar reservas en el pasado.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const overlappingBooking = await db.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
id: { not: bookingId },
|
|
||||||
courtId: targetCourtId,
|
|
||||||
bookingDate: booking.bookingDate,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
startTime: { lt: selectedSlot.endTime },
|
|
||||||
endTime: { gt: selectedSlot.startTime },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (overlappingBooking) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'El horario seleccionado ya fue reservado por otra reserva.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newPrice = resolvePrice(
|
|
||||||
targetCourt,
|
|
||||||
dayOfWeek,
|
|
||||||
selectedSlot.startTime,
|
|
||||||
selectedSlot.endTime
|
|
||||||
);
|
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
|
||||||
await tx.courtBookingLog.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
courtId: booking.court.id,
|
|
||||||
bookingDate: booking.bookingDate,
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
previousStatus: booking.status,
|
|
||||||
newStatus: booking.status,
|
|
||||||
previousCourtId: booking.court.id,
|
|
||||||
previousStartTime: booking.startTime,
|
|
||||||
previousEndTime: booking.endTime,
|
|
||||||
changedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await tx.courtBooking.update({
|
|
||||||
where: { id: booking.id },
|
|
||||||
data: {
|
|
||||||
courtId: targetCourtId,
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
endTime: selectedSlot.endTime,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const updatedBooking = {
|
|
||||||
...booking,
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
endTime: selectedSlot.endTime,
|
|
||||||
price: newPrice,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (targetCourtId !== booking.courtId) {
|
|
||||||
updatedBooking.court = {
|
|
||||||
id: targetCourt.id,
|
|
||||||
name: targetCourt.name,
|
|
||||||
slotDurationMinutes: targetCourt.slotDurationMinutes,
|
|
||||||
sport: targetCourt.sport,
|
|
||||||
complex: booking.court.complex,
|
|
||||||
} as typeof booking.court;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapBookingResponse(updatedBooking);
|
|
||||||
}
|
|
||||||
@@ -1,893 +0,0 @@
|
|||||||
import { randomInt } from 'node:crypto';
|
|
||||||
import { DayOfWeek as DayOfWeekEnum } from '@/generated/prisma/enums';
|
|
||||||
import { db } from '@/lib/prisma';
|
|
||||||
import { isSlotInPast } from '@/lib/slot-validator';
|
|
||||||
import {
|
|
||||||
evaluatePlanUsage,
|
|
||||||
isFeatureEnabled,
|
|
||||||
parsePlanRules,
|
|
||||||
} from '@/modules/plan/services/plan-rules.service';
|
|
||||||
import type {
|
|
||||||
CreateRecurringBookingInput,
|
|
||||||
RecurringBookingGroup,
|
|
||||||
UpdateRecurringGroupInput,
|
|
||||||
} from '@repo/api-contract';
|
|
||||||
import { v7 as uuidv7 } from 'uuid';
|
|
||||||
import { AdminBookingServiceError } from './admin-booking.service';
|
|
||||||
|
|
||||||
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
||||||
const BOOKING_CODE_LENGTH = 6;
|
|
||||||
const MAX_RECURRING_WEEKS = 52;
|
|
||||||
|
|
||||||
const DAY_INDEX_BY_VALUE: Record<string, number> = {
|
|
||||||
SUNDAY: 0,
|
|
||||||
MONDAY: 1,
|
|
||||||
TUESDAY: 2,
|
|
||||||
WEDNESDAY: 3,
|
|
||||||
THURSDAY: 4,
|
|
||||||
FRIDAY: 5,
|
|
||||||
SATURDAY: 6,
|
|
||||||
};
|
|
||||||
|
|
||||||
const DAY_OF_WEEK_BY_INDEX = [
|
|
||||||
DayOfWeekEnum.SUNDAY,
|
|
||||||
DayOfWeekEnum.MONDAY,
|
|
||||||
DayOfWeekEnum.TUESDAY,
|
|
||||||
DayOfWeekEnum.WEDNESDAY,
|
|
||||||
DayOfWeekEnum.THURSDAY,
|
|
||||||
DayOfWeekEnum.FRIDAY,
|
|
||||||
DayOfWeekEnum.SATURDAY,
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
type DayOfWeek = (typeof DAY_OF_WEEK_BY_INDEX)[number];
|
|
||||||
|
|
||||||
function toMinutes(value: string): number {
|
|
||||||
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
|
||||||
return hours * 60 + minutes;
|
|
||||||
}
|
|
||||||
|
|
||||||
function minutesToTime(minutes: number): string {
|
|
||||||
const safeMinutes = Math.max(0, minutes);
|
|
||||||
const hours = Math.floor(safeMinutes / 60);
|
|
||||||
const mins = safeMinutes % 60;
|
|
||||||
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseIsoDate(date: string): Date {
|
|
||||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
|
|
||||||
|
|
||||||
if (!match) {
|
|
||||||
throw new AdminBookingServiceError('La fecha debe tener formato YYYY-MM-DD.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const year = Number(match[1]);
|
|
||||||
const month = Number(match[2]);
|
|
||||||
const day = Number(match[3]);
|
|
||||||
|
|
||||||
const parsed = new Date(Date.UTC(year, month - 1, day));
|
|
||||||
|
|
||||||
if (
|
|
||||||
Number.isNaN(parsed.getTime()) ||
|
|
||||||
parsed.getUTCFullYear() !== year ||
|
|
||||||
parsed.getUTCMonth() + 1 !== month ||
|
|
||||||
parsed.getUTCDate() !== day
|
|
||||||
) {
|
|
||||||
throw new AdminBookingServiceError('La fecha enviada no es valida.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatIsoDate(date: Date): string {
|
|
||||||
return date.toISOString().slice(0, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDayOfWeekValue(date: Date): DayOfWeek {
|
|
||||||
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()];
|
|
||||||
|
|
||||||
if (!dayOfWeek) {
|
|
||||||
throw new AdminBookingServiceError('No se pudo resolver el dia de la semana.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
return dayOfWeek;
|
|
||||||
}
|
|
||||||
|
|
||||||
function generateBookingCode(): string {
|
|
||||||
let code = '';
|
|
||||||
|
|
||||||
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
|
||||||
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
|
||||||
}
|
|
||||||
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildSlots(
|
|
||||||
availability: Array<{
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
}>,
|
|
||||||
slotDurationMinutes: number
|
|
||||||
) {
|
|
||||||
const slots: Array<{ startTime: string; endTime: string }> = [];
|
|
||||||
|
|
||||||
for (const range of availability) {
|
|
||||||
const start = toMinutes(range.startTime);
|
|
||||||
const end = toMinutes(range.endTime);
|
|
||||||
|
|
||||||
for (
|
|
||||||
let current = start;
|
|
||||||
current + slotDurationMinutes <= end;
|
|
||||||
current += slotDurationMinutes
|
|
||||||
) {
|
|
||||||
slots.push({
|
|
||||||
startTime: minutesToTime(current),
|
|
||||||
endTime: minutesToTime(current + slotDurationMinutes),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return slots;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureComplexAccess(complexId: string, userId: string) {
|
|
||||||
const complexUser = await db.complexUser.findUnique({
|
|
||||||
where: {
|
|
||||||
complexId_userId: {
|
|
||||||
complexId,
|
|
||||||
userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
plan: {
|
|
||||||
select: {
|
|
||||||
rules: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!complexUser) {
|
|
||||||
throw new AdminBookingServiceError('No tienes permisos para administrar este complejo.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
return complexUser.complex;
|
|
||||||
}
|
|
||||||
|
|
||||||
function* generateRecurringDates(
|
|
||||||
startDate: Date,
|
|
||||||
endDate: Date | null,
|
|
||||||
dayOfWeek: number
|
|
||||||
): Generator<Date> {
|
|
||||||
const current = new Date(startDate);
|
|
||||||
current.setUTCDate(current.getUTCDate() + ((dayOfWeek - current.getUTCDay() + 7) % 7));
|
|
||||||
|
|
||||||
if (current < startDate) {
|
|
||||||
current.setUTCDate(current.getUTCDate() + 7);
|
|
||||||
}
|
|
||||||
|
|
||||||
const maxDate = endDate ?? new Date(startDate);
|
|
||||||
if (!endDate) {
|
|
||||||
maxDate.setUTCDate(maxDate.getUTCDate() + MAX_RECURRING_WEEKS * 7);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (current <= maxDate) {
|
|
||||||
yield new Date(current);
|
|
||||||
current.setUTCDate(current.getUTCDate() + 7);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapBookingResponse(booking: {
|
|
||||||
id: string;
|
|
||||||
bookingCode: string;
|
|
||||||
bookingDate: Date;
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
customerName: string;
|
|
||||||
customerPhone: string;
|
|
||||||
customerEmail: string;
|
|
||||||
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
|
|
||||||
recurringGroupId: string | null;
|
|
||||||
createdAt: Date;
|
|
||||||
updatedAt: Date;
|
|
||||||
court: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
complex: {
|
|
||||||
id: string;
|
|
||||||
complexName: string;
|
|
||||||
};
|
|
||||||
sport: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
slug: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
price?: number;
|
|
||||||
}) {
|
|
||||||
return {
|
|
||||||
id: booking.id,
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
complexId: booking.court.complex.id,
|
|
||||||
complexName: booking.court.complex.complexName,
|
|
||||||
courtId: booking.court.id,
|
|
||||||
courtName: booking.court.name,
|
|
||||||
sport: {
|
|
||||||
id: booking.court.sport.id,
|
|
||||||
name: booking.court.sport.name,
|
|
||||||
slug: booking.court.sport.slug,
|
|
||||||
},
|
|
||||||
date: formatIsoDate(booking.bookingDate),
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
price: booking.price ?? 0,
|
|
||||||
status: booking.status,
|
|
||||||
recurringGroupId: booking.recurringGroupId,
|
|
||||||
createdAt: booking.createdAt.toISOString(),
|
|
||||||
updatedAt: booking.updatedAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createAdminRecurringBooking(
|
|
||||||
userId: string,
|
|
||||||
complexId: string,
|
|
||||||
input: CreateRecurringBookingInput
|
|
||||||
): Promise<RecurringBookingGroup> {
|
|
||||||
const complex = await ensureComplexAccess(complexId, userId);
|
|
||||||
|
|
||||||
const adminUser = await db.user.findUnique({
|
|
||||||
where: { id: userId },
|
|
||||||
select: { emailVerified: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!adminUser?.emailVerified) {
|
|
||||||
throw new AdminBookingServiceError('Debés verificar tu email para poder crear reservas.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!complex.plan) {
|
|
||||||
throw new AdminBookingServiceError('El complejo no tiene un plan asignado.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
const rules = parsePlanRules(complex.plan.rules);
|
|
||||||
|
|
||||||
if (!isFeatureEnabled(rules, 'fixedSlots')) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'Tu plan no permite la creación de turnos fijos. Comunicate con el administrador.',
|
|
||||||
403
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const startDate = parseIsoDate(input.date);
|
|
||||||
const dayOfWeek = getDayOfWeekValue(startDate);
|
|
||||||
const endDate = input.recurringEndDate ? parseIsoDate(input.recurringEndDate) : null;
|
|
||||||
|
|
||||||
if (endDate && endDate <= startDate) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'La fecha de fin debe ser posterior a la fecha de inicio.',
|
|
||||||
400
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const court = await db.court.findFirst({
|
|
||||||
where: {
|
|
||||||
id: input.courtId,
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
availabilities: {
|
|
||||||
where: {
|
|
||||||
dayOfWeek,
|
|
||||||
},
|
|
||||||
orderBy: {
|
|
||||||
startTime: 'asc',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
priceRules: {
|
|
||||||
where: { isActive: true },
|
|
||||||
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!court) {
|
|
||||||
throw new AdminBookingServiceError('La cancha seleccionada no existe en el complejo.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
|
||||||
const selectedEndMinutes = toMinutes(input.startTime) + court.slotDurationMinutes;
|
|
||||||
const selectedSlot = {
|
|
||||||
startTime: input.startTime,
|
|
||||||
endTime: minutesToTime(selectedEndMinutes),
|
|
||||||
};
|
|
||||||
|
|
||||||
const slotExists = validSlots.some(
|
|
||||||
(slot) => slot.startTime === selectedSlot.startTime && slot.endTime === selectedSlot.endTime
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!slotExists) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'El horario seleccionado no esta disponible para esa cancha.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isSlotInPast(startDate, input.startTime, court.slotDurationMinutes)) {
|
|
||||||
throw new AdminBookingServiceError('La fecha de inicio no puede estar en el pasado.', 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const recurringDates = Array.from(
|
|
||||||
generateRecurringDates(startDate, endDate, startDate.getUTCDay())
|
|
||||||
);
|
|
||||||
|
|
||||||
if (recurringDates.length === 0) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'No se generaron fechas para la reserva periódica. Verifica las fechas ingresadas.',
|
|
||||||
400
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
||||||
try {
|
|
||||||
const result = await db.$transaction(async (tx) => {
|
|
||||||
const groupId = uuidv7();
|
|
||||||
|
|
||||||
const bookingsForDate = await tx.courtBooking.count({
|
|
||||||
where: {
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
bookingDate: startDate,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
court: {
|
|
||||||
complexId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const courtsCount = await tx.court.count({
|
|
||||||
where: { complexId },
|
|
||||||
});
|
|
||||||
|
|
||||||
const violations = evaluatePlanUsage(rules, {
|
|
||||||
courtsCount,
|
|
||||||
bookingsToday: bookingsForDate,
|
|
||||||
});
|
|
||||||
|
|
||||||
const maxBookingsViolation = violations.find(
|
|
||||||
(v) => v.code === 'MAX_BOOKINGS_PER_DAY_REACHED'
|
|
||||||
);
|
|
||||||
|
|
||||||
if (maxBookingsViolation) {
|
|
||||||
throw new AdminBookingServiceError(maxBookingsViolation.message, 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
const group = await tx.recurringBookingGroup.create({
|
|
||||||
data: {
|
|
||||||
id: groupId,
|
|
||||||
complexId,
|
|
||||||
courtId: court.id,
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
endTime: selectedSlot.endTime,
|
|
||||||
dayOfWeek,
|
|
||||||
startDate,
|
|
||||||
endDate,
|
|
||||||
status: 'ACTIVE',
|
|
||||||
customerName: input.customerName.trim(),
|
|
||||||
customerPhone: input.customerPhone.trim(),
|
|
||||||
customerEmail: input.customerEmail?.trim() ?? '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const createdBookings = [];
|
|
||||||
|
|
||||||
for (const date of recurringDates) {
|
|
||||||
if (isSlotInPast(date, input.startTime, court.slotDurationMinutes)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const overlappingBooking = await tx.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
courtId: court.id,
|
|
||||||
bookingDate: date,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
startTime: {
|
|
||||||
lt: selectedSlot.endTime,
|
|
||||||
},
|
|
||||||
endTime: {
|
|
||||||
gt: selectedSlot.startTime,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (overlappingBooking) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
`El horario seleccionado ya fue reservado para el dia ${formatIsoDate(date)}.`,
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const booking = await tx.courtBooking.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: generateBookingCode(),
|
|
||||||
courtId: court.id,
|
|
||||||
bookingDate: date,
|
|
||||||
startTime: selectedSlot.startTime,
|
|
||||||
endTime: selectedSlot.endTime,
|
|
||||||
customerName: input.customerName.trim(),
|
|
||||||
customerPhone: input.customerPhone.trim(),
|
|
||||||
customerEmail: input.customerEmail?.trim() ?? '',
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
recurringGroupId: groupId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
slug: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
complexName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
createdBookings.push(booking);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { group, bookings: createdBookings };
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: result.group.id,
|
|
||||||
complexId,
|
|
||||||
courtId: court.id,
|
|
||||||
startTime: result.group.startTime,
|
|
||||||
endTime: result.group.endTime,
|
|
||||||
dayOfWeek: result.group.dayOfWeek,
|
|
||||||
startDate: formatIsoDate(result.group.startDate),
|
|
||||||
endDate: result.group.endDate ? formatIsoDate(result.group.endDate) : null,
|
|
||||||
status: 'ACTIVE' as const,
|
|
||||||
customerName: result.group.customerName,
|
|
||||||
customerPhone: result.group.customerPhone,
|
|
||||||
customerEmail: result.group.customerEmail,
|
|
||||||
bookings: result.bookings.map((b) => mapBookingResponse(b)),
|
|
||||||
createdAt: result.group.createdAt.toISOString(),
|
|
||||||
updatedAt: result.group.updatedAt.toISOString(),
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof AdminBookingServiceError) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const prismaError = error as {
|
|
||||||
code?: string;
|
|
||||||
meta?: {
|
|
||||||
target?: string[] | string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
if (prismaError.code === 'P2002') {
|
|
||||||
const targets = Array.isArray(prismaError.meta?.target)
|
|
||||||
? prismaError.meta?.target
|
|
||||||
: [prismaError.meta?.target];
|
|
||||||
const isBookingCodeCollision = targets.some((target) =>
|
|
||||||
String(target).includes('booking_code')
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isBookingCodeCollision) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new AdminBookingServiceError('El horario seleccionado ya fue reservado.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'No se pudo generar un codigo de reserva unico. Intenta nuevamente.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function cancelRecurringGroup(userId: string, groupId: string) {
|
|
||||||
const group = await db.recurringBookingGroup.findUnique({
|
|
||||||
where: { id: groupId },
|
|
||||||
include: {
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
users: {
|
|
||||||
where: { userId },
|
|
||||||
select: { userId: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!group) {
|
|
||||||
throw new AdminBookingServiceError('Grupo de reservas no encontrado.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (group.complex.users.length === 0) {
|
|
||||||
throw new AdminBookingServiceError('No tienes permisos para administrar este complejo.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (group.status === 'CANCELLED') {
|
|
||||||
throw new AdminBookingServiceError('El grupo ya fue cancelado anteriormente.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
|
||||||
await tx.recurringBookingGroup.update({
|
|
||||||
where: { id: groupId },
|
|
||||||
data: { status: 'CANCELLED' },
|
|
||||||
});
|
|
||||||
|
|
||||||
const futureBookings = await tx.courtBooking.findMany({
|
|
||||||
where: {
|
|
||||||
recurringGroupId: groupId,
|
|
||||||
bookingDate: { gte: todayStart },
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const booking of futureBookings) {
|
|
||||||
await tx.courtBookingLog.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
courtId: booking.courtId,
|
|
||||||
bookingDate: booking.bookingDate,
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
previousStatus: booking.status,
|
|
||||||
newStatus: 'CANCELLED',
|
|
||||||
changedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await tx.courtBooking.delete({
|
|
||||||
where: { id: booking.id },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function listRecurringGroups(complexId: string): Promise<RecurringBookingGroup[]> {
|
|
||||||
const groups = await db.recurringBookingGroup.findMany({
|
|
||||||
where: { complexId, status: 'ACTIVE' },
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: { id: true, name: true, slug: true },
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: { id: true, complexName: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
bookings: {
|
|
||||||
orderBy: { bookingDate: 'asc' },
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: {
|
|
||||||
select: { id: true, name: true, slug: true },
|
|
||||||
},
|
|
||||||
complex: {
|
|
||||||
select: { id: true, complexName: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
});
|
|
||||||
|
|
||||||
return groups.map((group) => ({
|
|
||||||
id: group.id,
|
|
||||||
complexId: group.complexId,
|
|
||||||
courtId: group.courtId,
|
|
||||||
startTime: group.startTime,
|
|
||||||
endTime: group.endTime,
|
|
||||||
dayOfWeek: group.dayOfWeek,
|
|
||||||
startDate: formatIsoDate(group.startDate),
|
|
||||||
endDate: group.endDate ? formatIsoDate(group.endDate) : null,
|
|
||||||
status: group.status,
|
|
||||||
customerName: group.customerName,
|
|
||||||
customerPhone: group.customerPhone,
|
|
||||||
customerEmail: group.customerEmail,
|
|
||||||
bookings: group.bookings.map(mapBookingResponse),
|
|
||||||
createdAt: group.createdAt.toISOString(),
|
|
||||||
updatedAt: group.updatedAt.toISOString(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateRecurringGroup(
|
|
||||||
userId: string,
|
|
||||||
groupId: string,
|
|
||||||
input: UpdateRecurringGroupInput
|
|
||||||
): Promise<RecurringBookingGroup> {
|
|
||||||
const group = await db.recurringBookingGroup.findUnique({
|
|
||||||
where: { id: groupId },
|
|
||||||
include: {
|
|
||||||
complex: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
users: {
|
|
||||||
where: { userId },
|
|
||||||
select: { userId: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!group) {
|
|
||||||
throw new AdminBookingServiceError('Grupo de turnos fijos no encontrado.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (group.complex.users.length === 0) {
|
|
||||||
throw new AdminBookingServiceError('No tienes permisos para administrar este complejo.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (group.status === 'CANCELLED') {
|
|
||||||
throw new AdminBookingServiceError('No se puede editar un grupo cancelado.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
const courtId = input.courtId ?? group.courtId;
|
|
||||||
const dayOfWeek = input.dayOfWeek ?? group.dayOfWeek;
|
|
||||||
const startTime = input.startTime ?? group.startTime;
|
|
||||||
|
|
||||||
const scheduleChanged =
|
|
||||||
input.courtId !== undefined || input.dayOfWeek !== undefined || input.startTime !== undefined;
|
|
||||||
|
|
||||||
if (scheduleChanged) {
|
|
||||||
const court = await db.court.findFirst({
|
|
||||||
where: { id: courtId, complexId: group.complexId },
|
|
||||||
include: {
|
|
||||||
availabilities: {
|
|
||||||
where: { dayOfWeek: dayOfWeek as DayOfWeek },
|
|
||||||
orderBy: { startTime: 'asc' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!court) {
|
|
||||||
throw new AdminBookingServiceError('La cancha seleccionada no existe en el complejo.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validSlots = buildSlots(court.availabilities, court.slotDurationMinutes);
|
|
||||||
const selectedEndMinutes = toMinutes(startTime) + court.slotDurationMinutes;
|
|
||||||
const endTime = minutesToTime(selectedEndMinutes);
|
|
||||||
|
|
||||||
const slotExists = validSlots.some(
|
|
||||||
(slot) => slot.startTime === startTime && slot.endTime === endTime
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!slotExists) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
'El horario seleccionado no esta disponible para esa cancha.',
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
const todayStart = new Date(
|
|
||||||
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
|
||||||
);
|
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
|
||||||
await tx.recurringBookingGroup.update({
|
|
||||||
where: { id: groupId },
|
|
||||||
data: {
|
|
||||||
courtId,
|
|
||||||
dayOfWeek: dayOfWeek as DayOfWeek,
|
|
||||||
startTime,
|
|
||||||
endTime,
|
|
||||||
customerName: input.customerName?.trim() ?? group.customerName,
|
|
||||||
customerPhone: input.customerPhone?.trim() ?? group.customerPhone,
|
|
||||||
customerEmail: input.customerEmail?.trim() ?? group.customerEmail,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const futureBookings = await tx.courtBooking.findMany({
|
|
||||||
where: {
|
|
||||||
recurringGroupId: groupId,
|
|
||||||
bookingDate: { gte: todayStart },
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const booking of futureBookings) {
|
|
||||||
await tx.courtBookingLog.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: booking.bookingCode,
|
|
||||||
courtId: booking.courtId,
|
|
||||||
bookingDate: booking.bookingDate,
|
|
||||||
startTime: booking.startTime,
|
|
||||||
endTime: booking.endTime,
|
|
||||||
customerName: booking.customerName,
|
|
||||||
customerPhone: booking.customerPhone,
|
|
||||||
customerEmail: booking.customerEmail,
|
|
||||||
previousStatus: booking.status,
|
|
||||||
newStatus: 'CANCELLED',
|
|
||||||
changedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await tx.courtBooking.delete({
|
|
||||||
where: { id: booking.id },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const dayIndex = DAY_INDEX_BY_VALUE[dayOfWeek] ?? 0;
|
|
||||||
const recurringDates = Array.from(
|
|
||||||
generateRecurringDates(todayStart, group.endDate, dayIndex)
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const date of recurringDates) {
|
|
||||||
const overlappingBooking = await tx.courtBooking.findFirst({
|
|
||||||
where: {
|
|
||||||
courtId,
|
|
||||||
bookingDate: date,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
startTime: { lt: endTime },
|
|
||||||
endTime: { gt: startTime },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (overlappingBooking) {
|
|
||||||
throw new AdminBookingServiceError(
|
|
||||||
`El horario seleccionado ya fue reservado para el dia ${formatIsoDate(date)}.`,
|
|
||||||
409
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await tx.courtBooking.create({
|
|
||||||
data: {
|
|
||||||
id: uuidv7(),
|
|
||||||
bookingCode: generateBookingCode(),
|
|
||||||
courtId,
|
|
||||||
bookingDate: date,
|
|
||||||
startTime,
|
|
||||||
endTime,
|
|
||||||
customerName: input.customerName?.trim() ?? group.customerName,
|
|
||||||
customerPhone: input.customerPhone?.trim() ?? group.customerPhone,
|
|
||||||
customerEmail: input.customerEmail?.trim() ?? group.customerEmail,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
recurringGroupId: groupId,
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: { select: { id: true, name: true, slug: true } },
|
|
||||||
complex: { select: { id: true, complexName: true } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await db.recurringBookingGroup.update({
|
|
||||||
where: { id: groupId },
|
|
||||||
data: {
|
|
||||||
...(input.customerName !== undefined && { customerName: input.customerName.trim() }),
|
|
||||||
...(input.customerPhone !== undefined && { customerPhone: input.customerPhone.trim() }),
|
|
||||||
...(input.customerEmail !== undefined && { customerEmail: input.customerEmail.trim() }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
const todayStart = new Date(
|
|
||||||
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
|
||||||
);
|
|
||||||
|
|
||||||
const updateData: Record<string, string> = {};
|
|
||||||
if (input.customerName !== undefined) updateData.customerName = input.customerName.trim();
|
|
||||||
if (input.customerPhone !== undefined) updateData.customerPhone = input.customerPhone.trim();
|
|
||||||
if (input.customerEmail !== undefined) updateData.customerEmail = input.customerEmail.trim();
|
|
||||||
|
|
||||||
if (Object.keys(updateData).length > 0) {
|
|
||||||
await db.courtBooking.updateMany({
|
|
||||||
where: { recurringGroupId: groupId, bookingDate: { gte: todayStart } },
|
|
||||||
data: updateData,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = await db.recurringBookingGroup.findUnique({
|
|
||||||
where: { id: groupId },
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: { select: { id: true, name: true, slug: true } },
|
|
||||||
complex: { select: { id: true, complexName: true } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
bookings: {
|
|
||||||
orderBy: { bookingDate: 'asc' },
|
|
||||||
include: {
|
|
||||||
court: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
sport: { select: { id: true, name: true, slug: true } },
|
|
||||||
complex: { select: { id: true, complexName: true } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
throw new AdminBookingServiceError('Error al actualizar el grupo.', 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: updated.id,
|
|
||||||
complexId: updated.complexId,
|
|
||||||
courtId: updated.courtId,
|
|
||||||
startTime: updated.startTime,
|
|
||||||
endTime: updated.endTime,
|
|
||||||
dayOfWeek: updated.dayOfWeek,
|
|
||||||
startDate: formatIsoDate(updated.startDate),
|
|
||||||
endDate: updated.endDate ? formatIsoDate(updated.endDate) : null,
|
|
||||||
status: updated.status,
|
|
||||||
customerName: updated.customerName,
|
|
||||||
customerPhone: updated.customerPhone,
|
|
||||||
customerEmail: updated.customerEmail,
|
|
||||||
bookings: updated.bookings.map(mapBookingResponse),
|
|
||||||
createdAt: updated.createdAt.toISOString(),
|
|
||||||
updatedAt: updated.updatedAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
6
apps/backend/src/modules/admin-booking/shared/errors.ts
Normal file
6
apps/backend/src/modules/admin-booking/shared/errors.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export class AdminBookingServiceError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'AdminBookingServiceError';
|
||||||
|
}
|
||||||
|
}
|
||||||
216
apps/backend/src/modules/admin-booking/shared/helpers.ts
Normal file
216
apps/backend/src/modules/admin-booking/shared/helpers.ts
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import type { AdminBooking, DayOfWeek } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export type Slot = { startTime: string; endTime: string };
|
||||||
|
|
||||||
|
const DAY_OF_WEEK_BY_INDEX = [
|
||||||
|
'SUNDAY',
|
||||||
|
'MONDAY',
|
||||||
|
'TUESDAY',
|
||||||
|
'WEDNESDAY',
|
||||||
|
'THURSDAY',
|
||||||
|
'FRIDAY',
|
||||||
|
'SATURDAY',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const BOOKING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const BOOKING_CODE_LENGTH = 6;
|
||||||
|
|
||||||
|
export function toMinutes(value: string): number {
|
||||||
|
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
||||||
|
return hours * 60 + minutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function minutesToTime(minutes: number): string {
|
||||||
|
const safeMinutes = Math.max(0, minutes);
|
||||||
|
const hours = Math.floor(safeMinutes / 60);
|
||||||
|
const mins = safeMinutes % 60;
|
||||||
|
return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseIsoDate(date: string): Result<Date> {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
return err(Errors.validation('La fecha debe tener formato YYYY-MM-DD.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
|
||||||
|
const bookingDate = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
|
||||||
|
if (
|
||||||
|
Number.isNaN(bookingDate.getTime()) ||
|
||||||
|
bookingDate.getUTCFullYear() !== year ||
|
||||||
|
bookingDate.getUTCMonth() + 1 !== month ||
|
||||||
|
bookingDate.getUTCDate() !== day
|
||||||
|
) {
|
||||||
|
return err(Errors.validation('La fecha enviada no es valida.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(bookingDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatIsoDate(date: Date): string {
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDayOfWeek(date: Date): Result<DayOfWeek> {
|
||||||
|
const dayOfWeek = DAY_OF_WEEK_BY_INDEX[date.getUTCDay()];
|
||||||
|
|
||||||
|
if (!dayOfWeek) {
|
||||||
|
return err(Errors.validation('No se pudo resolver el dia de la semana.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(dayOfWeek);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateBookingCode(): string {
|
||||||
|
let code = '';
|
||||||
|
|
||||||
|
for (let index = 0; index < BOOKING_CODE_LENGTH; index += 1) {
|
||||||
|
code += BOOKING_CODE_ALPHABET[randomInt(0, BOOKING_CODE_ALPHABET.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSlots(
|
||||||
|
availability: Array<{ startTime: string; endTime: string }>,
|
||||||
|
slotDurationMinutes: number
|
||||||
|
): Slot[] {
|
||||||
|
const slots: Slot[] = [];
|
||||||
|
|
||||||
|
for (const range of availability) {
|
||||||
|
const start = toMinutes(range.startTime);
|
||||||
|
const end = toMinutes(range.endTime);
|
||||||
|
|
||||||
|
for (
|
||||||
|
let current = start;
|
||||||
|
current + slotDurationMinutes <= end;
|
||||||
|
current += slotDurationMinutes
|
||||||
|
) {
|
||||||
|
slots.push({
|
||||||
|
startTime: minutesToTime(current),
|
||||||
|
endTime: minutesToTime(current + slotDurationMinutes),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureComplexAccess(
|
||||||
|
complexId: string,
|
||||||
|
userId: string
|
||||||
|
): Promise<
|
||||||
|
Result<{
|
||||||
|
id: string;
|
||||||
|
complexName: string;
|
||||||
|
plan: { rules: unknown } | null;
|
||||||
|
}>
|
||||||
|
> {
|
||||||
|
const complexUser = await db.complexUser.findUnique({
|
||||||
|
where: {
|
||||||
|
complexId_userId: { complexId, userId },
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
select: { id: true, complexName: true, plan: { select: { rules: true } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!complexUser) {
|
||||||
|
return err(Errors.forbidden('No tienes permisos para administrar este complejo.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(complexUser.complex);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePrice(
|
||||||
|
court: {
|
||||||
|
basePrice: unknown;
|
||||||
|
priceRules: Array<{
|
||||||
|
dayOfWeek: string | null;
|
||||||
|
startTime: string | null;
|
||||||
|
endTime: string | null;
|
||||||
|
price: unknown;
|
||||||
|
}>;
|
||||||
|
},
|
||||||
|
dayOfWeek: string,
|
||||||
|
startTime: string,
|
||||||
|
endTime: string
|
||||||
|
): number {
|
||||||
|
const slotStart = toMinutes(startTime);
|
||||||
|
const slotEnd = toMinutes(endTime);
|
||||||
|
|
||||||
|
const matchingRules = court.priceRules
|
||||||
|
.filter((rule) => {
|
||||||
|
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) return false;
|
||||||
|
if (!rule.startTime || !rule.endTime) return true;
|
||||||
|
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
|
||||||
|
})
|
||||||
|
.sort((first, second) => {
|
||||||
|
const firstSpecificity =
|
||||||
|
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
|
||||||
|
const secondSpecificity =
|
||||||
|
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
|
||||||
|
return secondSpecificity - firstSpecificity;
|
||||||
|
});
|
||||||
|
|
||||||
|
return Number(matchingRules[0]?.price ?? court.basePrice);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapBookingResponse(booking: {
|
||||||
|
id: string;
|
||||||
|
bookingCode: string;
|
||||||
|
bookingDate: Date;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
customerName: string;
|
||||||
|
customerPhone: string;
|
||||||
|
customerEmail: string;
|
||||||
|
status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NOSHOW';
|
||||||
|
recurringGroupId: string | null;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
court: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
complex: { id: string; complexName: string };
|
||||||
|
sport: { id: string; name: string; slug: string };
|
||||||
|
};
|
||||||
|
price?: number;
|
||||||
|
}): AdminBooking {
|
||||||
|
return {
|
||||||
|
id: booking.id,
|
||||||
|
bookingCode: booking.bookingCode,
|
||||||
|
complexId: booking.court.complex.id,
|
||||||
|
complexName: booking.court.complex.complexName,
|
||||||
|
courtId: booking.court.id,
|
||||||
|
courtName: booking.court.name,
|
||||||
|
sport: {
|
||||||
|
id: booking.court.sport.id,
|
||||||
|
name: booking.court.sport.name,
|
||||||
|
slug: booking.court.sport.slug,
|
||||||
|
},
|
||||||
|
date: formatIsoDate(booking.bookingDate),
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
customerName: booking.customerName,
|
||||||
|
customerPhone: booking.customerPhone,
|
||||||
|
customerEmail: booking.customerEmail,
|
||||||
|
price: booking.price ?? 0,
|
||||||
|
status: booking.status,
|
||||||
|
recurringGroupId: booking.recurringGroupId,
|
||||||
|
createdAt: booking.createdAt.toISOString(),
|
||||||
|
updatedAt: booking.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
import { validate } from '@/lib/http/validate';
|
import { validate } from '@/lib/http/validate';
|
||||||
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||||
import { requireSuperAdmin } from '@/middlewares/require-super-admin.middleware';
|
import { requireSuperAdmin } from '@/middlewares/require-super-admin.middleware';
|
||||||
import { blockUserHandler } from '@/modules/admin/handlers/block-user.handler';
|
import { blockUserHandler } from '@/modules/admin/features/block-user/block-user.handler';
|
||||||
import { createPlanHandler } from '@/modules/admin/handlers/create-plan.handler';
|
import { createPlanHandler } from '@/modules/admin/features/create-plan/create-plan.handler';
|
||||||
import { deletePlanHandler } from '@/modules/admin/handlers/delete-plan.handler';
|
import { deletePlanHandler } from '@/modules/admin/features/delete-plan/delete-plan.handler';
|
||||||
import { getGeoStatsHandler } from '@/modules/admin/handlers/get-geo-stats.handler';
|
import { getGeoStatsHandler } from '@/modules/admin/features/get-geo-stats/get-geo-stats.handler';
|
||||||
import { getUserSessionsHandler } from '@/modules/admin/handlers/get-user-sessions.handler';
|
import { getUserSessionsHandler } from '@/modules/admin/features/get-user-sessions/get-user-sessions.handler';
|
||||||
import { listComplexesHandler } from '@/modules/admin/handlers/list-complexes.handler';
|
import { listComplexesHandler } from '@/modules/admin/features/list-complexes/list-complexes.handler';
|
||||||
import { listPlansAdminHandler } from '@/modules/admin/handlers/list-plans-admin.handler';
|
import { listPlansAdminHandler } from '@/modules/admin/features/list-plans-admin/list-plans-admin.handler';
|
||||||
import { listUsersHandler } from '@/modules/admin/handlers/list-users.handler';
|
import { listUsersHandler } from '@/modules/admin/features/list-users/list-users.handler';
|
||||||
import { revokeAllSessionsHandler } from '@/modules/admin/handlers/revoke-all-sessions.handler';
|
import { revokeAllSessionsHandler } from '@/modules/admin/features/revoke-all-sessions/revoke-all-sessions.handler';
|
||||||
import { unblockUserHandler } from '@/modules/admin/handlers/unblock-user.handler';
|
import { unblockUserHandler } from '@/modules/admin/features/unblock-user/unblock-user.handler';
|
||||||
import { updatePlanHandler } from '@/modules/admin/handlers/update-plan.handler';
|
import { updatePlanHandler } from '@/modules/admin/features/update-plan/update-plan.handler';
|
||||||
import type { AppEnv } from '@/types/hono';
|
import type { AppEnv } from '@/types/hono';
|
||||||
import {
|
import {
|
||||||
adminBlockUserSchema,
|
adminBlockUserSchema,
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { AdminServiceError } from '../../shared/errors';
|
||||||
|
|
||||||
|
export async function blockUser(userId: string, banReason?: string): Promise<void> {
|
||||||
|
const target = await db.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { role: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!target) {
|
||||||
|
throw new AdminServiceError('Usuario no encontrado.', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.role === 'super_admin') {
|
||||||
|
throw new AdminServiceError('No se puede bloquear un super_admin.', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.user.update({
|
||||||
|
where: { id: userId },
|
||||||
|
data: {
|
||||||
|
banned: true,
|
||||||
|
bannedAt: new Date(),
|
||||||
|
banReason: banReason ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { AdminServiceError, blockUser } from '@/modules/admin/services/admin-users.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { AdminBlockUserInput } from '@repo/api-contract';
|
import type { AdminBlockUserInput } from '@repo/api-contract';
|
||||||
|
import { AdminServiceError } from '../../shared/errors';
|
||||||
|
import { blockUser } from './block-user.business';
|
||||||
|
|
||||||
type BlockUserParams = { id: string };
|
type BlockUserParams = { id: string };
|
||||||
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { AdminCreatePlanInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
export async function createPlan(input: AdminCreatePlanInput) {
|
||||||
|
const existing = await db.plan.findUnique({
|
||||||
|
where: { code: input.code },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
return { ok: false as const, message: 'Ya existe un plan con ese código.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const plan = await db.plan.create({
|
||||||
|
data: {
|
||||||
|
code: input.code,
|
||||||
|
name: input.name,
|
||||||
|
price: input.price,
|
||||||
|
rules: input.rules,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
data: {
|
||||||
|
code: plan.code,
|
||||||
|
name: plan.name,
|
||||||
|
price: Number(plan.price),
|
||||||
|
rules: plan.rules,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import type { AdminCreatePlanInput } from '@repo/api-contract';
|
||||||
|
import { createPlan } from './create-plan.business';
|
||||||
|
|
||||||
|
export async function createPlanHandler(c: AppContext) {
|
||||||
|
const body = c.req.valid('json' as never) as AdminCreatePlanInput;
|
||||||
|
|
||||||
|
const result = await createPlan(body);
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
return c.json({ message: result.message }, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json(result.data, 201);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function deletePlan(code: string) {
|
||||||
|
const existing = await db.plan.findUnique({
|
||||||
|
where: { code },
|
||||||
|
include: {
|
||||||
|
_count: { select: { complexes: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
return { ok: false as const, message: 'Plan no encontrado.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing._count.complexes > 0) {
|
||||||
|
return {
|
||||||
|
ok: false as const,
|
||||||
|
message: 'No se puede eliminar un plan que tiene complejos asignados.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.plan.delete({ where: { code } });
|
||||||
|
|
||||||
|
return { ok: true as const, message: 'Plan eliminado correctamente.' };
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { deletePlan } from './delete-plan.business';
|
||||||
|
|
||||||
|
type DeletePlanParams = { code: string };
|
||||||
|
|
||||||
|
export async function deletePlanHandler(c: AppContext) {
|
||||||
|
const { code } = c.req.valid('param' as never) as DeletePlanParams;
|
||||||
|
|
||||||
|
const result = await deletePlan(code);
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
const status = result.message === 'Plan no encontrado.' ? 404 : 409;
|
||||||
|
return c.json({ message: result.message }, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json({ message: result.message });
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { getGeoStats } from '@/modules/admin/services/admin-geo.service';
|
|
||||||
import type { AppEnv } from '@/types/hono';
|
import type { AppEnv } from '@/types/hono';
|
||||||
import type { Handler } from 'hono';
|
import type { Handler } from 'hono';
|
||||||
|
import { getGeoStats } from './get-geo-stats.business';
|
||||||
|
|
||||||
export const getGeoStatsHandler: Handler<AppEnv> = async (c) => {
|
export const getGeoStatsHandler: Handler<AppEnv> = async (c) => {
|
||||||
const stats = await getGeoStats();
|
const stats = await getGeoStats();
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { fetchGeoInfo } from '@/lib/geoip';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
type AdminUserSession = {
|
||||||
|
id: string;
|
||||||
|
createdAt: string;
|
||||||
|
expiresAt: string;
|
||||||
|
ipAddress: string | null;
|
||||||
|
userAgent: string | null;
|
||||||
|
city: string | null;
|
||||||
|
country: string | null;
|
||||||
|
countryCode: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getUserSessions(userId: string): Promise<AdminUserSession[]> {
|
||||||
|
const sessions = await db.session.findMany({
|
||||||
|
where: { userId },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const uniqueIps = [...new Set(sessions.map((s) => s.ipAddress).filter(Boolean))] as string[];
|
||||||
|
const geoResults = await Promise.all(uniqueIps.map((ip) => fetchGeoInfo(ip)));
|
||||||
|
const geoMap = new Map<
|
||||||
|
string,
|
||||||
|
{ city: string | null; country: string | null; countryCode: string | null }
|
||||||
|
>();
|
||||||
|
for (let i = 0; i < uniqueIps.length; i++) {
|
||||||
|
const info = geoResults[i];
|
||||||
|
geoMap.set(uniqueIps[i], {
|
||||||
|
city: info?.city ?? null,
|
||||||
|
country: info?.country ?? null,
|
||||||
|
countryCode: info?.countryCode ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return sessions.map((s) => {
|
||||||
|
const geo = s.ipAddress ? geoMap.get(s.ipAddress) : null;
|
||||||
|
return {
|
||||||
|
id: s.id,
|
||||||
|
createdAt: s.createdAt.toISOString(),
|
||||||
|
expiresAt: s.expiresAt.toISOString(),
|
||||||
|
ipAddress: s.ipAddress,
|
||||||
|
userAgent: s.userAgent,
|
||||||
|
city: geo?.city ?? null,
|
||||||
|
country: geo?.country ?? null,
|
||||||
|
countryCode: geo?.countryCode ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getUserSessions } from '@/modules/admin/services/admin-users.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getUserSessions } from './get-user-sessions.business';
|
||||||
|
|
||||||
type UserSessionsParams = { id: string };
|
type UserSessionsParams = { id: string };
|
||||||
|
|
||||||
@@ -26,9 +26,7 @@ export async function getComplexStatsList(): Promise<ComplexStats[]> {
|
|||||||
plan: true,
|
plan: true,
|
||||||
users: true,
|
users: true,
|
||||||
courts: {
|
courts: {
|
||||||
include: {
|
include: { bookings: true },
|
||||||
bookings: true,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getComplexStatsList } from '@/modules/admin/services/complex-stats.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getComplexStatsList } from './list-complexes.business';
|
||||||
|
|
||||||
export async function listComplexesHandler(c: AppContext) {
|
export async function listComplexesHandler(c: AppContext) {
|
||||||
const stats = await getComplexStatsList();
|
const stats = await getComplexStatsList();
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function listPlansAdmin() {
|
||||||
|
const plans = await db.plan.findMany({
|
||||||
|
orderBy: { price: 'asc' },
|
||||||
|
include: {
|
||||||
|
_count: { select: { complexes: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return plans.map((plan) => ({
|
||||||
|
code: plan.code,
|
||||||
|
name: plan.name,
|
||||||
|
price: Number(plan.price),
|
||||||
|
rules: plan.rules,
|
||||||
|
lastUpdatedAt: plan.lastUpdatedAt.toISOString(),
|
||||||
|
complexCount: plan._count.complexes,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { listPlansAdmin } from './list-plans-admin.business';
|
||||||
|
|
||||||
|
export async function listPlansAdminHandler(c: AppContext) {
|
||||||
|
const plans = await listPlansAdmin();
|
||||||
|
return c.json(plans);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
type AdminUser = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
banned: boolean;
|
||||||
|
bannedAt: string | null;
|
||||||
|
banReason: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
complexCount: number;
|
||||||
|
activeSessions: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listAdminUsers(search?: string): Promise<AdminUser[]> {
|
||||||
|
const users = await db.user.findMany({
|
||||||
|
where: search
|
||||||
|
? {
|
||||||
|
OR: [
|
||||||
|
{ name: { contains: search, mode: 'insensitive' } },
|
||||||
|
{ email: { contains: search, mode: 'insensitive' } },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
include: {
|
||||||
|
_count: { select: { complexes: true, sessions: true } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
return users.map((user) => ({
|
||||||
|
id: user.id,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
banned: user.banned ?? false,
|
||||||
|
bannedAt: user.bannedAt?.toISOString() ?? null,
|
||||||
|
banReason: user.banReason ?? null,
|
||||||
|
createdAt: user.createdAt.toISOString(),
|
||||||
|
complexCount: user._count.complexes,
|
||||||
|
activeSessions: user._count.sessions,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { listAdminUsers } from '@/modules/admin/services/admin-users.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { listAdminUsers } from './list-users.business';
|
||||||
|
|
||||||
export async function listUsersHandler(c: AppContext) {
|
export async function listUsersHandler(c: AppContext) {
|
||||||
const search = c.req.query('search');
|
const search = c.req.query('search');
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function revokeAllUserSessions(userId: string): Promise<number> {
|
||||||
|
const result = await db.session.deleteMany({
|
||||||
|
where: { userId },
|
||||||
|
});
|
||||||
|
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { revokeAllUserSessions } from '@/modules/admin/services/admin-users.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { revokeAllUserSessions } from './revoke-all-sessions.business';
|
||||||
|
|
||||||
type RevokeSessionsParams = { id: string };
|
type RevokeSessionsParams = { id: string };
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function unblockUser(userId: string): Promise<void> {
|
||||||
|
await db.user.update({
|
||||||
|
where: { id: userId },
|
||||||
|
data: {
|
||||||
|
banned: false,
|
||||||
|
bannedAt: null,
|
||||||
|
banReason: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { unblockUser } from '@/modules/admin/services/admin-users.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { unblockUser } from './unblock-user.business';
|
||||||
|
|
||||||
type UnblockUserParams = { id: string };
|
type UnblockUserParams = { id: string };
|
||||||
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { AdminUpdatePlanInput } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export async function updatePlan(code: string, input: AdminUpdatePlanInput) {
|
||||||
|
const existing = await db.plan.findUnique({ where: { code } });
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
return { ok: false as const, message: 'Plan no encontrado.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const plan = await db.plan.update({
|
||||||
|
where: { code },
|
||||||
|
data: {
|
||||||
|
...(input.name !== undefined && { name: input.name }),
|
||||||
|
...(input.price !== undefined && { price: input.price }),
|
||||||
|
...(input.rules !== undefined && { rules: input.rules }),
|
||||||
|
lastUpdatedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
data: {
|
||||||
|
code: plan.code,
|
||||||
|
name: plan.name,
|
||||||
|
price: Number(plan.price),
|
||||||
|
rules: plan.rules,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import type { AdminUpdatePlanInput } from '@repo/api-contract';
|
||||||
|
import { updatePlan } from './update-plan.business';
|
||||||
|
|
||||||
|
type UpdatePlanParams = { code: string };
|
||||||
|
|
||||||
|
export async function updatePlanHandler(c: AppContext) {
|
||||||
|
const { code } = c.req.valid('param' as never) as UpdatePlanParams;
|
||||||
|
const body = c.req.valid('json' as never) as AdminUpdatePlanInput;
|
||||||
|
|
||||||
|
const result = await updatePlan(code, body);
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
return c.json({ message: result.message }, 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json(result.data);
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { db } from '@/lib/prisma';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
import type { AdminCreatePlanInput } from '@repo/api-contract';
|
|
||||||
|
|
||||||
export async function createPlanHandler(c: AppContext) {
|
|
||||||
const body = c.req.valid('json' as never) as AdminCreatePlanInput;
|
|
||||||
|
|
||||||
const existing = await db.plan.findUnique({
|
|
||||||
where: { code: body.code },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (existing) {
|
|
||||||
return c.json({ message: 'Ya existe un plan con ese código.' }, 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
const plan = await db.plan.create({
|
|
||||||
data: {
|
|
||||||
code: body.code,
|
|
||||||
name: body.name,
|
|
||||||
price: body.price,
|
|
||||||
rules: body.rules,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return c.json(
|
|
||||||
{
|
|
||||||
code: plan.code,
|
|
||||||
name: plan.name,
|
|
||||||
price: Number(plan.price),
|
|
||||||
rules: plan.rules,
|
|
||||||
},
|
|
||||||
201
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { db } from '@/lib/prisma';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
|
|
||||||
type DeletePlanParams = { code: string };
|
|
||||||
|
|
||||||
export async function deletePlanHandler(c: AppContext) {
|
|
||||||
const { code } = c.req.valid('param' as never) as DeletePlanParams;
|
|
||||||
|
|
||||||
const existing = await db.plan.findUnique({
|
|
||||||
where: { code },
|
|
||||||
include: {
|
|
||||||
_count: {
|
|
||||||
select: { complexes: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!existing) {
|
|
||||||
return c.json({ message: 'Plan no encontrado.' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existing._count.complexes > 0) {
|
|
||||||
return c.json({ message: 'No se puede eliminar un plan que tiene complejos asignados.' }, 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.plan.delete({
|
|
||||||
where: { code },
|
|
||||||
});
|
|
||||||
|
|
||||||
return c.json({ message: 'Plan eliminado correctamente.' });
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { db } from '@/lib/prisma';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
|
|
||||||
export async function listPlansAdminHandler(c: AppContext) {
|
|
||||||
const plans = await db.plan.findMany({
|
|
||||||
orderBy: { price: 'asc' },
|
|
||||||
include: {
|
|
||||||
_count: {
|
|
||||||
select: { complexes: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return c.json(
|
|
||||||
plans.map((plan) => ({
|
|
||||||
code: plan.code,
|
|
||||||
name: plan.name,
|
|
||||||
price: Number(plan.price),
|
|
||||||
rules: plan.rules,
|
|
||||||
lastUpdatedAt: plan.lastUpdatedAt.toISOString(),
|
|
||||||
complexCount: plan._count.complexes,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { db } from '@/lib/prisma';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
|
||||||
import type { AdminUpdatePlanInput } from '@repo/api-contract';
|
|
||||||
|
|
||||||
type UpdatePlanParams = { code: string };
|
|
||||||
|
|
||||||
export async function updatePlanHandler(c: AppContext) {
|
|
||||||
const { code } = c.req.valid('param' as never) as UpdatePlanParams;
|
|
||||||
const body = c.req.valid('json' as never) as AdminUpdatePlanInput;
|
|
||||||
|
|
||||||
const existing = await db.plan.findUnique({
|
|
||||||
where: { code },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!existing) {
|
|
||||||
return c.json({ message: 'Plan no encontrado.' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
const plan = await db.plan.update({
|
|
||||||
where: { code },
|
|
||||||
data: {
|
|
||||||
...(body.name !== undefined && { name: body.name }),
|
|
||||||
...(body.price !== undefined && { price: body.price }),
|
|
||||||
...(body.rules !== undefined && { rules: body.rules }),
|
|
||||||
lastUpdatedAt: new Date(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
code: plan.code,
|
|
||||||
name: plan.name,
|
|
||||||
price: Number(plan.price),
|
|
||||||
rules: plan.rules,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
import { fetchGeoInfo } from '@/lib/geoip';
|
|
||||||
import { db } from '@/lib/prisma';
|
|
||||||
|
|
||||||
type AdminUser = {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
role: string;
|
|
||||||
banned: boolean;
|
|
||||||
bannedAt: string | null;
|
|
||||||
banReason: string | null;
|
|
||||||
createdAt: string;
|
|
||||||
complexCount: number;
|
|
||||||
activeSessions: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function listAdminUsers(search?: string): Promise<AdminUser[]> {
|
|
||||||
const users = await db.user.findMany({
|
|
||||||
where: search
|
|
||||||
? {
|
|
||||||
OR: [
|
|
||||||
{ name: { contains: search, mode: 'insensitive' } },
|
|
||||||
{ email: { contains: search, mode: 'insensitive' } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
include: {
|
|
||||||
_count: {
|
|
||||||
select: { complexes: true, sessions: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
});
|
|
||||||
|
|
||||||
return users.map((user) => ({
|
|
||||||
id: user.id,
|
|
||||||
name: user.name,
|
|
||||||
email: user.email,
|
|
||||||
role: user.role,
|
|
||||||
banned: user.banned ?? false,
|
|
||||||
bannedAt: user.bannedAt?.toISOString() ?? null,
|
|
||||||
banReason: user.banReason ?? null,
|
|
||||||
createdAt: user.createdAt.toISOString(),
|
|
||||||
complexCount: user._count.complexes,
|
|
||||||
activeSessions: user._count.sessions,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
type AdminUserSession = {
|
|
||||||
id: string;
|
|
||||||
createdAt: string;
|
|
||||||
expiresAt: string;
|
|
||||||
ipAddress: string | null;
|
|
||||||
userAgent: string | null;
|
|
||||||
city: string | null;
|
|
||||||
country: string | null;
|
|
||||||
countryCode: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function getUserSessions(userId: string): Promise<AdminUserSession[]> {
|
|
||||||
const sessions = await db.session.findMany({
|
|
||||||
where: { userId },
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
});
|
|
||||||
|
|
||||||
const uniqueIps = [...new Set(sessions.map((s) => s.ipAddress).filter(Boolean))] as string[];
|
|
||||||
const geoResults = await Promise.all(uniqueIps.map((ip) => fetchGeoInfo(ip)));
|
|
||||||
const geoMap = new Map<
|
|
||||||
string,
|
|
||||||
{ city: string | null; country: string | null; countryCode: string | null }
|
|
||||||
>();
|
|
||||||
for (let i = 0; i < uniqueIps.length; i++) {
|
|
||||||
const info = geoResults[i];
|
|
||||||
geoMap.set(uniqueIps[i], {
|
|
||||||
city: info?.city ?? null,
|
|
||||||
country: info?.country ?? null,
|
|
||||||
countryCode: info?.countryCode ?? null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return sessions.map((s) => {
|
|
||||||
const geo = s.ipAddress ? geoMap.get(s.ipAddress) : null;
|
|
||||||
return {
|
|
||||||
id: s.id,
|
|
||||||
createdAt: s.createdAt.toISOString(),
|
|
||||||
expiresAt: s.expiresAt.toISOString(),
|
|
||||||
ipAddress: s.ipAddress,
|
|
||||||
userAgent: s.userAgent,
|
|
||||||
city: geo?.city ?? null,
|
|
||||||
country: geo?.country ?? null,
|
|
||||||
countryCode: geo?.countryCode ?? null,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AdminServiceError extends Error {
|
|
||||||
status: 400 | 403 | 404;
|
|
||||||
constructor(message: string, status: 400 | 403 | 404 = 400) {
|
|
||||||
super(message);
|
|
||||||
this.status = status;
|
|
||||||
this.name = 'AdminServiceError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function blockUser(userId: string, banReason?: string): Promise<void> {
|
|
||||||
const target = await db.user.findUnique({
|
|
||||||
where: { id: userId },
|
|
||||||
select: { role: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!target) {
|
|
||||||
throw new AdminServiceError('Usuario no encontrado.', 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (target.role === 'super_admin') {
|
|
||||||
throw new AdminServiceError('No se puede bloquear un super_admin.', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.user.update({
|
|
||||||
where: { id: userId },
|
|
||||||
data: {
|
|
||||||
banned: true,
|
|
||||||
bannedAt: new Date(),
|
|
||||||
banReason: banReason ?? null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function unblockUser(userId: string): Promise<void> {
|
|
||||||
await db.user.update({
|
|
||||||
where: { id: userId },
|
|
||||||
data: {
|
|
||||||
banned: false,
|
|
||||||
bannedAt: null,
|
|
||||||
banReason: null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function revokeAllUserSessions(userId: string): Promise<number> {
|
|
||||||
const result = await db.session.deleteMany({
|
|
||||||
where: { userId },
|
|
||||||
});
|
|
||||||
|
|
||||||
return result.count;
|
|
||||||
}
|
|
||||||
9
apps/backend/src/modules/admin/shared/errors.ts
Normal file
9
apps/backend/src/modules/admin/shared/errors.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export class AdminServiceError extends Error {
|
||||||
|
status: 400 | 403 | 404;
|
||||||
|
|
||||||
|
constructor(message: string, status: 400 | 403 | 404 = 400) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
this.name = 'AdminServiceError';
|
||||||
|
}
|
||||||
|
}
|
||||||
24
apps/backend/src/modules/billing/billing.routes.ts
Normal file
24
apps/backend/src/modules/billing/billing.routes.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { validate } from '@/lib/http/validate';
|
||||||
|
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||||
|
import { cancelSubscriptionHandler } from '@/modules/billing/features/cancel-subscription/cancel-subscription.handler';
|
||||||
|
import { createCheckoutHandler } from '@/modules/billing/features/create-checkout/create-checkout.handler';
|
||||||
|
import { getBillingStatusHandler } from '@/modules/billing/features/get-billing-status/get-billing-status.handler';
|
||||||
|
import { mercadopagoWebhookHandler } from '@/modules/billing/features/mercadopago-webhook/mercadopago-webhook.handler';
|
||||||
|
import { stripeWebhookHandler } from '@/modules/billing/features/stripe-webhook/stripe-webhook.handler';
|
||||||
|
import type { AppEnv } from '@/types/hono';
|
||||||
|
import { createCheckoutSchema } from '@repo/api-contract';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
|
export const billingRoutes = new Hono<AppEnv>();
|
||||||
|
|
||||||
|
billingRoutes.post(
|
||||||
|
'/checkout',
|
||||||
|
requireAuth,
|
||||||
|
validate.json(createCheckoutSchema),
|
||||||
|
createCheckoutHandler
|
||||||
|
);
|
||||||
|
billingRoutes.post('/cancel', requireAuth, cancelSubscriptionHandler);
|
||||||
|
billingRoutes.get('/status', requireAuth, getBillingStatusHandler);
|
||||||
|
|
||||||
|
billingRoutes.post('/webhooks/stripe', stripeWebhookHandler);
|
||||||
|
billingRoutes.post('/webhooks/mercadopago', mercadopagoWebhookHandler);
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import { getBilling } from '@/modules/billing/services/billing-repository.service';
|
||||||
|
import { getProviderForComplex } from '@/modules/billing/services/provider-resolver.service';
|
||||||
|
|
||||||
|
export async function cancelSubscription(
|
||||||
|
user: { id: string },
|
||||||
|
complexId: string
|
||||||
|
): Promise<Result<{ status: string }>> {
|
||||||
|
const userAccess = await db.complexUser.findUnique({
|
||||||
|
where: { complexId_userId: { complexId, userId: user.id } },
|
||||||
|
select: { role: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!userAccess || userAccess.role !== 'ADMIN') {
|
||||||
|
return err(Errors.forbidden('Only admins can cancel the subscription'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const billingResult = await getBilling(complexId);
|
||||||
|
if (!billingResult.ok) return err(billingResult.error);
|
||||||
|
const billing = billingResult.value;
|
||||||
|
|
||||||
|
if (billing.status === 'CANCELED' || billing.status === 'SUSPENDED') {
|
||||||
|
return err(Errors.conflict('La suscripción ya está cancelada o suspendida'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const providerResult = await getProviderForComplex(complexId);
|
||||||
|
if (!providerResult.ok) return err(providerResult.error);
|
||||||
|
const { provider } = providerResult.value;
|
||||||
|
|
||||||
|
const subId = billing.providerSubscriptionId;
|
||||||
|
if (subId) {
|
||||||
|
const cancelResult = await provider.cancelSubscription(subId);
|
||||||
|
if (!cancelResult.ok) return err(cancelResult.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.complexBilling.update({
|
||||||
|
where: { complexId },
|
||||||
|
data: {
|
||||||
|
status: 'CANCELED',
|
||||||
|
canceledAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ status: 'CANCELED' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getCookie } from 'hono/cookie';
|
||||||
|
import { cancelSubscription } from './cancel-subscription.business';
|
||||||
|
|
||||||
|
const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
|
||||||
|
|
||||||
|
export async function cancelSubscriptionHandler(c: AppContext) {
|
||||||
|
const user = c.get('user');
|
||||||
|
const complexId = getCookie(c, SELECTED_COMPLEX_COOKIE);
|
||||||
|
|
||||||
|
if (!complexId) {
|
||||||
|
return c.json({ message: 'No complex selected' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return handleResult(c, await cancelSubscription(user, complexId));
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import { hasActiveSubscription } from '@/modules/billing/services/billing-repository.service';
|
||||||
|
import { getProviderForComplex } from '@/modules/billing/services/provider-resolver.service';
|
||||||
|
import type { CheckoutResponse, CreateCheckoutInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
export async function createCheckout(
|
||||||
|
user: { id: string; email: string },
|
||||||
|
complexId: string,
|
||||||
|
input: CreateCheckoutInput
|
||||||
|
): Promise<Result<CheckoutResponse>> {
|
||||||
|
const complex = await db.complex.findUnique({
|
||||||
|
where: { id: complexId },
|
||||||
|
select: { id: true, country: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!complex) {
|
||||||
|
return err(Errors.notFound('Complex not found'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const userAccess = await db.complexUser.findUnique({
|
||||||
|
where: { complexId_userId: { complexId, userId: user.id } },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!userAccess) {
|
||||||
|
return err(Errors.forbidden('You do not have access to this complex'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeResult = await hasActiveSubscription(complexId);
|
||||||
|
if (!activeResult.ok) return err(activeResult.error);
|
||||||
|
if (activeResult.value) {
|
||||||
|
return err(Errors.conflict('Ya existe una suscripción activa para este complejo'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const providerResult = await getProviderForComplex(complexId);
|
||||||
|
if (!providerResult.ok) return err(providerResult.error);
|
||||||
|
const { provider, country } = providerResult.value;
|
||||||
|
|
||||||
|
const currency = country === 'AR' ? 'ARS' : 'USD';
|
||||||
|
|
||||||
|
const baseUrl = Bun.env.FRONTEND_BASE_URL || Bun.env.APP_BASE_URL || 'http://localhost:5173';
|
||||||
|
const successUrl = `${baseUrl}/billing/success`;
|
||||||
|
const cancelUrl = `${baseUrl}/billing/cancel`;
|
||||||
|
|
||||||
|
const checkoutResult = await provider.createCheckout({
|
||||||
|
planCode: input.planCode,
|
||||||
|
complexId,
|
||||||
|
customerEmail: user.email,
|
||||||
|
successUrl,
|
||||||
|
cancelUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!checkoutResult.ok) return err(checkoutResult.error);
|
||||||
|
|
||||||
|
await db.complexBilling.upsert({
|
||||||
|
where: { complexId },
|
||||||
|
create: {
|
||||||
|
complexId,
|
||||||
|
planCode: input.planCode,
|
||||||
|
currency,
|
||||||
|
status: 'TRIAL',
|
||||||
|
provider: country === 'AR' ? 'MERCADOPAGO' : 'STRIPE',
|
||||||
|
providerSubscriptionId: checkoutResult.value.providerSubscriptionId,
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
planCode: input.planCode,
|
||||||
|
currency,
|
||||||
|
status: 'TRIAL',
|
||||||
|
provider: country === 'AR' ? 'MERCADOPAGO' : 'STRIPE',
|
||||||
|
providerSubscriptionId: checkoutResult.value.providerSubscriptionId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
checkoutUrl: checkoutResult.value.checkoutUrl,
|
||||||
|
subscriptionId: checkoutResult.value.providerSubscriptionId,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import type { CreateCheckoutInput } from '@repo/api-contract';
|
||||||
|
import { getCookie } from 'hono/cookie';
|
||||||
|
import { createCheckout } from './create-checkout.business';
|
||||||
|
|
||||||
|
const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
|
||||||
|
|
||||||
|
export async function createCheckoutHandler(c: AppContext) {
|
||||||
|
const user = c.get('user');
|
||||||
|
const complexId = getCookie(c, SELECTED_COMPLEX_COOKIE);
|
||||||
|
const payload = c.req.valid('json' as never) as CreateCheckoutInput;
|
||||||
|
|
||||||
|
if (!complexId) {
|
||||||
|
return c.json({ message: 'No complex selected' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return handleResult(c, await createCheckout(user, complexId, payload), 201);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import { getBilling } from '@/modules/billing/services/billing-repository.service';
|
||||||
|
import type { BillingStatusResponse } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export async function getBillingStatus(
|
||||||
|
_user: { id: string },
|
||||||
|
complexId: string
|
||||||
|
): Promise<Result<BillingStatusResponse>> {
|
||||||
|
const billingResult = await getBilling(complexId);
|
||||||
|
if (!billingResult.ok) return err(billingResult.error);
|
||||||
|
const billing = billingResult.value;
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
complexId: billing.complexId,
|
||||||
|
status: billing.status,
|
||||||
|
planCode: billing.planCode,
|
||||||
|
currency: billing.currency,
|
||||||
|
provider: billing.provider,
|
||||||
|
currentPeriodEnd: billing.currentPeriodEnd?.toISOString() ?? null,
|
||||||
|
currentPeriodStart: billing.currentPeriodStart?.toISOString() ?? null,
|
||||||
|
trialEndsAt: billing.trialEndsAt?.toISOString() ?? null,
|
||||||
|
canceledAt: billing.canceledAt?.toISOString() ?? null,
|
||||||
|
suspendedAt: billing.suspendedAt?.toISOString() ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getCookie } from 'hono/cookie';
|
||||||
|
import { getBillingStatus } from './get-billing-status.business';
|
||||||
|
|
||||||
|
const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
|
||||||
|
|
||||||
|
export async function getBillingStatusHandler(c: AppContext) {
|
||||||
|
const user = c.get('user');
|
||||||
|
const complexId = getCookie(c, SELECTED_COMPLEX_COOKIE);
|
||||||
|
|
||||||
|
if (!complexId) {
|
||||||
|
return c.json({ message: 'No complex selected' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return handleResult(c, await getBillingStatus(user, complexId));
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { logger } from '@/lib/logger';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import type { WebhookEvent } from '@/modules/billing/providers/billing-provider.interface';
|
||||||
|
import { mercadopagoBillingProvider } from '@/modules/billing/providers/mercadopago.provider';
|
||||||
|
import {
|
||||||
|
findEventByProviderId,
|
||||||
|
recordBillingEvent,
|
||||||
|
updateBillingStatus,
|
||||||
|
} from '@/modules/billing/services/billing-repository.service';
|
||||||
|
import type { BillingStatusEnum } from '@/modules/billing/services/billing-repository.service';
|
||||||
|
|
||||||
|
const MP_PROVIDER = 'MERCADOPAGO';
|
||||||
|
|
||||||
|
function mapWebhookTypeToStatus(event: WebhookEvent): BillingStatusEnum | null {
|
||||||
|
switch (event.type) {
|
||||||
|
case 'activated':
|
||||||
|
return 'ACTIVE';
|
||||||
|
case 'updated':
|
||||||
|
return 'ACTIVE';
|
||||||
|
case 'payment_failed':
|
||||||
|
return 'PAST_DUE';
|
||||||
|
case 'cancelled':
|
||||||
|
return 'CANCELED';
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getBillingByPreapprovalId(preapprovalId: string) {
|
||||||
|
return db.complexBilling.findFirst({
|
||||||
|
where: { providerPreapprovalId: preapprovalId },
|
||||||
|
}) as Promise<{ complexId: string; status: BillingStatusEnum } | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getBillingByExternalRef(externalRef: string) {
|
||||||
|
return db.complexBilling.findUnique({
|
||||||
|
where: { complexId: externalRef },
|
||||||
|
}) as Promise<{ complexId: string; status: BillingStatusEnum } | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processMercadoPagoWebhook(
|
||||||
|
body: Record<string, unknown>,
|
||||||
|
signature: string | undefined,
|
||||||
|
requestId: string | undefined
|
||||||
|
): Promise<Result<{ received: boolean }>> {
|
||||||
|
const parsedResult = await mercadopagoBillingProvider.parseWebhook(body, signature, requestId);
|
||||||
|
|
||||||
|
if (!parsedResult.ok) {
|
||||||
|
if (parsedResult.error.type === 'validation') {
|
||||||
|
return err(parsedResult.error);
|
||||||
|
}
|
||||||
|
logger.error({ error: parsedResult.error }, 'MP webhook parse failed');
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const event = parsedResult.value;
|
||||||
|
|
||||||
|
const existingResult = await findEventByProviderId(event.providerEventId);
|
||||||
|
if (!existingResult.ok) return err(existingResult.error);
|
||||||
|
if (existingResult.value) {
|
||||||
|
logger.info(
|
||||||
|
{ providerEventId: event.providerEventId },
|
||||||
|
'MP webhook: already processed, skipping'
|
||||||
|
);
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const newStatus = mapWebhookTypeToStatus(event);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const billing =
|
||||||
|
(await getBillingByPreapprovalId(event.providerSubscriptionId)) ??
|
||||||
|
(await getBillingByExternalRef(event.providerSubscriptionId));
|
||||||
|
|
||||||
|
if (!billing) {
|
||||||
|
logger.info(
|
||||||
|
{ providerSubscriptionId: event.providerSubscriptionId, eventType: event.type },
|
||||||
|
'MP webhook: no billing record found'
|
||||||
|
);
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: 'unknown',
|
||||||
|
eventType: `unlinked:${event.type}`,
|
||||||
|
provider: MP_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: event.data ?? null,
|
||||||
|
previousStatus: null,
|
||||||
|
newStatus: null,
|
||||||
|
});
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousStatus = billing.status;
|
||||||
|
|
||||||
|
if (newStatus) {
|
||||||
|
await updateBillingStatus(billing.complexId, newStatus, {
|
||||||
|
provider: MP_PROVIDER,
|
||||||
|
providerPreapprovalId: event.providerSubscriptionId,
|
||||||
|
...(event.type === 'activated' || event.type === 'updated'
|
||||||
|
? {
|
||||||
|
currentPeriodStart: new Date(),
|
||||||
|
currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: billing.complexId,
|
||||||
|
eventType: event.type,
|
||||||
|
provider: MP_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: event.data ?? null,
|
||||||
|
previousStatus,
|
||||||
|
newStatus,
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ received: true });
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error, providerEventId: event.providerEventId }, 'MP webhook processing failed');
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: 'unknown',
|
||||||
|
eventType: `error:${event.type}`,
|
||||||
|
provider: MP_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: { error: String(error) },
|
||||||
|
previousStatus: null,
|
||||||
|
newStatus: null,
|
||||||
|
}).catch((e) => logger.error({ error: e }, 'Failed to record error event'));
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { processMercadoPagoWebhook } from './mercadopago-webhook.business';
|
||||||
|
|
||||||
|
export async function mercadopagoWebhookHandler(c: AppContext) {
|
||||||
|
const body = await c.req.json();
|
||||||
|
const signature = c.req.header('x-signature');
|
||||||
|
const requestId = c.req.header('x-request-id');
|
||||||
|
|
||||||
|
return handleResult(
|
||||||
|
c,
|
||||||
|
await processMercadoPagoWebhook(body, signature ?? undefined, requestId ?? undefined),
|
||||||
|
200
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { logger } from '@/lib/logger';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import type { WebhookEvent } from '@/modules/billing/providers/billing-provider.interface';
|
||||||
|
import { stripeBillingProvider } from '@/modules/billing/providers/stripe.provider';
|
||||||
|
import {
|
||||||
|
findEventByProviderId,
|
||||||
|
recordBillingEvent,
|
||||||
|
updateBillingStatus,
|
||||||
|
} from '@/modules/billing/services/billing-repository.service';
|
||||||
|
import type { BillingStatusEnum } from '@/modules/billing/services/billing-repository.service';
|
||||||
|
|
||||||
|
const STRIPE_PROVIDER = 'STRIPE';
|
||||||
|
|
||||||
|
function mapWebhookTypeToStatus(event: WebhookEvent): BillingStatusEnum | null {
|
||||||
|
switch (event.type) {
|
||||||
|
case 'activated':
|
||||||
|
return 'ACTIVE';
|
||||||
|
case 'updated':
|
||||||
|
return 'ACTIVE';
|
||||||
|
case 'payment_failed':
|
||||||
|
return 'PAST_DUE';
|
||||||
|
case 'cancelled':
|
||||||
|
return 'CANCELED';
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getBillingBySubscription(providerSubscriptionId: string) {
|
||||||
|
return db.complexBilling.findFirst({
|
||||||
|
where: { providerSubscriptionId },
|
||||||
|
}) as Promise<{ complexId: string; status: BillingStatusEnum } | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processStripeWebhook(
|
||||||
|
rawBody: string,
|
||||||
|
signature: string | undefined
|
||||||
|
): Promise<Result<{ received: boolean }>> {
|
||||||
|
const parsedResult = await stripeBillingProvider.parseWebhook(rawBody, signature);
|
||||||
|
|
||||||
|
if (!parsedResult.ok) {
|
||||||
|
if (parsedResult.error.type === 'validation') {
|
||||||
|
return err(parsedResult.error);
|
||||||
|
}
|
||||||
|
logger.error({ error: parsedResult.error }, 'Stripe webhook parse failed');
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const event = parsedResult.value;
|
||||||
|
|
||||||
|
const existingResult = await findEventByProviderId(event.providerEventId);
|
||||||
|
if (!existingResult.ok) return err(existingResult.error);
|
||||||
|
if (existingResult.value) {
|
||||||
|
logger.info(
|
||||||
|
{ providerEventId: event.providerEventId },
|
||||||
|
'Stripe webhook: already processed, skipping'
|
||||||
|
);
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const newStatus = mapWebhookTypeToStatus(event);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const billing = await getBillingBySubscription(event.providerSubscriptionId);
|
||||||
|
|
||||||
|
if (!billing) {
|
||||||
|
logger.info(
|
||||||
|
{ providerSubscriptionId: event.providerSubscriptionId, eventType: event.type },
|
||||||
|
'Stripe webhook: no billing record found for subscription'
|
||||||
|
);
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: 'unknown',
|
||||||
|
eventType: `unlinked:${event.type}`,
|
||||||
|
provider: STRIPE_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: event.data ?? null,
|
||||||
|
previousStatus: null,
|
||||||
|
newStatus: null,
|
||||||
|
});
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousStatus = billing.status;
|
||||||
|
|
||||||
|
if (newStatus) {
|
||||||
|
await updateBillingStatus(billing.complexId, newStatus, {
|
||||||
|
provider: STRIPE_PROVIDER,
|
||||||
|
providerCustomerId: event.providerCustomerId,
|
||||||
|
providerSubscriptionId: event.providerSubscriptionId,
|
||||||
|
...(event.type === 'activated' || event.type === 'updated'
|
||||||
|
? {
|
||||||
|
currentPeriodStart: new Date(),
|
||||||
|
currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: billing.complexId,
|
||||||
|
eventType: event.type,
|
||||||
|
provider: STRIPE_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: event.data ?? null,
|
||||||
|
previousStatus,
|
||||||
|
newStatus,
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ received: true });
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
{ error, providerEventId: event.providerEventId },
|
||||||
|
'Stripe webhook processing failed'
|
||||||
|
);
|
||||||
|
await recordBillingEvent({
|
||||||
|
complexId: 'unknown',
|
||||||
|
eventType: `error:${event.type}`,
|
||||||
|
provider: STRIPE_PROVIDER,
|
||||||
|
providerEventId: event.providerEventId,
|
||||||
|
providerData: { error: String(error) },
|
||||||
|
previousStatus: null,
|
||||||
|
newStatus: null,
|
||||||
|
}).catch((e) => logger.error({ error: e }, 'Failed to record error event'));
|
||||||
|
return ok({ received: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { processStripeWebhook } from './stripe-webhook.business';
|
||||||
|
|
||||||
|
export async function stripeWebhookHandler(c: AppContext) {
|
||||||
|
const body = await c.req.raw.text();
|
||||||
|
const signature = c.req.header('stripe-signature');
|
||||||
|
|
||||||
|
return handleResult(c, await processStripeWebhook(body, signature ?? undefined), 200);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
|
||||||
|
export type WebhookEventType = 'activated' | 'updated' | 'cancelled' | 'payment_failed';
|
||||||
|
|
||||||
|
export type WebhookEvent = {
|
||||||
|
providerEventId: string;
|
||||||
|
type: WebhookEventType;
|
||||||
|
providerSubscriptionId: string;
|
||||||
|
providerCustomerId?: string;
|
||||||
|
data?: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CheckoutParams = {
|
||||||
|
planCode: string;
|
||||||
|
complexId: string;
|
||||||
|
customerEmail: string;
|
||||||
|
successUrl: string;
|
||||||
|
cancelUrl: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CheckoutResult = {
|
||||||
|
checkoutUrl: string;
|
||||||
|
providerSubscriptionId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface BillingProvider {
|
||||||
|
createCheckout(params: CheckoutParams): Promise<Result<CheckoutResult>>;
|
||||||
|
cancelSubscription(providerSubscriptionId: string): Promise<Result<void>>;
|
||||||
|
parseWebhook(
|
||||||
|
payload: unknown,
|
||||||
|
signature?: string,
|
||||||
|
requestId?: string
|
||||||
|
): Promise<Result<WebhookEvent>>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { logger } from '@/lib/logger';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import MercadoPagoConfig, { PreApproval } from 'mercadopago';
|
||||||
|
import { WebhookSignatureValidator } from 'mercadopago';
|
||||||
|
import type {
|
||||||
|
BillingProvider,
|
||||||
|
CheckoutParams,
|
||||||
|
CheckoutResult,
|
||||||
|
WebhookEvent,
|
||||||
|
} from './billing-provider.interface';
|
||||||
|
|
||||||
|
function getMpConfig(): MercadoPagoConfig {
|
||||||
|
const accessToken = Bun.env.MERCADOPAGO_ACCESS_TOKEN;
|
||||||
|
if (!accessToken) {
|
||||||
|
throw new Error('Missing MERCADOPAGO_ACCESS_TOKEN env var');
|
||||||
|
}
|
||||||
|
return new MercadoPagoConfig({ accessToken });
|
||||||
|
}
|
||||||
|
|
||||||
|
let _mpConfig: MercadoPagoConfig | null = null;
|
||||||
|
let _preApproval: PreApproval | null = null;
|
||||||
|
function preapproval(): PreApproval {
|
||||||
|
if (!_preApproval) {
|
||||||
|
_mpConfig = getMpConfig();
|
||||||
|
_preApproval = new PreApproval(_mpConfig);
|
||||||
|
}
|
||||||
|
return _preApproval;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMpPlanId(planCode: string, currency: string): string {
|
||||||
|
const key = `MERCADOPAGO_PLAN_ID_${currency}_${planCode}` as const;
|
||||||
|
const planId = Bun.env[key];
|
||||||
|
if (!planId) {
|
||||||
|
throw new Error(`Missing env var ${key} for Mercado Pago plan ID`);
|
||||||
|
}
|
||||||
|
return planId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSandbox(): boolean {
|
||||||
|
return Bun.env.BILLING_ENV !== 'production';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const mercadopagoBillingProvider: BillingProvider = {
|
||||||
|
async createCheckout(params: CheckoutParams): Promise<Result<CheckoutResult>> {
|
||||||
|
try {
|
||||||
|
const { planCode, complexId, customerEmail, successUrl } = params;
|
||||||
|
|
||||||
|
const currency = 'ARS';
|
||||||
|
const planId = getMpPlanId(planCode, currency);
|
||||||
|
|
||||||
|
const response = await preapproval().create({
|
||||||
|
body: {
|
||||||
|
preapproval_plan_id: planId,
|
||||||
|
reason: `Suscripción ${planCode} - Playzer`,
|
||||||
|
payer_email: customerEmail,
|
||||||
|
external_reference: complexId,
|
||||||
|
back_url: successUrl,
|
||||||
|
status: isSandbox() ? 'pending' : undefined,
|
||||||
|
auto_recurring: undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.id || !response.init_point) {
|
||||||
|
return err(Errors.unexpected('Mercado Pago did not return a preapproval ID or init_point'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
checkoutUrl: response.init_point,
|
||||||
|
providerSubscriptionId: response.id,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
{ error, params: { planCode: params.planCode } },
|
||||||
|
'MercadoPago createCheckout failed'
|
||||||
|
);
|
||||||
|
return err(Errors.unexpected('Failed to create Mercado Pago preapproval'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async cancelSubscription(providerSubscriptionId: string): Promise<Result<void>> {
|
||||||
|
try {
|
||||||
|
await preapproval().update({
|
||||||
|
id: providerSubscriptionId,
|
||||||
|
body: { status: 'cancelled' },
|
||||||
|
});
|
||||||
|
return ok(undefined);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error, providerSubscriptionId }, 'MercadoPago cancelSubscription failed');
|
||||||
|
return err(Errors.unexpected('Failed to cancel Mercado Pago preapproval'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async parseWebhook(
|
||||||
|
payload: unknown,
|
||||||
|
signature?: string,
|
||||||
|
requestId?: string
|
||||||
|
): Promise<Result<WebhookEvent>> {
|
||||||
|
try {
|
||||||
|
const body = payload as Record<string, unknown>;
|
||||||
|
|
||||||
|
const action = body?.action as string | undefined;
|
||||||
|
const dataId = (body?.data as Record<string, unknown>)?.id as string | undefined;
|
||||||
|
|
||||||
|
if (!action || !dataId) {
|
||||||
|
return err(
|
||||||
|
Errors.validation('Invalid Mercado Pago webhook payload: missing action or data.id')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (signature && requestId) {
|
||||||
|
const secret = Bun.env.MERCADOPAGO_WEBHOOK_SECRET;
|
||||||
|
if (secret) {
|
||||||
|
try {
|
||||||
|
WebhookSignatureValidator.validate({
|
||||||
|
xSignature: signature,
|
||||||
|
xRequestId: requestId,
|
||||||
|
dataId,
|
||||||
|
secret,
|
||||||
|
toleranceSeconds: 300,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return err(Errors.validation('Invalid Mercado Pago webhook signature'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let webhookType: WebhookEvent['type'];
|
||||||
|
|
||||||
|
switch (action) {
|
||||||
|
case 'subscription_authorized_payment':
|
||||||
|
webhookType = 'activated';
|
||||||
|
break;
|
||||||
|
case 'subscription_cancelled':
|
||||||
|
webhookType = 'cancelled';
|
||||||
|
break;
|
||||||
|
case 'subscription_updated':
|
||||||
|
webhookType = 'updated';
|
||||||
|
break;
|
||||||
|
case 'subscription_charge_payment':
|
||||||
|
webhookType = 'payment_failed';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
logger.info(
|
||||||
|
{ action },
|
||||||
|
'Mercado Pago webhook: unhandled action type, treating as updated'
|
||||||
|
);
|
||||||
|
webhookType = 'updated';
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
providerEventId: `mp-${dataId}-${action}`,
|
||||||
|
type: webhookType,
|
||||||
|
providerSubscriptionId: dataId,
|
||||||
|
providerCustomerId: undefined,
|
||||||
|
data: body as Record<string, unknown>,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error }, 'MercadoPago webhook parsing failed');
|
||||||
|
return err(Errors.validation('Invalid Mercado Pago webhook payload'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
165
apps/backend/src/modules/billing/providers/stripe.provider.ts
Normal file
165
apps/backend/src/modules/billing/providers/stripe.provider.ts
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { logger } from '@/lib/logger';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import Stripe from 'stripe';
|
||||||
|
import type {
|
||||||
|
BillingProvider,
|
||||||
|
CheckoutParams,
|
||||||
|
CheckoutResult,
|
||||||
|
WebhookEvent,
|
||||||
|
} from './billing-provider.interface';
|
||||||
|
|
||||||
|
function getStripeClient(): Stripe {
|
||||||
|
const secretKey = Bun.env.STRIPE_SECRET_KEY;
|
||||||
|
if (!secretKey) {
|
||||||
|
throw new Error('Missing STRIPE_SECRET_KEY env var');
|
||||||
|
}
|
||||||
|
return new Stripe(secretKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
let _stripeClient: Stripe | null = null;
|
||||||
|
function stripe(): Stripe {
|
||||||
|
if (!_stripeClient) {
|
||||||
|
_stripeClient = getStripeClient();
|
||||||
|
}
|
||||||
|
return _stripeClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStripePriceId(planCode: string, currency: string): string {
|
||||||
|
const key = `STRIPE_PRICE_ID_${currency}_${planCode}` as const;
|
||||||
|
const priceId = Bun.env[key];
|
||||||
|
if (!priceId) {
|
||||||
|
throw new Error(`Missing env var ${key} for Stripe price ID`);
|
||||||
|
}
|
||||||
|
return priceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const stripeBillingProvider: BillingProvider = {
|
||||||
|
async createCheckout(params: CheckoutParams): Promise<Result<CheckoutResult>> {
|
||||||
|
try {
|
||||||
|
const { planCode, complexId, customerEmail, successUrl, cancelUrl } = params;
|
||||||
|
|
||||||
|
const currency = 'USD';
|
||||||
|
|
||||||
|
const priceId = getStripePriceId(planCode, currency);
|
||||||
|
|
||||||
|
const session = await stripe().checkout.sessions.create({
|
||||||
|
mode: 'subscription',
|
||||||
|
customer_email: customerEmail,
|
||||||
|
line_items: [
|
||||||
|
{
|
||||||
|
price: priceId,
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
metadata: {
|
||||||
|
complexId,
|
||||||
|
planCode,
|
||||||
|
},
|
||||||
|
subscription_data: {
|
||||||
|
metadata: {
|
||||||
|
complexId,
|
||||||
|
planCode,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
success_url: successUrl,
|
||||||
|
cancel_url: cancelUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!session.url || !session.subscription) {
|
||||||
|
return err(Errors.unexpected('Stripe did not return a checkout URL or subscription ID'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const subscriptionId =
|
||||||
|
typeof session.subscription === 'string' ? session.subscription : session.subscription.id;
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
checkoutUrl: session.url,
|
||||||
|
providerSubscriptionId: subscriptionId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
{ error, params: { planCode: params.planCode } },
|
||||||
|
'Stripe createCheckout failed'
|
||||||
|
);
|
||||||
|
return err(Errors.unexpected('Failed to create Stripe checkout session'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async cancelSubscription(providerSubscriptionId: string): Promise<Result<void>> {
|
||||||
|
try {
|
||||||
|
await stripe().subscriptions.cancel(providerSubscriptionId);
|
||||||
|
return ok(undefined);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error, providerSubscriptionId }, 'Stripe cancelSubscription failed');
|
||||||
|
return err(Errors.unexpected('Failed to cancel Stripe subscription'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async parseWebhook(payload: unknown, signature?: string): Promise<Result<WebhookEvent>> {
|
||||||
|
if (!signature) {
|
||||||
|
return err(Errors.validation('Missing Stripe signature'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const secret = Bun.env.STRIPE_WEBHOOK_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
return err(Errors.unexpected('Missing STRIPE_WEBHOOK_SECRET env var'));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rawBody = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
||||||
|
const event = stripe().webhooks.constructEvent(rawBody, signature, secret);
|
||||||
|
|
||||||
|
const eventType = event.type;
|
||||||
|
const data = event.data.object as unknown as Record<string, unknown>;
|
||||||
|
|
||||||
|
let webhookType: WebhookEvent['type'];
|
||||||
|
let providerSubscriptionId: string | undefined;
|
||||||
|
let providerCustomerId: string | undefined;
|
||||||
|
|
||||||
|
if (eventType === 'checkout.session.completed') {
|
||||||
|
webhookType = 'activated';
|
||||||
|
providerSubscriptionId = data.subscription as string | undefined;
|
||||||
|
providerCustomerId = data.customer as string | undefined;
|
||||||
|
} else if (eventType === 'customer.subscription.updated') {
|
||||||
|
const status = data.status as string | undefined;
|
||||||
|
if (status === 'past_due') {
|
||||||
|
webhookType = 'payment_failed';
|
||||||
|
} else if (status === 'active' || status === 'trialing') {
|
||||||
|
webhookType = 'updated';
|
||||||
|
} else if (status === 'canceled' || status === 'unpaid') {
|
||||||
|
webhookType = 'cancelled';
|
||||||
|
} else {
|
||||||
|
webhookType = 'updated';
|
||||||
|
}
|
||||||
|
providerSubscriptionId = data.id as string | undefined;
|
||||||
|
providerCustomerId = data.customer as string | undefined;
|
||||||
|
} else if (eventType === 'customer.subscription.deleted') {
|
||||||
|
webhookType = 'cancelled';
|
||||||
|
providerSubscriptionId = data.id as string | undefined;
|
||||||
|
providerCustomerId = data.customer as string | undefined;
|
||||||
|
} else if (eventType === 'invoice.payment_failed') {
|
||||||
|
webhookType = 'payment_failed';
|
||||||
|
providerSubscriptionId = data.subscription as string | undefined;
|
||||||
|
providerCustomerId = data.customer as string | undefined;
|
||||||
|
} else {
|
||||||
|
logger.info({ eventType }, 'Stripe webhook: unhandled event type, skipping');
|
||||||
|
webhookType = 'updated';
|
||||||
|
providerSubscriptionId =
|
||||||
|
(data as { subscription?: string })?.subscription ?? `unknown-${event.id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
providerEventId: event.id,
|
||||||
|
type: webhookType,
|
||||||
|
providerSubscriptionId: providerSubscriptionId ?? `unknown-${event.id}`,
|
||||||
|
providerCustomerId,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error }, 'Stripe webhook parsing failed');
|
||||||
|
return err(Errors.validation('Invalid Stripe webhook signature or payload'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
|
||||||
|
export async function canUseApp(complexId: string): Promise<Result<true>> {
|
||||||
|
const billing = await db.complexBilling.findUnique({
|
||||||
|
where: { complexId },
|
||||||
|
select: { status: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!billing) {
|
||||||
|
return ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (billing.status === 'TRIAL' || billing.status === 'ACTIVE') {
|
||||||
|
return ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (billing.status === 'CANCELED') {
|
||||||
|
return err(
|
||||||
|
Errors.forbidden('Suscripción cancelada. Renueva tu plan para seguir usando la app.')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (billing.status === 'PAST_DUE') {
|
||||||
|
return err(
|
||||||
|
Errors.forbidden(
|
||||||
|
'Suscripción con pago pendiente. Regularizá tu deuda para seguir usando la app.'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (billing.status === 'SUSPENDED') {
|
||||||
|
return err(Errors.forbidden('Suscripción suspendida. Contactanos para reactivarla.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(true);
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
export type BillingProviderEnum = 'STRIPE' | 'MERCADOPAGO' | 'PAYPAL';
|
||||||
|
export type BillingStatusEnum = 'TRIAL' | 'ACTIVE' | 'PAST_DUE' | 'CANCELED' | 'SUSPENDED';
|
||||||
|
|
||||||
|
export type ComplexBillingRow = {
|
||||||
|
complexId: string;
|
||||||
|
status: BillingStatusEnum;
|
||||||
|
planCode: string;
|
||||||
|
currency: string;
|
||||||
|
provider: BillingProviderEnum | null;
|
||||||
|
providerCustomerId: string | null;
|
||||||
|
providerSubscriptionId: string | null;
|
||||||
|
providerPreapprovalId: string | null;
|
||||||
|
currentPeriodStart: Date | null;
|
||||||
|
currentPeriodEnd: Date | null;
|
||||||
|
trialEndsAt: Date | null;
|
||||||
|
canceledAt: Date | null;
|
||||||
|
suspendedAt: Date | null;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getBilling(complexId: string): Promise<Result<ComplexBillingRow>> {
|
||||||
|
const billing = await db.complexBilling.findUnique({
|
||||||
|
where: { complexId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!billing) {
|
||||||
|
return err(Errors.notFound('Billing record not found for this complex'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(billing as unknown as ComplexBillingRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureBilling(
|
||||||
|
complexId: string,
|
||||||
|
currency: string
|
||||||
|
): Promise<Result<ComplexBillingRow>> {
|
||||||
|
const existing = await db.complexBilling.findUnique({
|
||||||
|
where: { complexId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
return ok(existing as unknown as ComplexBillingRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = await db.complexBilling.create({
|
||||||
|
data: {
|
||||||
|
complexId,
|
||||||
|
status: 'TRIAL',
|
||||||
|
planCode: 'BASIC',
|
||||||
|
currency,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok(created as unknown as ComplexBillingRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateBillingStatus(
|
||||||
|
complexId: string,
|
||||||
|
status: BillingStatusEnum,
|
||||||
|
extra?: {
|
||||||
|
provider?: BillingProviderEnum;
|
||||||
|
providerCustomerId?: string;
|
||||||
|
providerSubscriptionId?: string;
|
||||||
|
providerPreapprovalId?: string;
|
||||||
|
currentPeriodStart?: Date;
|
||||||
|
currentPeriodEnd?: Date;
|
||||||
|
}
|
||||||
|
): Promise<Result<ComplexBillingRow>> {
|
||||||
|
try {
|
||||||
|
const data: Record<string, unknown> = { status };
|
||||||
|
|
||||||
|
if (extra?.provider) data.provider = extra.provider;
|
||||||
|
if (extra?.providerCustomerId) data.providerCustomerId = extra.providerCustomerId;
|
||||||
|
if (extra?.providerSubscriptionId) data.providerSubscriptionId = extra.providerSubscriptionId;
|
||||||
|
if (extra?.providerPreapprovalId) data.providerPreapprovalId = extra.providerPreapprovalId;
|
||||||
|
if (extra?.currentPeriodStart) data.currentPeriodStart = extra.currentPeriodStart;
|
||||||
|
if (extra?.currentPeriodEnd) data.currentPeriodEnd = extra.currentPeriodEnd;
|
||||||
|
|
||||||
|
const updated = await db.complexBilling.update({
|
||||||
|
where: { complexId },
|
||||||
|
data: data as never,
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok(updated as unknown as ComplexBillingRow);
|
||||||
|
} catch {
|
||||||
|
return err(Errors.unexpected('Failed to update billing status'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function recordBillingEvent(params: {
|
||||||
|
complexId: string;
|
||||||
|
eventType: string;
|
||||||
|
provider: BillingProviderEnum;
|
||||||
|
providerEventId: string | null;
|
||||||
|
providerData: unknown;
|
||||||
|
previousStatus: BillingStatusEnum | null;
|
||||||
|
newStatus: BillingStatusEnum | null;
|
||||||
|
}): Promise<Result<{ id: string }>> {
|
||||||
|
try {
|
||||||
|
const event = await db.billingEvent.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
complexId: params.complexId,
|
||||||
|
eventType: params.eventType,
|
||||||
|
provider: params.provider,
|
||||||
|
providerEventId: params.providerEventId,
|
||||||
|
providerData: params.providerData as never,
|
||||||
|
previousStatus: params.previousStatus,
|
||||||
|
newStatus: params.newStatus,
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ id: event.id });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const prismaError = error as { code?: string };
|
||||||
|
if (prismaError.code === 'P2002') {
|
||||||
|
return err(Errors.conflict('Webhook event already processed (idempotency)'));
|
||||||
|
}
|
||||||
|
return err(Errors.unexpected('Failed to record billing event'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findEventByProviderId(
|
||||||
|
providerEventId: string
|
||||||
|
): Promise<Result<{ id: string } | null>> {
|
||||||
|
const event = await db.billingEvent.findUnique({
|
||||||
|
where: { providerEventId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok(event ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function hasActiveSubscription(complexId: string): Promise<Result<boolean>> {
|
||||||
|
const billing = await db.complexBilling.findUnique({
|
||||||
|
where: { complexId },
|
||||||
|
select: { status: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!billing) return ok(false);
|
||||||
|
|
||||||
|
return ok(billing.status === 'ACTIVE' || billing.status === 'TRIAL');
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import type { Result } from '@/lib/result';
|
||||||
|
import { err, ok } from '@/lib/result';
|
||||||
|
import type { BillingProvider } from '@/modules/billing/providers/billing-provider.interface';
|
||||||
|
import { mercadopagoBillingProvider } from '@/modules/billing/providers/mercadopago.provider';
|
||||||
|
import { stripeBillingProvider } from '@/modules/billing/providers/stripe.provider';
|
||||||
|
|
||||||
|
export const STRIPE = stripeBillingProvider;
|
||||||
|
export const MERCADOPAGO = mercadopagoBillingProvider;
|
||||||
|
|
||||||
|
export function resolveProviderByCountry(country: string | null): BillingProvider {
|
||||||
|
if (country === 'AR' || country?.toLowerCase() === 'argentina') {
|
||||||
|
return MERCADOPAGO;
|
||||||
|
}
|
||||||
|
return STRIPE;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getProviderForComplex(
|
||||||
|
complexId: string
|
||||||
|
): Promise<Result<{ provider: BillingProvider; country: string | null }>> {
|
||||||
|
const complex = await db.complex.findUnique({
|
||||||
|
where: { id: complexId },
|
||||||
|
select: { country: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!complex) {
|
||||||
|
return err(Errors.notFound('Complex not found'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const provider = resolveProviderByCountry(complex.country);
|
||||||
|
return ok({ provider, country: complex.country });
|
||||||
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||||
import { acceptComplexInvitationsHandler } from '@/modules/complex/handlers/accept-complex-invitations.handler';
|
import { acceptComplexInvitationsHandler } from '@/modules/complex/features/accept-complex-invitations/accept-complex-invitations.handler';
|
||||||
import { cancelComplexInvitationHandler } from '@/modules/complex/handlers/cancel-complex-invitation.handler';
|
import { cancelComplexInvitationHandler } from '@/modules/complex/features/cancel-complex-invitation/cancel-complex-invitation.handler';
|
||||||
import { createComplexHandler } from '@/modules/complex/handlers/create-complex.handler';
|
import { createComplexHandler } from '@/modules/complex/features/create-complex/create-complex.handler';
|
||||||
import { getComplexByIdHandler } from '@/modules/complex/handlers/get-complex-by-id.handler';
|
import { getComplexByIdHandler } from '@/modules/complex/features/get-complex-by-id/get-complex-by-id.handler';
|
||||||
import { getComplexBySlugHandler } from '@/modules/complex/handlers/get-complex-by-slug.handler';
|
import { getComplexBySlugHandler } from '@/modules/complex/features/get-complex-by-slug/get-complex-by-slug.handler';
|
||||||
import { getCurrentComplexHandler } from '@/modules/complex/handlers/get-current-complex.handler';
|
import { getCurrentComplexHandler } from '@/modules/complex/features/get-current-complex/get-current-complex.handler';
|
||||||
import { inviteComplexUserHandler } from '@/modules/complex/handlers/invite-complex-user.handler';
|
import { inviteComplexUserHandler } from '@/modules/complex/features/invite-complex-user/invite-complex-user.handler';
|
||||||
import { listComplexUsersHandler } from '@/modules/complex/handlers/list-complex-users.handler';
|
import { listComplexUsersHandler } from '@/modules/complex/features/list-complex-users/list-complex-users.handler';
|
||||||
import { listMyComplexesHandler } from '@/modules/complex/handlers/list-my-complexes.handler';
|
import { listMyComplexesHandler } from '@/modules/complex/features/list-my-complexes/list-my-complexes.handler';
|
||||||
import { resendComplexInvitationHandler } from '@/modules/complex/handlers/resend-complex-invitation.handler';
|
import { resendComplexInvitationHandler } from '@/modules/complex/features/resend-complex-invitation/resend-complex-invitation.handler';
|
||||||
import { revokeComplexUserHandler } from '@/modules/complex/handlers/revoke-complex-user.handler';
|
import { revokeComplexUserHandler } from '@/modules/complex/features/revoke-complex-user/revoke-complex-user.handler';
|
||||||
import { selectComplexHandler } from '@/modules/complex/handlers/select-complex.handler';
|
import { selectComplexHandler } from '@/modules/complex/features/select-complex/select-complex.handler';
|
||||||
import { updateComplexHandler } from '@/modules/complex/handlers/update-complex.handler';
|
import { updateComplexHandler } from '@/modules/complex/features/update-complex/update-complex.handler';
|
||||||
import type { AppEnv } from '@/types/hono';
|
import type { AppEnv } from '@/types/hono';
|
||||||
import { zValidator } from '@hono/zod-validator';
|
import { zValidator } from '@hono/zod-validator';
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import type {
|
||||||
|
AcceptComplexInvitationsInput,
|
||||||
|
AcceptComplexInvitationsResponse,
|
||||||
|
} from '@repo/api-contract';
|
||||||
|
import { hashToken, normalizeEmail } from '../../shared/members-helpers';
|
||||||
|
|
||||||
|
export async function acceptComplexInvitations(
|
||||||
|
userId: string,
|
||||||
|
email: string,
|
||||||
|
input: AcceptComplexInvitationsInput = {}
|
||||||
|
): Promise<Result<AcceptComplexInvitationsResponse>> {
|
||||||
|
const normalizedEmail = normalizeEmail(email);
|
||||||
|
const tokenHash = input.inviteToken ? hashToken(input.inviteToken) : null;
|
||||||
|
|
||||||
|
const invitations = await db.complexInvitation.findMany({
|
||||||
|
where: {
|
||||||
|
email: normalizedEmail,
|
||||||
|
acceptedAt: null,
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: { gte: new Date() },
|
||||||
|
...(tokenHash ? { tokenHash } : {}),
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (tokenHash && invitations.length === 0) {
|
||||||
|
return err(Errors.notFound('La invitación es inválida o ya venció.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
let acceptedCount = 0;
|
||||||
|
|
||||||
|
for (const invitation of invitations) {
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
const existingMembership = await tx.complexUser.findUnique({
|
||||||
|
where: {
|
||||||
|
complexId_userId: {
|
||||||
|
complexId: invitation.complexId,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
select: { userId: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existingMembership) {
|
||||||
|
await tx.complexUser.create({
|
||||||
|
data: {
|
||||||
|
complexId: invitation.complexId,
|
||||||
|
userId,
|
||||||
|
role: 'EMPLOYEE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.complexInvitation.update({
|
||||||
|
where: { id: invitation.id },
|
||||||
|
data: { acceptedAt: new Date() },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
acceptedCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({ acceptedCount });
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import type { AcceptComplexInvitationsInput } from '@repo/api-contract';
|
||||||
|
import { acceptComplexInvitations } from './accept-complex-invitations.business';
|
||||||
|
|
||||||
|
export async function acceptComplexInvitationsHandler(c: AppContext) {
|
||||||
|
const user = c.get('user');
|
||||||
|
const payload = c.req.valid('json' as never) as AcceptComplexInvitationsInput;
|
||||||
|
|
||||||
|
return handleResult(c, await acceptComplexInvitations(user.id, user.email, payload));
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Errors } from '@/lib/errors';
|
||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { type Result, err, ok } from '@/lib/result';
|
||||||
|
import type { CancelComplexInvitationResponse } from '@repo/api-contract';
|
||||||
|
import { ensureComplexAdmin } from '../../shared/members-helpers';
|
||||||
|
|
||||||
|
export async function cancelComplexInvitation(
|
||||||
|
userId: string,
|
||||||
|
complexId: string,
|
||||||
|
invitationId: string
|
||||||
|
): Promise<Result<CancelComplexInvitationResponse>> {
|
||||||
|
const adminResult = await ensureComplexAdmin(userId, complexId);
|
||||||
|
if (!adminResult.ok) return adminResult;
|
||||||
|
|
||||||
|
const invitation = await db.complexInvitation.findUnique({
|
||||||
|
where: { id: invitationId },
|
||||||
|
select: { complexId: true, acceptedAt: true, revokedAt: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!invitation || invitation.complexId !== complexId) {
|
||||||
|
return err(Errors.notFound('La invitación no existe.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitation.acceptedAt) {
|
||||||
|
return err(Errors.conflict('La invitación ya fue aceptada.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitation.revokedAt) {
|
||||||
|
return ok({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.complexInvitation.update({
|
||||||
|
where: { id: invitationId },
|
||||||
|
data: { revokedAt: new Date() },
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { handleResult } from '@/lib/http/handle-result';
|
||||||
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { cancelComplexInvitation } from './cancel-complex-invitation.business';
|
||||||
|
|
||||||
|
const cancelInvitationParamsSchema = z.object({ id: z.uuid(), invitationId: z.uuid() });
|
||||||
|
|
||||||
|
export async function cancelComplexInvitationHandler(c: AppContext) {
|
||||||
|
const user = c.get('user');
|
||||||
|
const params = cancelInvitationParamsSchema.parse(c.req.param());
|
||||||
|
|
||||||
|
return handleResult(c, await cancelComplexInvitation(user.id, params.id, params.invitationId));
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { buildUniqueSlug, slugify } from '@/lib/slug';
|
||||||
|
import type { CreateComplexInput } from '@repo/api-contract';
|
||||||
|
import { v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
type DayOfWeek = 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY';
|
||||||
|
|
||||||
|
type CreateComplexInternalInput = CreateComplexInput & {
|
||||||
|
adminEmail: string;
|
||||||
|
userId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function toMinutes(value: string): number {
|
||||||
|
const [hours, minutes] = value.split(':').map((part) => Number(part));
|
||||||
|
return hours * 60 + minutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertAvailabilityRanges(
|
||||||
|
availability: Array<{
|
||||||
|
dayOfWeek: DayOfWeek;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
}>
|
||||||
|
) {
|
||||||
|
for (const range of availability) {
|
||||||
|
const start = toMinutes(range.startTime);
|
||||||
|
const end = toMinutes(range.endTime);
|
||||||
|
if (start >= end) {
|
||||||
|
throw new Error(`El rango ${range.startTime}-${range.endTime} es inválido.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createComplex(input: CreateComplexInternalInput) {
|
||||||
|
return db.$transaction(async (tx) => {
|
||||||
|
const base = slugify(input.complexName);
|
||||||
|
const fallback = base.length > 0 ? base : `complex-${uuidv7().slice(0, 8)}`;
|
||||||
|
const complexSlug = await buildUniqueSlug(fallback, (slug) =>
|
||||||
|
tx.complex.findFirst({ where: { complexSlug: slug }, select: { id: true } })
|
||||||
|
);
|
||||||
|
|
||||||
|
const complex = await tx.complex.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
complexName: input.complexName,
|
||||||
|
physicalAddress: input.physicalAddress.trim(),
|
||||||
|
city: input.city?.trim() || null,
|
||||||
|
state: input.state?.trim() || null,
|
||||||
|
country: input.country?.trim() || null,
|
||||||
|
complexSlug,
|
||||||
|
adminEmail: input.adminEmail,
|
||||||
|
planCode: input.planCode,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.userId) {
|
||||||
|
await tx.complexUser.create({
|
||||||
|
data: {
|
||||||
|
complexId: complex.id,
|
||||||
|
userId: input.userId,
|
||||||
|
role: 'ADMIN',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.setupCourts && input.courtSportId) {
|
||||||
|
const sport = await tx.sport.findFirst({
|
||||||
|
where: { id: input.courtSportId, isActive: true },
|
||||||
|
select: { name: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sport) {
|
||||||
|
throw new Error('El deporte seleccionado no existe o esta inactivo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const availability = (input.courtDaysOfWeek ?? []).map((day) => ({
|
||||||
|
dayOfWeek: day as DayOfWeek,
|
||||||
|
startTime: input.courtStartTime ?? '08:00',
|
||||||
|
endTime: input.courtEndTime ?? '22:00',
|
||||||
|
}));
|
||||||
|
|
||||||
|
assertAvailabilityRanges(availability);
|
||||||
|
|
||||||
|
const court = await tx.court.create({
|
||||||
|
data: {
|
||||||
|
id: uuidv7(),
|
||||||
|
complexId: complex.id,
|
||||||
|
sportId: input.courtSportId,
|
||||||
|
name: `${sport.name} 1`,
|
||||||
|
slotDurationMinutes: 60,
|
||||||
|
basePrice: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await tx.courtAvailability.createMany({
|
||||||
|
data: availability.map((avail) => ({
|
||||||
|
id: uuidv7(),
|
||||||
|
courtId: court.id,
|
||||||
|
dayOfWeek: avail.dayOfWeek,
|
||||||
|
startTime: avail.startTime,
|
||||||
|
endTime: avail.endTime,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return complex;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { db } from '@/lib/prisma';
|
import { db } from '@/lib/prisma';
|
||||||
import { createComplex } from '@/modules/complex/services/complex.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import type { CreateComplexInput } from '@repo/api-contract';
|
import type { CreateComplexInput } from '@repo/api-contract';
|
||||||
|
import { createComplex } from './create-complex.business';
|
||||||
|
|
||||||
export async function createComplexHandler(c: AppContext) {
|
export async function createComplexHandler(c: AppContext) {
|
||||||
const payload = c.req.valid('json' as never) as CreateComplexInput;
|
const payload = c.req.valid('json' as never) as CreateComplexInput;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function getComplexById(id: string) {
|
||||||
|
return db.complex.findUnique({ where: { id } });
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getComplexById } from '@/modules/complex/services/complex.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getComplexById } from './get-complex-by-id.business';
|
||||||
|
|
||||||
type ComplexIdParams = { id: string };
|
type ComplexIdParams = { id: string };
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function getComplexBySlug(slug: string) {
|
||||||
|
return db.complex.findUnique({ where: { complexSlug: slug } });
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getComplexBySlug } from '@/modules/complex/services/complex.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
|
import { getComplexBySlug } from './get-complex-by-slug.business';
|
||||||
|
|
||||||
type ComplexSlugParams = { slug: string };
|
type ComplexSlugParams = { slug: string };
|
||||||
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { db } from '@/lib/prisma';
|
||||||
|
import { parsePlanRules } from '@/modules/plan/services/plan-rules.service';
|
||||||
|
|
||||||
|
export async function getCurrentComplex(userId: string, complexId: string) {
|
||||||
|
const complexUser = await db.complexUser.findUnique({
|
||||||
|
where: {
|
||||||
|
complexId_userId: {
|
||||||
|
complexId,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
complex: {
|
||||||
|
include: {
|
||||||
|
plan: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!complexUser) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...complexUser.complex,
|
||||||
|
role: complexUser.role,
|
||||||
|
planFeatures: complexUser.complex.plan
|
||||||
|
? parsePlanRules(complexUser.complex.plan.rules).features
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function selectComplex(userId: string, complexId: string) {
|
||||||
|
return getCurrentComplex(userId, complexId);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { getCurrentComplex } from '@/modules/complex/services/complex.service';
|
|
||||||
import type { AppContext } from '@/types/hono';
|
import type { AppContext } from '@/types/hono';
|
||||||
import { getCookie } from 'hono/cookie';
|
import { getCookie } from 'hono/cookie';
|
||||||
|
import { getCurrentComplex } from './get-current-complex.business';
|
||||||
|
|
||||||
const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
|
const SELECTED_COMPLEX_COOKIE = 'selected-complex-id';
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user