feat: add complex user invitation and management features
- Implemented complex member and invitation schemas using Zod for validation. - Created new API endpoints for inviting, accepting, revoking, and canceling complex user invitations. - Developed handlers for managing complex users, including listing, inviting, revoking, and canceling invitations. - Added frontend components for displaying and managing complex users and invitations. - Introduced session storage management for pending invitations. - Integrated Gravatar for user avatars based on email. - Created database migration for complex invitations table.
This commit is contained in:
@@ -12,6 +12,7 @@ model Complex {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
plan Plan? @relation(fields: [planCode], references: [code])
|
||||
users ComplexUser[]
|
||||
invitations ComplexInvitation[]
|
||||
courts Court[]
|
||||
|
||||
@@index([planCode])
|
||||
@@ -36,3 +37,20 @@ model ComplexUser {
|
||||
@@index([userId])
|
||||
@@map("complex_users")
|
||||
}
|
||||
|
||||
model ComplexInvitation {
|
||||
id String @id @db.Uuid
|
||||
complexId String @map("complex_id") @db.Uuid
|
||||
email String @db.VarChar(255)
|
||||
tokenHash String @unique @map("token_hash")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
acceptedAt DateTime? @map("accepted_at")
|
||||
revokedAt DateTime? @map("revoked_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
complex Complex @relation(fields: [complexId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([complexId, email])
|
||||
@@index([email])
|
||||
@@map("complex_invitations")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "complex_invitations" (
|
||||
"id" UUID NOT NULL,
|
||||
"complex_id" UUID NOT NULL,
|
||||
"email" VARCHAR(255) NOT NULL,
|
||||
"token_hash" TEXT NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"accepted_at" TIMESTAMP(3),
|
||||
"revoked_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "complex_invitations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "complex_invitations_token_hash_key" ON "complex_invitations"("token_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "complex_invitations_complex_id_email_idx" ON "complex_invitations"("complex_id", "email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "complex_invitations_email_idx" ON "complex_invitations"("email");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "complex_invitations" ADD CONSTRAINT "complex_invitations_complex_id_fkey" FOREIGN KEY ("complex_id") REFERENCES "complexes"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -47,6 +47,11 @@ export type Complex = Prisma.ComplexModel
|
||||
*
|
||||
*/
|
||||
export type ComplexUser = Prisma.ComplexUserModel
|
||||
/**
|
||||
* Model ComplexInvitation
|
||||
*
|
||||
*/
|
||||
export type ComplexInvitation = Prisma.ComplexInvitationModel
|
||||
/**
|
||||
* Model Sport
|
||||
*
|
||||
|
||||
@@ -71,6 +71,11 @@ export type Complex = Prisma.ComplexModel
|
||||
*
|
||||
*/
|
||||
export type ComplexUser = Prisma.ComplexUserModel
|
||||
/**
|
||||
* Model ComplexInvitation
|
||||
*
|
||||
*/
|
||||
export type ComplexInvitation = Prisma.ComplexInvitationModel
|
||||
/**
|
||||
* Model Sport
|
||||
*
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -390,6 +390,7 @@ export const ModelName = {
|
||||
Verification: 'Verification',
|
||||
Complex: 'Complex',
|
||||
ComplexUser: 'ComplexUser',
|
||||
ComplexInvitation: 'ComplexInvitation',
|
||||
Sport: 'Sport',
|
||||
Court: 'Court',
|
||||
CourtAvailability: 'CourtAvailability',
|
||||
@@ -413,7 +414,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "onboardingRequest" | "passwordResetRequest" | "plan"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "complex" | "complexUser" | "complexInvitation" | "sport" | "court" | "courtAvailability" | "courtPriceRule" | "courtBooking" | "onboardingRequest" | "passwordResetRequest" | "plan"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -861,6 +862,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
ComplexInvitation: {
|
||||
payload: Prisma.$ComplexInvitationPayload<ExtArgs>
|
||||
fields: Prisma.ComplexInvitationFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.ComplexInvitationFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.ComplexInvitationFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.ComplexInvitationFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.ComplexInvitationFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.ComplexInvitationFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.ComplexInvitationCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.ComplexInvitationCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.ComplexInvitationCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.ComplexInvitationDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.ComplexInvitationUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.ComplexInvitationDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.ComplexInvitationUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.ComplexInvitationUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.ComplexInvitationUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$ComplexInvitationPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.ComplexInvitationAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateComplexInvitation>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.ComplexInvitationGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.ComplexInvitationGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.ComplexInvitationCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.ComplexInvitationCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
Sport: {
|
||||
payload: Prisma.$SportPayload<ExtArgs>
|
||||
fields: Prisma.SportFieldRefs
|
||||
@@ -1578,6 +1653,21 @@ export const ComplexUserScalarFieldEnum = {
|
||||
export type ComplexUserScalarFieldEnum = (typeof ComplexUserScalarFieldEnum)[keyof typeof ComplexUserScalarFieldEnum]
|
||||
|
||||
|
||||
export const ComplexInvitationScalarFieldEnum = {
|
||||
id: 'id',
|
||||
complexId: 'complexId',
|
||||
email: 'email',
|
||||
tokenHash: 'tokenHash',
|
||||
expiresAt: 'expiresAt',
|
||||
acceptedAt: 'acceptedAt',
|
||||
revokedAt: 'revokedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type ComplexInvitationScalarFieldEnum = (typeof ComplexInvitationScalarFieldEnum)[keyof typeof ComplexInvitationScalarFieldEnum]
|
||||
|
||||
|
||||
export const SportScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
@@ -1972,6 +2062,7 @@ export type GlobalOmitConfig = {
|
||||
verification?: Prisma.VerificationOmit
|
||||
complex?: Prisma.ComplexOmit
|
||||
complexUser?: Prisma.ComplexUserOmit
|
||||
complexInvitation?: Prisma.ComplexInvitationOmit
|
||||
sport?: Prisma.SportOmit
|
||||
court?: Prisma.CourtOmit
|
||||
courtAvailability?: Prisma.CourtAvailabilityOmit
|
||||
|
||||
@@ -57,6 +57,7 @@ export const ModelName = {
|
||||
Verification: 'Verification',
|
||||
Complex: 'Complex',
|
||||
ComplexUser: 'ComplexUser',
|
||||
ComplexInvitation: 'ComplexInvitation',
|
||||
Sport: 'Sport',
|
||||
Court: 'Court',
|
||||
CourtAvailability: 'CourtAvailability',
|
||||
@@ -169,6 +170,21 @@ export const ComplexUserScalarFieldEnum = {
|
||||
export type ComplexUserScalarFieldEnum = (typeof ComplexUserScalarFieldEnum)[keyof typeof ComplexUserScalarFieldEnum]
|
||||
|
||||
|
||||
export const ComplexInvitationScalarFieldEnum = {
|
||||
id: 'id',
|
||||
complexId: 'complexId',
|
||||
email: 'email',
|
||||
tokenHash: 'tokenHash',
|
||||
expiresAt: 'expiresAt',
|
||||
acceptedAt: 'acceptedAt',
|
||||
revokedAt: 'revokedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type ComplexInvitationScalarFieldEnum = (typeof ComplexInvitationScalarFieldEnum)[keyof typeof ComplexInvitationScalarFieldEnum]
|
||||
|
||||
|
||||
export const SportScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
|
||||
@@ -14,6 +14,7 @@ export type * from './models/Account'
|
||||
export type * from './models/Verification'
|
||||
export type * from './models/Complex'
|
||||
export type * from './models/ComplexUser'
|
||||
export type * from './models/ComplexInvitation'
|
||||
export type * from './models/Sport'
|
||||
export type * from './models/Court'
|
||||
export type * from './models/CourtAvailability'
|
||||
|
||||
@@ -232,6 +232,7 @@ export type ComplexWhereInput = {
|
||||
updatedAt?: Prisma.DateTimeFilter<"Complex"> | Date | string
|
||||
plan?: Prisma.XOR<Prisma.PlanNullableScalarRelationFilter, Prisma.PlanWhereInput> | null
|
||||
users?: Prisma.ComplexUserListRelationFilter
|
||||
invitations?: Prisma.ComplexInvitationListRelationFilter
|
||||
courts?: Prisma.CourtListRelationFilter
|
||||
}
|
||||
|
||||
@@ -249,6 +250,7 @@ export type ComplexOrderByWithRelationInput = {
|
||||
updatedAt?: Prisma.SortOrder
|
||||
plan?: Prisma.PlanOrderByWithRelationInput
|
||||
users?: Prisma.ComplexUserOrderByRelationAggregateInput
|
||||
invitations?: Prisma.ComplexInvitationOrderByRelationAggregateInput
|
||||
courts?: Prisma.CourtOrderByRelationAggregateInput
|
||||
}
|
||||
|
||||
@@ -269,6 +271,7 @@ export type ComplexWhereUniqueInput = Prisma.AtLeast<{
|
||||
updatedAt?: Prisma.DateTimeFilter<"Complex"> | Date | string
|
||||
plan?: Prisma.XOR<Prisma.PlanNullableScalarRelationFilter, Prisma.PlanWhereInput> | null
|
||||
users?: Prisma.ComplexUserListRelationFilter
|
||||
invitations?: Prisma.ComplexInvitationListRelationFilter
|
||||
courts?: Prisma.CourtListRelationFilter
|
||||
}, "id" | "complexSlug">
|
||||
|
||||
@@ -319,6 +322,7 @@ export type ComplexCreateInput = {
|
||||
updatedAt?: Date | string
|
||||
plan?: Prisma.PlanCreateNestedOneWithoutComplexesInput
|
||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -335,6 +339,7 @@ export type ComplexUncheckedCreateInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -351,6 +356,7 @@ export type ComplexUpdateInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
plan?: Prisma.PlanUpdateOneWithoutComplexesNestedInput
|
||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -367,6 +373,7 @@ export type ComplexUncheckedUpdateInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -482,6 +489,20 @@ export type ComplexUpdateOneRequiredWithoutUsersNestedInput = {
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.ComplexUpdateToOneWithWhereWithoutUsersInput, Prisma.ComplexUpdateWithoutUsersInput>, Prisma.ComplexUncheckedUpdateWithoutUsersInput>
|
||||
}
|
||||
|
||||
export type ComplexCreateNestedOneWithoutInvitationsInput = {
|
||||
create?: Prisma.XOR<Prisma.ComplexCreateWithoutInvitationsInput, Prisma.ComplexUncheckedCreateWithoutInvitationsInput>
|
||||
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutInvitationsInput
|
||||
connect?: Prisma.ComplexWhereUniqueInput
|
||||
}
|
||||
|
||||
export type ComplexUpdateOneRequiredWithoutInvitationsNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.ComplexCreateWithoutInvitationsInput, Prisma.ComplexUncheckedCreateWithoutInvitationsInput>
|
||||
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutInvitationsInput
|
||||
upsert?: Prisma.ComplexUpsertWithoutInvitationsInput
|
||||
connect?: Prisma.ComplexWhereUniqueInput
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.ComplexUpdateToOneWithWhereWithoutInvitationsInput, Prisma.ComplexUpdateWithoutInvitationsInput>, Prisma.ComplexUncheckedUpdateWithoutInvitationsInput>
|
||||
}
|
||||
|
||||
export type ComplexCreateNestedOneWithoutCourtsInput = {
|
||||
create?: Prisma.XOR<Prisma.ComplexCreateWithoutCourtsInput, Prisma.ComplexUncheckedCreateWithoutCourtsInput>
|
||||
connectOrCreate?: Prisma.ComplexCreateOrConnectWithoutCourtsInput
|
||||
@@ -550,6 +571,7 @@ export type ComplexCreateWithoutUsersInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
plan?: Prisma.PlanCreateNestedOneWithoutComplexesInput
|
||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -565,6 +587,7 @@ export type ComplexUncheckedCreateWithoutUsersInput = {
|
||||
planCode?: string | null
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -596,6 +619,7 @@ export type ComplexUpdateWithoutUsersInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
plan?: Prisma.PlanUpdateOneWithoutComplexesNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -611,6 +635,87 @@ export type ComplexUncheckedUpdateWithoutUsersInput = {
|
||||
planCode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
export type ComplexCreateWithoutInvitationsInput = {
|
||||
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
|
||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
export type ComplexUncheckedCreateWithoutInvitationsInput = {
|
||||
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
|
||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
export type ComplexCreateOrConnectWithoutInvitationsInput = {
|
||||
where: Prisma.ComplexWhereUniqueInput
|
||||
create: Prisma.XOR<Prisma.ComplexCreateWithoutInvitationsInput, Prisma.ComplexUncheckedCreateWithoutInvitationsInput>
|
||||
}
|
||||
|
||||
export type ComplexUpsertWithoutInvitationsInput = {
|
||||
update: Prisma.XOR<Prisma.ComplexUpdateWithoutInvitationsInput, Prisma.ComplexUncheckedUpdateWithoutInvitationsInput>
|
||||
create: Prisma.XOR<Prisma.ComplexCreateWithoutInvitationsInput, Prisma.ComplexUncheckedCreateWithoutInvitationsInput>
|
||||
where?: Prisma.ComplexWhereInput
|
||||
}
|
||||
|
||||
export type ComplexUpdateToOneWithWhereWithoutInvitationsInput = {
|
||||
where?: Prisma.ComplexWhereInput
|
||||
data: Prisma.XOR<Prisma.ComplexUpdateWithoutInvitationsInput, Prisma.ComplexUncheckedUpdateWithoutInvitationsInput>
|
||||
}
|
||||
|
||||
export type ComplexUpdateWithoutInvitationsInput = {
|
||||
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
|
||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
export type ComplexUncheckedUpdateWithoutInvitationsInput = {
|
||||
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
|
||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -627,6 +732,7 @@ export type ComplexCreateWithoutCourtsInput = {
|
||||
updatedAt?: Date | string
|
||||
plan?: Prisma.PlanCreateNestedOneWithoutComplexesInput
|
||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
export type ComplexUncheckedCreateWithoutCourtsInput = {
|
||||
@@ -642,6 +748,7 @@ export type ComplexUncheckedCreateWithoutCourtsInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
export type ComplexCreateOrConnectWithoutCourtsInput = {
|
||||
@@ -673,6 +780,7 @@ export type ComplexUpdateWithoutCourtsInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
plan?: Prisma.PlanUpdateOneWithoutComplexesNestedInput
|
||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
export type ComplexUncheckedUpdateWithoutCourtsInput = {
|
||||
@@ -688,6 +796,7 @@ export type ComplexUncheckedUpdateWithoutCourtsInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
export type ComplexCreateWithoutPlanInput = {
|
||||
@@ -702,6 +811,7 @@ export type ComplexCreateWithoutPlanInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
users?: Prisma.ComplexUserCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -717,6 +827,7 @@ export type ComplexUncheckedCreateWithoutPlanInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
users?: Prisma.ComplexUserUncheckedCreateNestedManyWithoutComplexInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedCreateNestedManyWithoutComplexInput
|
||||
courts?: Prisma.CourtUncheckedCreateNestedManyWithoutComplexInput
|
||||
}
|
||||
|
||||
@@ -788,6 +899,7 @@ export type ComplexUpdateWithoutPlanInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
users?: Prisma.ComplexUserUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -803,6 +915,7 @@ export type ComplexUncheckedUpdateWithoutPlanInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
users?: Prisma.ComplexUserUncheckedUpdateManyWithoutComplexNestedInput
|
||||
invitations?: Prisma.ComplexInvitationUncheckedUpdateManyWithoutComplexNestedInput
|
||||
courts?: Prisma.CourtUncheckedUpdateManyWithoutComplexNestedInput
|
||||
}
|
||||
|
||||
@@ -826,11 +939,13 @@ export type ComplexUncheckedUpdateManyWithoutPlanInput = {
|
||||
|
||||
export type ComplexCountOutputType = {
|
||||
users: number
|
||||
invitations: number
|
||||
courts: number
|
||||
}
|
||||
|
||||
export type ComplexCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
users?: boolean | ComplexCountOutputTypeCountUsersArgs
|
||||
invitations?: boolean | ComplexCountOutputTypeCountInvitationsArgs
|
||||
courts?: boolean | ComplexCountOutputTypeCountCourtsArgs
|
||||
}
|
||||
|
||||
@@ -851,6 +966,13 @@ export type ComplexCountOutputTypeCountUsersArgs<ExtArgs extends runtime.Types.E
|
||||
where?: Prisma.ComplexUserWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* ComplexCountOutputType without action
|
||||
*/
|
||||
export type ComplexCountOutputTypeCountInvitationsArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
where?: Prisma.ComplexInvitationWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* ComplexCountOutputType without action
|
||||
*/
|
||||
@@ -873,6 +995,7 @@ export type ComplexSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
||||
updatedAt?: boolean
|
||||
plan?: boolean | Prisma.Complex$planArgs<ExtArgs>
|
||||
users?: boolean | Prisma.Complex$usersArgs<ExtArgs>
|
||||
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
||||
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
||||
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
||||
}, ExtArgs["result"]["complex"]>
|
||||
@@ -925,6 +1048,7 @@ export type ComplexOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
export type ComplexInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
plan?: boolean | Prisma.Complex$planArgs<ExtArgs>
|
||||
users?: boolean | Prisma.Complex$usersArgs<ExtArgs>
|
||||
invitations?: boolean | Prisma.Complex$invitationsArgs<ExtArgs>
|
||||
courts?: boolean | Prisma.Complex$courtsArgs<ExtArgs>
|
||||
_count?: boolean | Prisma.ComplexCountOutputTypeDefaultArgs<ExtArgs>
|
||||
}
|
||||
@@ -940,6 +1064,7 @@ export type $ComplexPayload<ExtArgs extends runtime.Types.Extensions.InternalArg
|
||||
objects: {
|
||||
plan: Prisma.$PlanPayload<ExtArgs> | null
|
||||
users: Prisma.$ComplexUserPayload<ExtArgs>[]
|
||||
invitations: Prisma.$ComplexInvitationPayload<ExtArgs>[]
|
||||
courts: Prisma.$CourtPayload<ExtArgs>[]
|
||||
}
|
||||
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
||||
@@ -1350,6 +1475,7 @@ export interface Prisma__ComplexClient<T, Null = never, ExtArgs extends runtime.
|
||||
readonly [Symbol.toStringTag]: "PrismaPromise"
|
||||
plan<T extends Prisma.Complex$planArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$planArgs<ExtArgs>>): Prisma.Prisma__PlanClient<runtime.Types.Result.GetResult<Prisma.$PlanPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
users<T extends Prisma.Complex$usersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Complex$usersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ComplexUserPayload<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>
|
||||
/**
|
||||
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
||||
@@ -1834,6 +1960,30 @@ export type Complex$usersArgs<ExtArgs extends runtime.Types.Extensions.InternalA
|
||||
distinct?: Prisma.ComplexUserScalarFieldEnum | Prisma.ComplexUserScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Complex.invitations
|
||||
*/
|
||||
export type Complex$invitationsArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
/**
|
||||
* Select specific fields to fetch from the ComplexInvitation
|
||||
*/
|
||||
select?: Prisma.ComplexInvitationSelect<ExtArgs> | null
|
||||
/**
|
||||
* Omit specific fields from the ComplexInvitation
|
||||
*/
|
||||
omit?: Prisma.ComplexInvitationOmit<ExtArgs> | null
|
||||
/**
|
||||
* Choose, which related nodes to fetch as well
|
||||
*/
|
||||
include?: Prisma.ComplexInvitationInclude<ExtArgs> | null
|
||||
where?: Prisma.ComplexInvitationWhereInput
|
||||
orderBy?: Prisma.ComplexInvitationOrderByWithRelationInput | Prisma.ComplexInvitationOrderByWithRelationInput[]
|
||||
cursor?: Prisma.ComplexInvitationWhereUniqueInput
|
||||
take?: number
|
||||
skip?: number
|
||||
distinct?: Prisma.ComplexInvitationScalarFieldEnum | Prisma.ComplexInvitationScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Complex.courts
|
||||
*/
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { dash } from '@better-auth/infra';
|
||||
import { betterAuth } from 'better-auth';
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
||||
import { openAPI } from 'better-auth/plugins';
|
||||
import { db } from './prisma';
|
||||
import { dash } from "@better-auth/infra";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(db, {
|
||||
@@ -28,10 +28,7 @@ export const auth = betterAuth({
|
||||
process.env.APP_BASE_URL ?? 'http://localhost:5173',
|
||||
process.env.BETTER_AUTH_URL ?? 'http://localhost:3000',
|
||||
],
|
||||
plugins: [
|
||||
openAPI(),
|
||||
dash()
|
||||
],
|
||||
plugins: [openAPI(), dash()],
|
||||
});
|
||||
|
||||
export type Session = typeof auth.$Infer.Session.session;
|
||||
|
||||
17
apps/backend/src/lib/avatar.ts
Normal file
17
apps/backend/src/lib/avatar.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
function getGravatarUrl(email: string): string {
|
||||
const hash = createHash('md5').update(email.trim().toLowerCase()).digest('hex');
|
||||
return `https://www.gravatar.com/avatar/${hash}?d=identicon`;
|
||||
}
|
||||
|
||||
export function resolveAvatarUrl(input: {
|
||||
email: string;
|
||||
image?: string | null;
|
||||
}): string {
|
||||
if (input.image) {
|
||||
return input.image;
|
||||
}
|
||||
|
||||
return getGravatarUrl(input.email);
|
||||
}
|
||||
@@ -1,14 +1,25 @@
|
||||
import { requireAuth } from '@/middlewares/require-auth.middleware';
|
||||
import { acceptComplexInvitationsHandler } from '@/modules/complex/handlers/accept-complex-invitations.handler';
|
||||
import { cancelComplexInvitationHandler } from '@/modules/complex/handlers/cancel-complex-invitation.handler';
|
||||
import { createComplexHandler } from '@/modules/complex/handlers/create-complex.handler';
|
||||
import { getComplexByIdHandler } from '@/modules/complex/handlers/get-complex-by-id.handler';
|
||||
import { getComplexBySlugHandler } from '@/modules/complex/handlers/get-complex-by-slug.handler';
|
||||
import { getCurrentComplexHandler } from '@/modules/complex/handlers/get-current-complex.handler';
|
||||
import { inviteComplexUserHandler } from '@/modules/complex/handlers/invite-complex-user.handler';
|
||||
import { listComplexUsersHandler } from '@/modules/complex/handlers/list-complex-users.handler';
|
||||
import { listMyComplexesHandler } from '@/modules/complex/handlers/list-my-complexes.handler';
|
||||
import { resendComplexInvitationHandler } from '@/modules/complex/handlers/resend-complex-invitation.handler';
|
||||
import { revokeComplexUserHandler } from '@/modules/complex/handlers/revoke-complex-user.handler';
|
||||
import { selectComplexHandler } from '@/modules/complex/handlers/select-complex.handler';
|
||||
import { updateComplexHandler } from '@/modules/complex/handlers/update-complex.handler';
|
||||
import type { AppEnv } from '@/types/hono';
|
||||
import { zValidator } from '@hono/zod-validator';
|
||||
import { createComplexSchema, updateComplexSchema } from '@repo/api-contract';
|
||||
import {
|
||||
acceptComplexInvitationsSchema,
|
||||
createComplexSchema,
|
||||
inviteComplexUserSchema,
|
||||
updateComplexSchema,
|
||||
} from '@repo/api-contract';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -21,6 +32,11 @@ complexRoutes.use('*', requireAuth);
|
||||
complexRoutes.post('/', zValidator('json', createComplexSchema), createComplexHandler);
|
||||
complexRoutes.get('/me', getCurrentComplexHandler);
|
||||
complexRoutes.post('/select', selectComplexHandler);
|
||||
complexRoutes.post(
|
||||
'/accept-pending',
|
||||
zValidator('json', acceptComplexInvitationsSchema),
|
||||
acceptComplexInvitationsHandler
|
||||
);
|
||||
complexRoutes.get('/mine', listMyComplexesHandler);
|
||||
complexRoutes.get(
|
||||
'/slug/:slug',
|
||||
@@ -28,6 +44,33 @@ complexRoutes.get(
|
||||
getComplexBySlugHandler
|
||||
);
|
||||
|
||||
complexRoutes.get(
|
||||
'/:id/users',
|
||||
zValidator('param', complexIdParamsSchema),
|
||||
listComplexUsersHandler
|
||||
);
|
||||
complexRoutes.post(
|
||||
'/:id/users',
|
||||
zValidator('param', complexIdParamsSchema),
|
||||
zValidator('json', inviteComplexUserSchema),
|
||||
inviteComplexUserHandler
|
||||
);
|
||||
complexRoutes.post(
|
||||
'/:id/invitations/:invitationId/resend',
|
||||
zValidator('param', z.object({ id: z.uuid(), invitationId: z.uuid() })),
|
||||
resendComplexInvitationHandler
|
||||
);
|
||||
complexRoutes.delete(
|
||||
'/:id/invitations/:invitationId',
|
||||
zValidator('param', z.object({ id: z.uuid(), invitationId: z.uuid() })),
|
||||
cancelComplexInvitationHandler
|
||||
);
|
||||
complexRoutes.delete(
|
||||
'/:id/users/:userId',
|
||||
zValidator('param', z.object({ id: z.uuid(), userId: z.string().min(1) })),
|
||||
revokeComplexUserHandler
|
||||
);
|
||||
|
||||
complexRoutes.get('/:id', zValidator('param', complexIdParamsSchema), getComplexByIdHandler);
|
||||
complexRoutes.patch(
|
||||
'/:id',
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
ComplexMembersError,
|
||||
acceptComplexInvitations,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { AcceptComplexInvitationsInput } from '@repo/api-contract';
|
||||
|
||||
export async function acceptComplexInvitationsHandler(c: AppContext) {
|
||||
const user = c.get('user');
|
||||
const payload = c.req.valid('json' as never) as AcceptComplexInvitationsInput;
|
||||
|
||||
try {
|
||||
const result = await acceptComplexInvitations(user.id, user.email, payload);
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof ComplexMembersError) {
|
||||
return c.json(
|
||||
{ message: error.message },
|
||||
{
|
||||
status: error.status,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
ComplexMembersError,
|
||||
cancelComplexInvitation,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
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());
|
||||
|
||||
try {
|
||||
const result = await cancelComplexInvitation(user.id, params.id, params.invitationId);
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof ComplexMembersError) {
|
||||
return c.json({ message: error.message }, { status: error.status });
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
ComplexMembersError,
|
||||
inviteComplexUser,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import type { InviteComplexUserInput } from '@repo/api-contract';
|
||||
import { z } from 'zod';
|
||||
|
||||
const complexParamsSchema = z.object({
|
||||
id: z.uuid(),
|
||||
});
|
||||
|
||||
export async function inviteComplexUserHandler(c: AppContext) {
|
||||
const user = c.get('user');
|
||||
const params = complexParamsSchema.parse(c.req.param());
|
||||
const payload = c.req.valid('json' as never) as InviteComplexUserInput;
|
||||
|
||||
try {
|
||||
const result = await inviteComplexUser(user.id, params.id, payload);
|
||||
return c.json(result, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof ComplexMembersError) {
|
||||
return c.json(
|
||||
{ message: error.message },
|
||||
{
|
||||
status: error.status,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getComplexUsersOverview } from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
const complexParamsSchema = z.object({
|
||||
id: z.uuid(),
|
||||
});
|
||||
|
||||
export async function listComplexUsersHandler(c: AppContext) {
|
||||
const user = c.get('user');
|
||||
const params = complexParamsSchema.parse(c.req.param());
|
||||
const result = await getComplexUsersOverview(user.id, params.id);
|
||||
return c.json(result);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
ComplexMembersError,
|
||||
resendComplexInvitation,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
const resendInvitationParamsSchema = z.object({
|
||||
id: z.uuid(),
|
||||
invitationId: z.uuid(),
|
||||
});
|
||||
|
||||
export async function resendComplexInvitationHandler(c: AppContext) {
|
||||
const user = c.get('user');
|
||||
const params = resendInvitationParamsSchema.parse(c.req.param());
|
||||
|
||||
try {
|
||||
const result = await resendComplexInvitation(user.id, params.id, params.invitationId);
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof ComplexMembersError) {
|
||||
return c.json({ message: error.message }, { status: error.status });
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
ComplexMembersError,
|
||||
revokeComplexUser,
|
||||
} from '@/modules/complex/services/complex-members.service';
|
||||
import type { AppContext } from '@/types/hono';
|
||||
import { z } from 'zod';
|
||||
|
||||
const revokeParamsSchema = z.object({
|
||||
id: z.uuid(),
|
||||
userId: z.string().min(1),
|
||||
});
|
||||
|
||||
export async function revokeComplexUserHandler(c: AppContext) {
|
||||
const user = c.get('user');
|
||||
const params = revokeParamsSchema.parse(c.req.param());
|
||||
|
||||
try {
|
||||
const result = await revokeComplexUser(user.id, params.id, { userId: params.userId });
|
||||
return c.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof ComplexMembersError) {
|
||||
return c.json(
|
||||
{ message: error.message },
|
||||
{
|
||||
status: error.status,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { resolveAvatarUrl } from '@/lib/avatar';
|
||||
import { sendMail } from '@/lib/mailer';
|
||||
import { db } from '@/lib/prisma';
|
||||
import type {
|
||||
AcceptComplexInvitationsInput,
|
||||
AcceptComplexInvitationsResponse,
|
||||
CancelComplexInvitationResponse,
|
||||
ComplexInvitation,
|
||||
ComplexInvitationStatus,
|
||||
ComplexUsersOverview,
|
||||
InviteComplexUserInput,
|
||||
InviteComplexUserResponse,
|
||||
RevokeComplexUserInput,
|
||||
} from '@repo/api-contract';
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
const INVITATION_TTL_DAYS = Number(Bun.env.COMPLEX_INVITATION_TTL_DAYS ?? 7);
|
||||
const APP_BASE_URL = Bun.env.APP_BASE_URL ?? 'http://localhost:5173';
|
||||
|
||||
export class ComplexMembersError extends Error {
|
||||
status: 400 | 403 | 404 | 409;
|
||||
|
||||
constructor(message: string, status: 400 | 403 | 404 | 409 = 400) {
|
||||
super(message);
|
||||
this.name = 'ComplexMembersError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
function createInvitationToken(): string {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
function nowPlusDays(days: number): Date {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() + days);
|
||||
return date;
|
||||
}
|
||||
|
||||
function getInvitationStatus(invitation: {
|
||||
expiresAt: Date;
|
||||
acceptedAt: Date | null;
|
||||
revokedAt: Date | null;
|
||||
}): ComplexInvitationStatus {
|
||||
if (invitation.acceptedAt) return 'ACCEPTED';
|
||||
if (invitation.revokedAt) return 'REVOKED';
|
||||
if (invitation.expiresAt < new Date()) return 'EXPIRED';
|
||||
return 'PENDING';
|
||||
}
|
||||
|
||||
function formatInvitation(invitation: {
|
||||
id: string;
|
||||
complexId: string;
|
||||
email: string;
|
||||
expiresAt: Date;
|
||||
acceptedAt: Date | null;
|
||||
revokedAt: Date | null;
|
||||
createdAt: Date;
|
||||
}): ComplexInvitation {
|
||||
return {
|
||||
id: invitation.id,
|
||||
complexId: invitation.complexId,
|
||||
email: invitation.email,
|
||||
status: getInvitationStatus(invitation),
|
||||
createdAt: invitation.createdAt.toISOString(),
|
||||
expiresAt: invitation.expiresAt.toISOString(),
|
||||
acceptedAt: invitation.acceptedAt?.toISOString() ?? null,
|
||||
revokedAt: invitation.revokedAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureComplexAdmin(userId: string, complexId: string) {
|
||||
const membership = await db.complexUser.findUnique({
|
||||
where: {
|
||||
complexId_userId: {
|
||||
complexId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new ComplexMembersError('No tenés acceso a este complejo.', 403);
|
||||
}
|
||||
|
||||
if (membership.role !== 'ADMIN') {
|
||||
throw new ComplexMembersError('Solo un ADMIN puede administrar usuarios.', 403);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureComplexMember(userId: string, complexId: string) {
|
||||
const membership = await db.complexUser.findUnique({
|
||||
where: {
|
||||
complexId_userId: {
|
||||
complexId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new ComplexMembersError('No tenés acceso a este complejo.', 403);
|
||||
}
|
||||
|
||||
return membership;
|
||||
}
|
||||
|
||||
async function sendInvitationEmail(input: {
|
||||
complexName: string;
|
||||
inviteeEmail: string;
|
||||
token: string;
|
||||
}) {
|
||||
const inviteUrl = new URL('/invite', APP_BASE_URL);
|
||||
inviteUrl.searchParams.set('inviteToken', input.token);
|
||||
inviteUrl.searchParams.set('email', input.inviteeEmail);
|
||||
|
||||
await sendMail({
|
||||
to: input.inviteeEmail,
|
||||
subject: `Te invitaron a ${input.complexName}`,
|
||||
text: `Te invitaron a sumarte a ${input.complexName}. Abrí este enlace para crear tu cuenta o iniciar sesión: ${inviteUrl.toString()}`,
|
||||
html: `
|
||||
<h2>Te invitaron a <strong>${input.complexName}</strong></h2>
|
||||
<p>Hacé click en el siguiente enlace para crear tu cuenta o iniciar sesión y aceptar la invitación:</p>
|
||||
<p><a href="${inviteUrl.toString()}">${inviteUrl.toString()}</a></p>
|
||||
`,
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshPendingInvitation(invitationId: string) {
|
||||
const token = createInvitationToken();
|
||||
const tokenHash = hashToken(token);
|
||||
const expiresAt = nowPlusDays(INVITATION_TTL_DAYS);
|
||||
|
||||
const invitation = await db.complexInvitation.update({
|
||||
where: {
|
||||
id: invitationId,
|
||||
},
|
||||
data: {
|
||||
tokenHash,
|
||||
expiresAt,
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
},
|
||||
include: {
|
||||
complex: {
|
||||
select: {
|
||||
complexName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
invitation,
|
||||
token,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listComplexUsers(complexId: string) {
|
||||
const [members, invitations] = await Promise.all([
|
||||
db.complexUser.findMany({
|
||||
where: { complexId },
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'asc',
|
||||
},
|
||||
}),
|
||||
db.complexInvitation.findMany({
|
||||
where: {
|
||||
complexId,
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
expiresAt: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const membersWithAvatars = members.map((member) => ({
|
||||
userId: member.userId,
|
||||
fullName: member.user.name,
|
||||
email: member.user.email,
|
||||
avatarUrl: resolveAvatarUrl({
|
||||
email: member.user.email,
|
||||
image: member.user.image,
|
||||
}),
|
||||
role: member.role,
|
||||
createdAt: member.createdAt.toISOString(),
|
||||
}));
|
||||
|
||||
return {
|
||||
members: membersWithAvatars,
|
||||
invitations: invitations.map(formatInvitation),
|
||||
} satisfies ComplexUsersOverview;
|
||||
}
|
||||
|
||||
export async function inviteComplexUser(
|
||||
userId: string,
|
||||
complexId: string,
|
||||
input: InviteComplexUserInput
|
||||
): Promise<InviteComplexUserResponse> {
|
||||
await ensureComplexAdmin(userId, complexId);
|
||||
|
||||
const email = normalizeEmail(input.email);
|
||||
const complex = await db.complex.findUnique({
|
||||
where: { id: complexId },
|
||||
select: {
|
||||
complexName: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!complex) {
|
||||
throw new ComplexMembersError('El complejo no existe.', 404);
|
||||
}
|
||||
|
||||
const existingUser = await db.user.findUnique({
|
||||
where: { email },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
const existingMembership = await db.complexUser.findUnique({
|
||||
where: {
|
||||
complexId_userId: {
|
||||
complexId,
|
||||
userId: existingUser.id,
|
||||
},
|
||||
},
|
||||
select: { userId: true },
|
||||
});
|
||||
|
||||
if (existingMembership) {
|
||||
throw new ComplexMembersError('Ese usuario ya pertenece al complejo.', 409);
|
||||
}
|
||||
}
|
||||
|
||||
const token = createInvitationToken();
|
||||
|
||||
const invitation = await db.$transaction(async (tx) => {
|
||||
const pendingInvitation = await tx.complexInvitation.findFirst({
|
||||
where: {
|
||||
complexId,
|
||||
email,
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
expiresAt: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
if (pendingInvitation) {
|
||||
const refreshed = await tx.complexInvitation.update({
|
||||
where: {
|
||||
id: pendingInvitation.id,
|
||||
},
|
||||
data: {
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt: nowPlusDays(INVITATION_TTL_DAYS),
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
return refreshed;
|
||||
}
|
||||
|
||||
return tx.complexInvitation.create({
|
||||
data: {
|
||||
id: uuidv7(),
|
||||
complexId,
|
||||
email,
|
||||
tokenHash: hashToken(token),
|
||||
expiresAt: nowPlusDays(INVITATION_TTL_DAYS),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await sendInvitationEmail({
|
||||
complexName: complex.complexName,
|
||||
inviteeEmail: email,
|
||||
token,
|
||||
});
|
||||
|
||||
return {
|
||||
invitation: formatInvitation(invitation),
|
||||
};
|
||||
}
|
||||
|
||||
export async function resendComplexInvitation(
|
||||
userId: string,
|
||||
complexId: string,
|
||||
invitationId: string
|
||||
): Promise<InviteComplexUserResponse> {
|
||||
await ensureComplexAdmin(userId, complexId);
|
||||
|
||||
const pendingInvitation = await db.complexInvitation.findUnique({
|
||||
where: {
|
||||
id: invitationId,
|
||||
},
|
||||
include: {
|
||||
complex: {
|
||||
select: {
|
||||
complexName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!pendingInvitation || pendingInvitation.complexId !== complexId) {
|
||||
throw new ComplexMembersError('La invitación no existe.', 404);
|
||||
}
|
||||
|
||||
if (pendingInvitation.acceptedAt) {
|
||||
throw new ComplexMembersError('La invitación ya fue aceptada.', 409);
|
||||
}
|
||||
|
||||
if (pendingInvitation.revokedAt) {
|
||||
throw new ComplexMembersError('La invitación fue cancelada.', 409);
|
||||
}
|
||||
|
||||
const refreshed = await refreshPendingInvitation(invitationId);
|
||||
|
||||
await sendInvitationEmail({
|
||||
complexName: refreshed.invitation.complex.complexName,
|
||||
inviteeEmail: pendingInvitation.email,
|
||||
token: refreshed.token,
|
||||
});
|
||||
|
||||
return {
|
||||
invitation: formatInvitation({
|
||||
id: refreshed.invitation.id,
|
||||
complexId: refreshed.invitation.complexId,
|
||||
email: refreshed.invitation.email,
|
||||
expiresAt: refreshed.invitation.expiresAt,
|
||||
acceptedAt: refreshed.invitation.acceptedAt,
|
||||
revokedAt: refreshed.invitation.revokedAt,
|
||||
createdAt: refreshed.invitation.createdAt,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function acceptComplexInvitations(
|
||||
userId: string,
|
||||
email: string,
|
||||
input: AcceptComplexInvitationsInput = {}
|
||||
): Promise<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) {
|
||||
throw new ComplexMembersError('La invitación es inválida o ya venció.', 404);
|
||||
}
|
||||
|
||||
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 {
|
||||
acceptedCount,
|
||||
};
|
||||
}
|
||||
|
||||
export async function revokeComplexUser(
|
||||
userId: string,
|
||||
complexId: string,
|
||||
input: RevokeComplexUserInput
|
||||
) {
|
||||
await ensureComplexAdmin(userId, complexId);
|
||||
|
||||
const membership = await db.complexUser.findUnique({
|
||||
where: {
|
||||
complexId_userId: {
|
||||
complexId,
|
||||
userId: input.userId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new ComplexMembersError('Ese usuario no pertenece al complejo.', 404);
|
||||
}
|
||||
|
||||
if (membership.role !== 'EMPLOYEE') {
|
||||
throw new ComplexMembersError('Solo podés revocar usuarios con rol EMPLOYEE.', 409);
|
||||
}
|
||||
|
||||
await db.complexUser.delete({
|
||||
where: {
|
||||
complexId_userId: {
|
||||
complexId,
|
||||
userId: input.userId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function cancelComplexInvitation(
|
||||
userId: string,
|
||||
complexId: string,
|
||||
invitationId: string
|
||||
): Promise<CancelComplexInvitationResponse> {
|
||||
await ensureComplexAdmin(userId, complexId);
|
||||
|
||||
const invitation = await db.complexInvitation.findUnique({
|
||||
where: {
|
||||
id: invitationId,
|
||||
},
|
||||
select: {
|
||||
complexId: true,
|
||||
acceptedAt: true,
|
||||
revokedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!invitation || invitation.complexId !== complexId) {
|
||||
throw new ComplexMembersError('La invitación no existe.', 404);
|
||||
}
|
||||
|
||||
if (invitation.acceptedAt) {
|
||||
throw new ComplexMembersError('La invitación ya fue aceptada.', 409);
|
||||
}
|
||||
|
||||
if (invitation.revokedAt) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
await db.complexInvitation.update({
|
||||
where: {
|
||||
id: invitationId,
|
||||
},
|
||||
data: {
|
||||
revokedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export async function getComplexUsersOverview(userId: string, complexId: string) {
|
||||
await ensureComplexMember(userId, complexId);
|
||||
return listComplexUsers(complexId);
|
||||
}
|
||||
@@ -65,7 +65,7 @@ async function buildUniqueSlug(source: string, excludeComplexId?: string): Promi
|
||||
}
|
||||
|
||||
export async function createComplex(input: CreateComplexInput) {
|
||||
const { userId, ...rest } = input;
|
||||
const { userId } = input;
|
||||
|
||||
return db.$transaction(async (tx) => {
|
||||
const complexSlug = await buildUniqueSlug(input.complexName);
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { User } from '@/lib/auth';
|
||||
import { resolveAvatarUrl } from '@/lib/avatar';
|
||||
import { db } from '@/lib/prisma';
|
||||
import type { UserProfile } from '@repo/api-contract';
|
||||
|
||||
function getGravatarUrl(email: string): string {
|
||||
const hash = createHash('md5').update(email.trim().toLowerCase()).digest('hex');
|
||||
return `https://www.gravatar.com/avatar/${hash}?d=identicon`;
|
||||
}
|
||||
|
||||
export async function getUserProfile(user: User, complexId?: string): Promise<UserProfile> {
|
||||
const dbUser = await db.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
image: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!dbUser) {
|
||||
throw new Error('User not found.');
|
||||
}
|
||||
|
||||
let role = 'member';
|
||||
|
||||
if (complexId) {
|
||||
@@ -27,11 +37,14 @@ export async function getUserProfile(user: User, complexId?: string): Promise<Us
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
fullName: user.name,
|
||||
email: user.email,
|
||||
id: dbUser.id,
|
||||
fullName: dbUser.name,
|
||||
email: dbUser.email,
|
||||
role,
|
||||
avatarUrl: user.image || getGravatarUrl(user.email),
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
avatarUrl: resolveAvatarUrl({
|
||||
email: dbUser.email,
|
||||
image: dbUser.image,
|
||||
}),
|
||||
createdAt: dbUser.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
47
apps/frontend/src/components/user-avatar.tsx
Normal file
47
apps/frontend/src/components/user-avatar.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type UserAvatarProps = {
|
||||
src?: string | null;
|
||||
alt: string;
|
||||
fallbackText: string;
|
||||
size?: 'default' | 'sm' | 'lg';
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function getInitials(text: string) {
|
||||
const words = text.trim().split(/\s+/).filter(Boolean).slice(0, 2);
|
||||
const initials = words.map((word) => word[0]?.toUpperCase() ?? '').join('');
|
||||
return initials || 'U';
|
||||
}
|
||||
|
||||
export function UserAvatar({
|
||||
src,
|
||||
alt,
|
||||
fallbackText,
|
||||
size = 'default',
|
||||
className,
|
||||
}: UserAvatarProps) {
|
||||
const [imageError, setImageError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setImageError(false);
|
||||
}, [src]);
|
||||
|
||||
const canShowImage = Boolean(src) && !imageError;
|
||||
|
||||
return (
|
||||
<Avatar size={size} className={className}>
|
||||
{canShowImage && (
|
||||
<AvatarImage
|
||||
src={src ?? undefined}
|
||||
alt={alt}
|
||||
onError={() => {
|
||||
setImageError(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<AvatarFallback>{getInitials(fallbackText)}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { setCurrentComplexSlug } from '@/lib/current-complex';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Building2, MapPin, Settings } from 'lucide-react';
|
||||
import { Building2, MapPin, Settings, Users } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ComplexCourtsSection } from './components/complex-courts-section';
|
||||
import { ComplexDetailsSection } from './components/complex-details-section';
|
||||
import { ComplexUsersSection } from './components/complex-users-section';
|
||||
|
||||
type ComplexSettingsPageProps = {
|
||||
complexSlug: string;
|
||||
};
|
||||
|
||||
type TabOption = 'details' | 'courts';
|
||||
type TabOption = 'details' | 'courts' | 'users';
|
||||
|
||||
export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
const [activeTab, setActiveTab] = useState<TabOption>('details');
|
||||
@@ -24,11 +25,21 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
queryFn: () => apiClient.complexes.getBySlug(complexSlug),
|
||||
});
|
||||
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
});
|
||||
|
||||
const complexId = complexQuery.data?.id ?? null;
|
||||
const currentMembership = myComplexesQuery.data?.find(
|
||||
(complex) => complex.complexSlug === complexSlug
|
||||
);
|
||||
const canManageUsers = currentMembership?.role === 'ADMIN';
|
||||
|
||||
const tabs = [
|
||||
{ id: 'details' as const, label: 'Datos del complejo', icon: Building2 },
|
||||
{ id: 'courts' as const, label: 'Canchas', icon: MapPin },
|
||||
{ id: 'users' as const, label: 'Usuarios', icon: Users },
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -76,6 +87,10 @@ export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
|
||||
)}
|
||||
|
||||
{activeTab === 'courts' && <ComplexCourtsSection complexId={complexId} />}
|
||||
|
||||
{activeTab === 'users' && (
|
||||
<ComplexUsersSection complexId={complexId} canManageUsers={canManageUsers} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Field, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
ResponsiveDialog,
|
||||
ResponsiveDialogClose,
|
||||
ResponsiveDialogContent,
|
||||
ResponsiveDialogDescription,
|
||||
ResponsiveDialogFooter,
|
||||
ResponsiveDialogHeader,
|
||||
ResponsiveDialogTitle,
|
||||
} from '@/components/ui/responsive-dialog';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import type { ComplexUsersOverview } from '@repo/api-contract';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AlertCircle, Loader2, Mail, RotateCw, Trash2, UserPlus, UserX, Users } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type ComplexUsersSectionProps = {
|
||||
complexId: string | null;
|
||||
canManageUsers: boolean;
|
||||
};
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat('es-AR', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function UsersSkeleton() {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-muted-foreground">Cargando usuarios...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComplexUsersSection({ complexId, canManageUsers }: ComplexUsersSectionProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [email, setEmail] = useState('');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [invitationToCancel, setInvitationToCancel] = useState<
|
||||
ComplexUsersOverview['invitations'][number] | null
|
||||
>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setEmail('');
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage(null);
|
||||
setInvitationToCancel(null);
|
||||
}, [complexId]);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ['complex-users', complexId],
|
||||
enabled: Boolean(complexId),
|
||||
queryFn: () => apiClient.complexes.listUsers(complexId!),
|
||||
});
|
||||
|
||||
const inviteMutation = useMutation({
|
||||
mutationFn: (payload: { email: string }) => apiClient.complexes.inviteUser(complexId!, payload),
|
||||
onSuccess: async () => {
|
||||
setEmail('');
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('Invitación enviada correctamente.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos enviar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const revokeMutation = useMutation({
|
||||
mutationFn: (userId: string) => apiClient.complexes.revokeUser(complexId!, { userId }),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('El usuario fue desvinculado del complejo.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos revocar el permiso.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const resendInvitationMutation = useMutation({
|
||||
mutationFn: (invitationId: string) =>
|
||||
apiClient.complexes.resendInvitation(complexId!, invitationId),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('La invitación se reenvió correctamente.');
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos reenviar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const cancelInvitationMutation = useMutation({
|
||||
mutationFn: (invitationId: string) =>
|
||||
apiClient.complexes.cancelInvitation(complexId!, invitationId),
|
||||
onSuccess: async () => {
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage('La invitación fue cancelada.');
|
||||
setInvitationToCancel(null);
|
||||
await queryClient.invalidateQueries({ queryKey: ['complex-users', complexId] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || 'No pudimos cancelar la invitación.');
|
||||
setSuccessMessage(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleInvite = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setErrorMessage(null);
|
||||
setSuccessMessage(null);
|
||||
|
||||
const trimmedEmail = email.trim();
|
||||
|
||||
if (!trimmedEmail) {
|
||||
setErrorMessage('Ingresá un email.');
|
||||
return;
|
||||
}
|
||||
|
||||
inviteMutation.mutate({ email: trimmedEmail });
|
||||
};
|
||||
|
||||
if (!complexId) {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Seleccioná un complejo para ver sus usuarios.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (usersQuery.isLoading) {
|
||||
return <UsersSkeleton />;
|
||||
}
|
||||
|
||||
if (usersQuery.isError || !usersQuery.data) {
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
<p className="text-sm text-destructive">No se pudieron cargar los usuarios del complejo.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const data: ComplexUsersOverview = usersQuery.data;
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border bg-card p-5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">Usuarios</h3>
|
||||
</div>
|
||||
<Separator className="my-4" />
|
||||
|
||||
{canManageUsers ? (
|
||||
<form className="mb-6 rounded-lg border bg-muted/30 p-4" onSubmit={handleInvite}>
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<UserPlus className="size-4 text-muted-foreground" />
|
||||
<h4 className="text-sm font-medium">Invitar un usuario</h4>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Field className="flex-1">
|
||||
<FieldLabel htmlFor="invite-email">Email</FieldLabel>
|
||||
<Input
|
||||
id="invite-email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
placeholder="empleado@correo.com"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="flex items-end">
|
||||
<Button type="submit" disabled={inviteMutation.isPending}>
|
||||
{inviteMutation.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}
|
||||
Enviar invitación
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
La invitación se envía por email y el usuario quedará vinculado como EMPLOYEE al
|
||||
aceptar.
|
||||
</p>
|
||||
</form>
|
||||
) : (
|
||||
<div className="mb-6 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
Solo un ADMIN puede invitar o desvincular usuarios.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{successMessage && (
|
||||
<p className="mb-4 text-sm text-green-600 dark:text-green-400">{successMessage}</p>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<p className="mb-4 flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="size-4" />
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h4 className="mb-3 text-sm font-medium">Miembros</h4>
|
||||
<div className="space-y-2">
|
||||
{data.members.map((member) => (
|
||||
<div
|
||||
key={member.userId}
|
||||
className="flex flex-col gap-3 rounded-lg border px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{member.fullName}</p>
|
||||
<p className="text-sm text-muted-foreground">{member.email}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Rol: {member.role} · Desde {formatDate(member.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<UserAvatar
|
||||
src={member.avatarUrl}
|
||||
alt={member.fullName}
|
||||
fallbackText={member.fullName}
|
||||
size="default"
|
||||
className="border"
|
||||
/>
|
||||
|
||||
{canManageUsers && member.role === 'EMPLOYEE' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => revokeMutation.mutate(member.userId)}
|
||||
disabled={revokeMutation.isPending}
|
||||
>
|
||||
<UserX className="mr-2 size-4" />
|
||||
Revocar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="mb-3 text-sm font-medium">Invitaciones pendientes</h4>
|
||||
{data.invitations.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No hay invitaciones pendientes.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{data.invitations.map((invitation) => (
|
||||
<div
|
||||
key={invitation.id}
|
||||
className="flex flex-col gap-2 rounded-lg border px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{invitation.email}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Vence {formatDate(invitation.expiresAt)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-start gap-2 sm:items-end">
|
||||
<span className="inline-flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground">
|
||||
<Mail className="size-3.5" />
|
||||
Pendiente
|
||||
</span>
|
||||
|
||||
{canManageUsers && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => resendInvitationMutation.mutate(invitation.id)}
|
||||
disabled={resendInvitationMutation.isPending}
|
||||
>
|
||||
<RotateCw className="mr-2 size-4" />
|
||||
Reenviar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => setInvitationToCancel(invitation)}
|
||||
disabled={cancelInvitationMutation.isPending}
|
||||
>
|
||||
<Trash2 className="mr-2 size-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ResponsiveDialog
|
||||
open={Boolean(invitationToCancel)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setInvitationToCancel(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ResponsiveDialogContent className="data-[variant=dialog]:max-w-md">
|
||||
<ResponsiveDialogHeader>
|
||||
<ResponsiveDialogTitle>Cancelar invitación</ResponsiveDialogTitle>
|
||||
<ResponsiveDialogDescription>
|
||||
Esta acción va a invalidar el link de invitación y la persona ya no podrá aceptar la
|
||||
invitación.
|
||||
</ResponsiveDialogDescription>
|
||||
</ResponsiveDialogHeader>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{invitationToCancel
|
||||
? `Se cancelará la invitación enviada a ${invitationToCancel.email}.`
|
||||
: 'Se cancelará la invitación seleccionada.'}
|
||||
</p>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Si querés volver a invitarlo, vas a poder generar una nueva invitación después.
|
||||
</p>
|
||||
|
||||
<ResponsiveDialogFooter>
|
||||
<ResponsiveDialogClose asChild>
|
||||
<Button variant="outline">Volver</Button>
|
||||
</ResponsiveDialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
if (!invitationToCancel) return;
|
||||
cancelInvitationMutation.mutate(invitationToCancel.id);
|
||||
}}
|
||||
disabled={cancelInvitationMutation.isPending}
|
||||
>
|
||||
{cancelInvitationMutation.isPending ? 'Cancelando...' : 'Cancelar invitación'}
|
||||
</Button>
|
||||
</ResponsiveDialogFooter>
|
||||
</ResponsiveDialogContent>
|
||||
</ResponsiveDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -8,25 +7,49 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, Outlet, useNavigate } from '@tanstack/react-router';
|
||||
import { LogOut, Menu, UserRound } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { ThemeSwitcher } from './theme-switcher';
|
||||
|
||||
export function RootLayout() {
|
||||
const navigate = useNavigate();
|
||||
const { isAuthenticated, displayName, initials, avatarUrl, signOut } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
||||
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
|
||||
const processedInviteForUser = useRef<string | null>(null);
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
enabled: isAuthenticated,
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
processedInviteForUser.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const userKey = user?.email ?? displayName ?? 'authenticated-user';
|
||||
|
||||
if (processedInviteForUser.current === userKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
processedInviteForUser.current = userKey;
|
||||
|
||||
void (async () => {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
|
||||
})();
|
||||
}, [displayName, isAuthenticated, queryClient, user?.email]);
|
||||
|
||||
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
|
||||
|
||||
const currentComplexName = useMemo(() => {
|
||||
@@ -85,10 +108,12 @@ export function RootLayout() {
|
||||
type="button"
|
||||
className="hidden items-center gap-2 rounded-md px-2 py-1.5 transition-colors hover:bg-muted md:inline-flex"
|
||||
>
|
||||
<Avatar size="sm">
|
||||
<AvatarImage src={avatarUrl ?? undefined} alt={displayName} />
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<UserAvatar
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
size="sm"
|
||||
/>
|
||||
<span className="max-w-32 truncate text-sm text-foreground">{displayName}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { apiClient, authClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import { useState } from 'react';
|
||||
@@ -39,6 +40,7 @@ export function LoginPage({ redirectTo = '/' }: LoginPageProps) {
|
||||
});
|
||||
|
||||
async function handlePostLogin() {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 0) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Field, FieldError, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { apiClient, authClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { useState } from 'react';
|
||||
@@ -29,26 +30,46 @@ const signupSchema = z
|
||||
type LoginForm = z.infer<typeof loginSchema>;
|
||||
type SignupForm = z.infer<typeof signupSchema>;
|
||||
|
||||
export function OnboardLoginPage() {
|
||||
type OnboardLoginPageProps = {
|
||||
variant?: 'onboard' | 'invite';
|
||||
inviteEmail?: string | null;
|
||||
};
|
||||
|
||||
export function OnboardLoginPage({
|
||||
variant = 'onboard',
|
||||
inviteEmail = null,
|
||||
}: OnboardLoginPageProps) {
|
||||
const navigate = useNavigate();
|
||||
const { signInWithPassword, signUp } = useAuth();
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login');
|
||||
const [mode, setMode] = useState<'login' | 'signup'>(variant === 'invite' ? 'signup' : 'login');
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const loginForm = useForm<LoginForm>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: { email: '', password: '' },
|
||||
defaultValues: { email: inviteEmail ?? '', password: '' },
|
||||
});
|
||||
|
||||
const signupForm = useForm<SignupForm>({
|
||||
resolver: zodResolver(signupSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: { fullName: '', email: '', password: '', confirmPassword: '' },
|
||||
defaultValues: {
|
||||
fullName: '',
|
||||
email: inviteEmail ?? '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
},
|
||||
});
|
||||
|
||||
async function handlePostLogin() {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
|
||||
if (variant === 'invite') {
|
||||
await navigate({ to: '/' });
|
||||
return;
|
||||
}
|
||||
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 0) {
|
||||
@@ -93,7 +114,12 @@ export function OnboardLoginPage() {
|
||||
search: { email: values.email },
|
||||
});
|
||||
} else {
|
||||
navigate({ to: '/onboard/create-complex' });
|
||||
if (variant === 'invite') {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await navigate({ to: '/' });
|
||||
} else {
|
||||
await handlePostLogin();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setSubmitError('No pudimos crear la cuenta. Intenta nuevamente.');
|
||||
@@ -108,7 +134,7 @@ export function OnboardLoginPage() {
|
||||
try {
|
||||
await authClient.signIn.social({
|
||||
provider: 'google',
|
||||
callbackURL: `${window.location.origin}/onboard/create-complex`,
|
||||
callbackURL: `${window.location.origin}/auth-callback`,
|
||||
});
|
||||
} catch {
|
||||
setSubmitError('No pudimos iniciar sesión con Google.');
|
||||
@@ -123,7 +149,11 @@ export function OnboardLoginPage() {
|
||||
</h1>
|
||||
<p className="mb-4 text-sm text-muted-foreground">
|
||||
{mode === 'login'
|
||||
? 'Ingresá con tu cuenta para continuar.'
|
||||
? variant === 'invite'
|
||||
? 'Ingresá con tu cuenta para aceptar la invitación.'
|
||||
: 'Ingresá con tu cuenta para continuar.'
|
||||
: variant === 'invite'
|
||||
? 'Creá tu cuenta para aceptar la invitación.'
|
||||
: 'Creá tu cuenta para comenzar.'}
|
||||
</p>
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { getPendingInvite } from '@/lib/invitations';
|
||||
import { Route } from '@/routes/onboard/verify-email';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useEffect, useState } from 'react';
|
||||
@@ -6,6 +7,7 @@ import { useEffect, useState } from 'react';
|
||||
export function VerifyEmailPage() {
|
||||
const search = Route.useSearch();
|
||||
const email = search.email || sessionStorage.getItem('pending-signup-email') || '';
|
||||
const pendingInvite = getPendingInvite();
|
||||
const [resendCooldown, setResendCooldown] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,9 +44,22 @@ export function VerifyEmailPage() {
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
¿Ya verificaste tu email?{' '}
|
||||
{pendingInvite.token ? (
|
||||
<Link
|
||||
to="/invite"
|
||||
search={{
|
||||
email: pendingInvite.email ?? email,
|
||||
inviteToken: pendingInvite.token,
|
||||
}}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
Continuar con la invitación
|
||||
</Link>
|
||||
) : (
|
||||
<Link to="/onboard/create-complex" className="text-primary hover:underline">
|
||||
Continuar
|
||||
</Link>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { UserAvatar } from '@/components/user-avatar';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
@@ -38,7 +38,7 @@ type UpdateProfileForm = z.infer<typeof updateProfileSchema>;
|
||||
type UpdatePasswordForm = z.infer<typeof updatePasswordSchema>;
|
||||
|
||||
export function ProfilePage() {
|
||||
const { user, displayName, initials, avatarUrl, isAuthenticated, updateProfile, updatePassword } =
|
||||
const { user, displayName, avatarUrl, isAuthenticated, updateProfile, updatePassword } =
|
||||
useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const profileQuery = useQuery({
|
||||
@@ -119,13 +119,12 @@ export function ProfilePage() {
|
||||
<div className="w-full max-w-3xl space-y-6">
|
||||
<section className="rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar size="lg">
|
||||
<AvatarImage
|
||||
src={profileQuery.data?.avatarUrl ?? avatarUrl ?? undefined}
|
||||
<UserAvatar
|
||||
src={profileQuery.data?.avatarUrl ?? avatarUrl}
|
||||
alt={displayName}
|
||||
fallbackText={displayName}
|
||||
size="lg"
|
||||
/>
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">{displayName}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { sentinelClient } from '@better-auth/infra/client';
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import * as api from './api';
|
||||
import { sentinelClient } from "@better-auth/infra/client";
|
||||
|
||||
const apiBaseUrl = api.apiBaseUrl;
|
||||
|
||||
const plugins = [
|
||||
sentinelClient()
|
||||
]
|
||||
const plugins = [sentinelClient()];
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: apiBaseUrl,
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import type {
|
||||
AcceptComplexInvitationsInput,
|
||||
AcceptComplexInvitationsResponse,
|
||||
CancelComplexInvitationResponse,
|
||||
Complex,
|
||||
ComplexUsersOverview,
|
||||
ComplexWithRole,
|
||||
CreateComplexPayload,
|
||||
CreateComplexResponse,
|
||||
InviteComplexUserInput,
|
||||
InviteComplexUserResponse,
|
||||
RevokeComplexUserInput,
|
||||
SelectComplexInput,
|
||||
UpdateComplexPayload,
|
||||
UpdateComplexResponse,
|
||||
@@ -49,3 +56,47 @@ export async function select(payload: SelectComplexInput) {
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function listUsers(id: string) {
|
||||
const response = await http.get<ComplexUsersOverview>(`/api/complexes/${id}/users`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function inviteUser(id: string, payload: InviteComplexUserInput) {
|
||||
const response = await http.post<InviteComplexUserResponse>(
|
||||
`/api/complexes/${id}/users`,
|
||||
JSON.stringify(payload),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function revokeUser(id: string, payload: RevokeComplexUserInput) {
|
||||
const response = await http.delete<{ ok: boolean }>(
|
||||
`/api/complexes/${id}/users/${payload.userId}`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function acceptPendingInvitations(payload: AcceptComplexInvitationsInput = {}) {
|
||||
const response = await http.post<AcceptComplexInvitationsResponse>(
|
||||
'/api/complexes/accept-pending',
|
||||
JSON.stringify(payload),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function resendInvitation(id: string, invitationId: string) {
|
||||
const response = await http.post<InviteComplexUserResponse>(
|
||||
`/api/complexes/${id}/invitations/${invitationId}/resend`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function cancelInvitation(id: string, invitationId: string) {
|
||||
const response = await http.delete<CancelComplexInvitationResponse>(
|
||||
`/api/complexes/${id}/invitations/${invitationId}`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
71
apps/frontend/src/lib/invitations.ts
Normal file
71
apps/frontend/src/lib/invitations.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
const PENDING_INVITE_EMAIL_KEY = 'pending-invite-email';
|
||||
const PENDING_INVITE_TOKEN_KEY = 'pending-invite-token';
|
||||
|
||||
export type PendingInvite = {
|
||||
email: string | null;
|
||||
token: string | null;
|
||||
};
|
||||
|
||||
function getSessionStorage(): Storage | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return window.sessionStorage;
|
||||
}
|
||||
|
||||
export function setPendingInvite(invite: PendingInvite) {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) return;
|
||||
|
||||
clearPendingInvite();
|
||||
|
||||
if (invite.email) {
|
||||
storage.setItem(PENDING_INVITE_EMAIL_KEY, invite.email);
|
||||
}
|
||||
|
||||
if (invite.token) {
|
||||
storage.setItem(PENDING_INVITE_TOKEN_KEY, invite.token);
|
||||
}
|
||||
}
|
||||
|
||||
export function getPendingInvite(): PendingInvite {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) {
|
||||
return {
|
||||
email: null,
|
||||
token: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
email: storage.getItem(PENDING_INVITE_EMAIL_KEY),
|
||||
token: storage.getItem(PENDING_INVITE_TOKEN_KEY),
|
||||
};
|
||||
}
|
||||
|
||||
export function clearPendingInvite() {
|
||||
const storage = getSessionStorage();
|
||||
|
||||
if (!storage) return;
|
||||
|
||||
storage.removeItem(PENDING_INVITE_EMAIL_KEY);
|
||||
storage.removeItem(PENDING_INVITE_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export async function acceptStoredPendingInvite(
|
||||
acceptPendingInvitations: (payload: { inviteToken?: string }) => Promise<unknown>
|
||||
) {
|
||||
const pendingInvite = getPendingInvite();
|
||||
|
||||
if (!pendingInvite.token) {
|
||||
await acceptPendingInvitations({});
|
||||
clearPendingInvite();
|
||||
return;
|
||||
}
|
||||
|
||||
await acceptPendingInvitations({ inviteToken: pendingInvite.token });
|
||||
clearPendingInvite();
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { Route as SelectComplexRouteImport } from './routes/select-complex'
|
||||
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||
import { Route as OnboardRouteImport } from './routes/onboard'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as InviteRouteImport } from './routes/invite'
|
||||
import { Route as AuthCallbackRouteImport } from './routes/auth-callback'
|
||||
import { Route as AppRouteRouteImport } from './routes/_app/route'
|
||||
import { Route as OnboardIndexRouteImport } from './routes/onboard/index'
|
||||
@@ -49,6 +50,11 @@ const LoginRoute = LoginRouteImport.update({
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const InviteRoute = InviteRouteImport.update({
|
||||
id: '/invite',
|
||||
path: '/invite',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthCallbackRoute = AuthCallbackRouteImport.update({
|
||||
id: '/auth-callback',
|
||||
path: '/auth-callback',
|
||||
@@ -128,6 +134,7 @@ const AppAuthenticatedComplexSlugEditRoute =
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof AppAuthenticatedIndexRoute
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/onboard': typeof OnboardRouteWithChildren
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
@@ -147,6 +154,7 @@ export interface FileRoutesByFullPath {
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof AppAuthenticatedIndexRoute
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/select-complex': typeof SelectComplexRoute
|
||||
@@ -165,6 +173,7 @@ export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_app': typeof AppRouteRouteWithChildren
|
||||
'/auth-callback': typeof AuthCallbackRoute
|
||||
'/invite': typeof InviteRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/onboard': typeof OnboardRouteWithChildren
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
@@ -188,6 +197,7 @@ export interface FileRouteTypes {
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/onboard'
|
||||
| '/reset-password'
|
||||
@@ -207,6 +217,7 @@ export interface FileRouteTypes {
|
||||
to:
|
||||
| '/'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/select-complex'
|
||||
@@ -224,6 +235,7 @@ export interface FileRouteTypes {
|
||||
| '__root__'
|
||||
| '/_app'
|
||||
| '/auth-callback'
|
||||
| '/invite'
|
||||
| '/login'
|
||||
| '/onboard'
|
||||
| '/reset-password'
|
||||
@@ -246,6 +258,7 @@ export interface FileRouteTypes {
|
||||
export interface RootRouteChildren {
|
||||
AppRouteRoute: typeof AppRouteRouteWithChildren
|
||||
AuthCallbackRoute: typeof AuthCallbackRoute
|
||||
InviteRoute: typeof InviteRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
OnboardRoute: typeof OnboardRouteWithChildren
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
@@ -283,6 +296,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/invite': {
|
||||
id: '/invite'
|
||||
path: '/invite'
|
||||
fullPath: '/invite'
|
||||
preLoaderRoute: typeof InviteRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/auth-callback': {
|
||||
id: '/auth-callback'
|
||||
path: '/auth-callback'
|
||||
@@ -458,6 +478,7 @@ const ComplexSlugBookingRouteWithChildren =
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AppRouteRoute: AppRouteRouteWithChildren,
|
||||
AuthCallbackRoute: AuthCallbackRoute,
|
||||
InviteRoute: InviteRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
OnboardRoute: OnboardRouteWithChildren,
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
@@ -15,6 +16,7 @@ function AuthCallbackPage() {
|
||||
}
|
||||
|
||||
try {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
const complexes = await apiClient.complexes.listMine();
|
||||
|
||||
if (complexes.length === 1) {
|
||||
|
||||
51
apps/frontend/src/routes/invite.tsx
Normal file
51
apps/frontend/src/routes/invite.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { OnboardLoginPage } from '@/features/onboard/onboard-login-page';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { acceptStoredPendingInvite, setPendingInvite } from '@/lib/invitations';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
|
||||
const inviteSearchSchema = z.object({
|
||||
email: z.string().email().optional(),
|
||||
inviteToken: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
function InvitePage() {
|
||||
const navigate = useNavigate();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const search = Route.useSearch();
|
||||
|
||||
useEffect(() => {
|
||||
setPendingInvite({
|
||||
email: search.email ?? null,
|
||||
token: search.inviteToken ?? null,
|
||||
});
|
||||
}, [search.email, search.inviteToken]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||
await navigate({ to: '/' });
|
||||
})();
|
||||
}, [isAuthenticated, navigate]);
|
||||
|
||||
if (isAuthenticated) {
|
||||
return (
|
||||
<main className="flex min-h-screen w-full items-center justify-center px-6">
|
||||
<p className="text-sm text-muted-foreground">Aceptando invitación...</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return <OnboardLoginPage variant="invite" inviteEmail={search.email ?? null} />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/invite')({
|
||||
validateSearch: inviteSearchSchema,
|
||||
component: InvitePage,
|
||||
});
|
||||
@@ -117,6 +117,59 @@ export const complexUserRoleSchema = z.enum(['ADMIN', 'EMPLOYEE'])
|
||||
|
||||
export type ComplexUserRole = z.infer<typeof complexUserRoleSchema>
|
||||
|
||||
export const complexMemberSchema = z.object({
|
||||
userId: z.string(),
|
||||
fullName: z.string(),
|
||||
email: z.email(),
|
||||
avatarUrl: z.url(),
|
||||
role: complexUserRoleSchema,
|
||||
createdAt: z.string().datetime(),
|
||||
})
|
||||
|
||||
export type ComplexMember = z.infer<typeof complexMemberSchema>
|
||||
|
||||
export const complexInvitationStatusSchema = z.enum(['PENDING', 'ACCEPTED', 'REVOKED', 'EXPIRED'])
|
||||
|
||||
export type ComplexInvitationStatus = z.infer<typeof complexInvitationStatusSchema>
|
||||
|
||||
export const complexInvitationSchema = z.object({
|
||||
id: z.uuid(),
|
||||
complexId: z.uuid(),
|
||||
email: z.email(),
|
||||
status: complexInvitationStatusSchema,
|
||||
createdAt: z.string().datetime(),
|
||||
expiresAt: z.string().datetime(),
|
||||
acceptedAt: z.string().datetime().nullable(),
|
||||
revokedAt: z.string().datetime().nullable(),
|
||||
})
|
||||
|
||||
export type ComplexInvitation = z.infer<typeof complexInvitationSchema>
|
||||
|
||||
export const complexUsersOverviewSchema = z.object({
|
||||
members: z.array(complexMemberSchema),
|
||||
invitations: z.array(complexInvitationSchema),
|
||||
})
|
||||
|
||||
export type ComplexUsersOverview = z.infer<typeof complexUsersOverviewSchema>
|
||||
|
||||
export const inviteComplexUserSchema = z.object({
|
||||
email: z.email('El email debe ser válido.'),
|
||||
})
|
||||
|
||||
export type InviteComplexUserInput = z.infer<typeof inviteComplexUserSchema>
|
||||
|
||||
export const acceptComplexInvitationsSchema = z.object({
|
||||
inviteToken: z.string().min(1, 'El token de invitación no puede estar vacío.').optional(),
|
||||
})
|
||||
|
||||
export type AcceptComplexInvitationsInput = z.infer<typeof acceptComplexInvitationsSchema>
|
||||
|
||||
export const revokeComplexUserSchema = z.object({
|
||||
userId: z.string().min(1, 'El userId no puede estar vacío.'),
|
||||
})
|
||||
|
||||
export type RevokeComplexUserInput = z.infer<typeof revokeComplexUserSchema>
|
||||
|
||||
export const selectComplexSchema = z.object({
|
||||
complexId: z.string().uuid(),
|
||||
})
|
||||
@@ -138,3 +191,12 @@ export type CreateComplexPayload = CreateComplexInput
|
||||
export type CreateComplexResponse = Complex
|
||||
export type UpdateComplexPayload = UpdateComplexInput
|
||||
export type UpdateComplexResponse = Complex
|
||||
export type InviteComplexUserResponse = {
|
||||
invitation: ComplexInvitation
|
||||
}
|
||||
export type AcceptComplexInvitationsResponse = {
|
||||
acceptedCount: number
|
||||
}
|
||||
export type CancelComplexInvitationResponse = {
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
@@ -27,24 +27,41 @@ export type {
|
||||
OnboardingVerifyOtpResponse,
|
||||
} from './onboarding'
|
||||
export {
|
||||
acceptComplexInvitationsSchema,
|
||||
complexInvitationSchema,
|
||||
complexInvitationStatusSchema,
|
||||
complexMemberSchema,
|
||||
complexUsersOverviewSchema,
|
||||
complexSchema,
|
||||
complexUserRoleSchema,
|
||||
complexWithRoleSchema,
|
||||
createComplexSchema,
|
||||
inviteComplexUserSchema,
|
||||
revokeComplexUserSchema,
|
||||
selectComplexSchema,
|
||||
updateComplexSchema,
|
||||
} from './complex'
|
||||
export type {
|
||||
AcceptComplexInvitationsInput,
|
||||
AcceptComplexInvitationsResponse,
|
||||
CancelComplexInvitationResponse,
|
||||
Complex,
|
||||
ComplexInvitation,
|
||||
ComplexInvitationStatus,
|
||||
ComplexMember,
|
||||
ComplexUserRole,
|
||||
ComplexWithRole,
|
||||
CreateComplexInput,
|
||||
CreateComplexPayload,
|
||||
CreateComplexResponse,
|
||||
ComplexUsersOverview,
|
||||
SelectComplexInput,
|
||||
InviteComplexUserInput,
|
||||
InviteComplexUserResponse,
|
||||
UpdateComplexInput,
|
||||
UpdateComplexPayload,
|
||||
UpdateComplexResponse,
|
||||
RevokeComplexUserInput,
|
||||
} from './complex'
|
||||
export {
|
||||
dayOfWeekSchema,
|
||||
|
||||
Reference in New Issue
Block a user