updated living space added

This commit is contained in:
Berkay 2025-12-04 15:46:24 +03:00
parent 56b42bb906
commit 53e1f1e4fc
70 changed files with 1128 additions and 824 deletions

View File

@ -2,10 +2,12 @@ import { Module } from '@nestjs/common';
import { BuildIbanResolver } from './build-iban.resolver'; import { BuildIbanResolver } from './build-iban.resolver';
import { BuildIbanService } from './build-iban.service'; import { BuildIbanService } from './build-iban.service';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { BuildIban, BuildIbanSchema } from '@/models/build.model'; import { BuildIban, BuildIbanSchema, Build, BuildSchema } from '@/models/build.model';
@Module({ @Module({
imports: [MongooseModule.forFeature([{ name: BuildIban.name, schema: BuildIbanSchema }])], imports: [MongooseModule.forFeature([
{ name: BuildIban.name, schema: BuildIbanSchema }, { name: Build.name, schema: BuildSchema }
])],
providers: [BuildIbanResolver, BuildIbanService] providers: [BuildIbanResolver, BuildIbanService]
}) })
export class BuildIbanModule { } export class BuildIbanModule { }

View File

@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose'; import { Types, Model } from 'mongoose';
import { BuildIban, BuildIbanDocument } from '@/models/build.model'; import { Build, BuildDocument, BuildIban, BuildIbanDocument } from '@/models/build.model';
import { ListBuildIbanResponse } from './dto/list-build-ibans.response'; import { ListBuildIbanResponse } from './dto/list-build-ibans.response';
import { CreateBuildIbanInput } from './dto/create-build-ibans.input'; import { CreateBuildIbanInput } from './dto/create-build-ibans.input';
import { UpdateBuildIbanInput } from './dto/update-build-ibans.input'; import { UpdateBuildIbanInput } from './dto/update-build-ibans.input';
@ -9,10 +9,14 @@ import { UpdateBuildIbanInput } from './dto/update-build-ibans.input';
@Injectable() @Injectable()
export class BuildIbanService { export class BuildIbanService {
constructor(@InjectModel(BuildIban.name) private readonly buildIbanModel: Model<BuildIbanDocument>) { } constructor(
@InjectModel(BuildIban.name) private readonly buildIbanModel: Model<BuildIbanDocument>,
@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>
) { }
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildIbanResponse> { async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildIbanResponse> {
const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) }; const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
if (!!query?.buildId) { query.buildId = new Types.ObjectId(query?.buildId) };
const totalCount = await this.buildIbanModel.countDocuments(query).exec(); const totalCount = await this.buildIbanModel.countDocuments(query).exec();
const data = await this.buildIbanModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec(); const data = await this.buildIbanModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
return { data, totalCount }; return { data, totalCount };
@ -22,17 +26,21 @@ export class BuildIbanService {
return this.buildIbanModel.findById(id, projection, { lean: false }).populate({ path: 'buildIban', select: projection?.buildIban }).exec(); return this.buildIbanModel.findById(id, projection, { lean: false }).populate({ path: 'buildIban', select: projection?.buildIban }).exec();
} }
async create(input: CreateBuildIbanInput): Promise<BuildIbanDocument> { const buildIban = new this.buildIbanModel(input); return buildIban.save() } async create(input: CreateBuildIbanInput): Promise<BuildIbanDocument> {
const build = await this.buildModel.findOne({ _id: new Types.ObjectId(input.buildId) });
if (!build) { throw new Error('Build not found') }
const buildIban = new this.buildIbanModel({ ...input, buildId: build._id }); return buildIban.save()
}
async update(uuid: string, input: UpdateBuildIbanInput): Promise<BuildIbanDocument> { const buildIban = await this.buildIbanModel.findOne({ uuid }); if (!buildIban) { throw new Error('BuildIban not found') }; buildIban.set(input); return buildIban.save() } async update(uuid: string, input: UpdateBuildIbanInput): Promise<BuildIbanDocument> {
const buildIban = await this.buildIbanModel.findOne({ uuid }); if (!buildIban) { throw new Error('BuildIban not found') }; buildIban.set(input); return buildIban.save()
}
async delete(uuid: string): Promise<boolean> { const buildIban = await this.buildIbanModel.deleteMany({ uuid }); return buildIban.deletedCount > 0 } async delete(uuid: string): Promise<boolean> { const buildIban = await this.buildIbanModel.deleteMany({ uuid }); return buildIban.deletedCount > 0 }
buildProjection(fields: Record<string, any>): any { buildProjection(fields: Record<string, any>): any {
const projection: any = {}; const projection: any = {};
for (const key in fields) { for (const key in fields) { if (key === 'buildIban' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`buildIban.${subField}`] = 1 } } else { projection[key] = 1 } }; return projection;
if (key === 'buildIban' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`buildIban.${subField}`] = 1 } } else { projection[key] = 1 }
}; return projection;
} }
} }

View File

@ -4,6 +4,9 @@ import { InputType, Field } from "@nestjs/graphql";
@InputType() @InputType()
export class CreateBuildIbanInput extends ExpiryBaseInput { export class CreateBuildIbanInput extends ExpiryBaseInput {
@Field()
buildId: string;
@Field() @Field()
iban: string; iban: string;

View File

@ -0,0 +1,8 @@
import { randomBytes, createHash } from "crypto";
export function generateResetToken(length: number = 128) {
const resetToken = randomBytes(length).toString("hex");
const hashedToken = createHash("sha256").update(resetToken).digest("hex");
const expires = Date.now() + 1000 * 60 * 60 * 24 * 3;
return { resetToken, hashedToken, expires };
}

View File

@ -13,8 +13,8 @@ export class CreateLivingSpaceInput extends ExpiryBaseInput {
@Field() @Field()
userTypeID: string; userTypeID: string;
@Field() @Field({ nullable: true })
companyID: string; companyID?: string;
@Field() @Field()
personID: string; personID: string;

View File

@ -0,0 +1,12 @@
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class GetLivingSpaceInput {
@Field()
buildID: string;
@Field()
uuid: string;
}

View File

@ -4,11 +4,13 @@ import { LivingSpaceResolver } from './living-space.resolver';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { LivingSpaces, LivingSpacesSchema } from '@/models/living-spaces.model'; import { LivingSpaces, LivingSpacesSchema } from '@/models/living-spaces.model';
import { UserType, UserTypeSchema } from '@/models/user-type.model'; import { UserType, UserTypeSchema } from '@/models/user-type.model';
import { Build, BuildSchema } from '@/models/build.model';
@Module({ @Module({
imports: [MongooseModule.forFeature([ imports: [MongooseModule.forFeature([
{ name: LivingSpaces.name, schema: LivingSpacesSchema }, { name: LivingSpaces.name, schema: LivingSpacesSchema },
{ name: UserType.name, schema: UserTypeSchema }, { name: UserType.name, schema: UserTypeSchema },
{ name: Build.name, schema: BuildSchema },
])], ])],
providers: [LivingSpaceService, LivingSpaceResolver] providers: [LivingSpaceService, LivingSpaceResolver]
}) })

View File

@ -8,6 +8,7 @@ import { UpdateLivingSpaceInput } from './dto/update-living-space.input';
import { LivingSpaceService } from './living-space.service'; import { LivingSpaceService } from './living-space.service';
import type { GraphQLResolveInfo } from 'graphql'; import type { GraphQLResolveInfo } from 'graphql';
import graphqlFields from 'graphql-fields'; import graphqlFields from 'graphql-fields';
import { GetLivingSpaceInput } from './dto/get-living-space.input';
@Resolver() @Resolver()
export class LivingSpaceResolver { export class LivingSpaceResolver {
@ -25,6 +26,9 @@ export class LivingSpaceResolver {
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields); return this.livingSpaceService.findById(buildID, new Types.ObjectId(id), projection); const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields); return this.livingSpaceService.findById(buildID, new Types.ObjectId(id), projection);
} }
@Query(() => LivingSpaces, { name: 'getLivingSpaceDetail', nullable: true })
async getLivingSpaceDetail(@Args('uuid') uuid: string, @Args('buildID') buildID: string): Promise<LivingSpaces | null> { return this.livingSpaceService.getDetail(buildID, uuid) }
@Mutation(() => LivingSpaces, { name: 'createLivingSpace' }) @Mutation(() => LivingSpaces, { name: 'createLivingSpace' })
async createLivingSpace(@Args('input') input: CreateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.create(input) } async createLivingSpace(@Args('input') input: CreateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.create(input) }

View File

@ -6,6 +6,7 @@ import { CreateLivingSpaceInput } from './dto/create-living-space.input';
import { UpdateLivingSpaceInput } from './dto/update-living-space.input'; import { UpdateLivingSpaceInput } from './dto/update-living-space.input';
import { InjectConnection, InjectModel } from '@nestjs/mongoose'; import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { UserTypeDocument } from '@/models/user-type.model'; import { UserTypeDocument } from '@/models/user-type.model';
import { BuildDocument } from '@/models/build.model';
interface UpdateInput { interface UpdateInput {
userType?: Types.ObjectId; userType?: Types.ObjectId;
@ -21,17 +22,30 @@ export class LivingSpaceService {
constructor( constructor(
@InjectConnection() private readonly connection: Connection, @InjectConnection() private readonly connection: Connection,
@InjectModel('UserType') private readonly userTypeModel: Model<UserTypeDocument> @InjectModel('UserType') private readonly userTypeModel: Model<UserTypeDocument>,
@InjectModel('Build') private readonly buildModel: Model<BuildDocument>
) { } ) { }
async findAll(buildID: string, projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListLivingSpaceResponse> { async findAll(buildID: string, projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListLivingSpaceResponse> {
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) }; const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
const totalCount = await selectedModel.countDocuments(query).exec(); const totalCount = await selectedModel.countDocuments(query).exec();
const data = await selectedModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec(); const data = await selectedModel.find(query, projection, { lean: false })
.populate({ path: 'build', select: { ...projection?.build, _id: 0 } })
.populate({ path: 'person', select: { ...projection?.person, _id: 0 } })
.populate({ path: 'company', select: { ...projection?.company, _id: 0 } })
.populate({ path: 'userType', select: { ...projection?.userType, _id: 0 } })
.populate({ path: 'part', select: { ...projection?.part, _id: 0 } })
.skip(skip).limit(limit).sort(sort).exec();
return { data, totalCount }; return { data, totalCount };
} }
async getDetail(buildID: string, uuid: string): Promise<any | null> {
const buildObjectID = new Types.ObjectId(buildID); const build = await this.buildModel.findById(buildObjectID); if (!build) { throw new Error('Build not found') };
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const data = await selectedModel.findOne({ uuid }, { lean: false }).exec();
if (!data) { throw new Error('Living space not found') }; return data;
}
async findById(buildID: string, id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> { async findById(buildID: string, id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> {
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
return selectedModel.findById(id, projection, { lean: false }).populate({ path: 'company', select: projection?.company }).exec(); return selectedModel.findById(id, projection, { lean: false }).populate({ path: 'company', select: projection?.company }).exec();
@ -42,7 +56,7 @@ export class LivingSpaceService {
const LivingSpaceModel = getDynamicLivingSpaceModel(input.buildID, this.connection); const LivingSpaceModel = getDynamicLivingSpaceModel(input.buildID, this.connection);
const docInput: Partial<LivingSpacesDocument> = { const docInput: Partial<LivingSpacesDocument> = {
build: new Types.ObjectId(input.buildID), part: new Types.ObjectId(input.partID), userType: new Types.ObjectId(input.userTypeID), build: new Types.ObjectId(input.buildID), part: new Types.ObjectId(input.partID), userType: new Types.ObjectId(input.userTypeID),
company: new Types.ObjectId(input.companyID), person: new Types.ObjectId(input.personID), company: !!input.companyID ? new Types.ObjectId(input.companyID) : undefined, person: new Types.ObjectId(input.personID),
expiryStarts: input.expiryStarts ? new Date(input.expiryStarts) : new Date(), expiryEnds: input.expiryEnds ? new Date(input.expiryEnds) : new Date('2099-12-31'), expiryStarts: input.expiryStarts ? new Date(input.expiryStarts) : new Date(), expiryEnds: input.expiryEnds ? new Date(input.expiryEnds) : new Date('2099-12-31'),
}; const doc = new LivingSpaceModel(docInput); return await doc.save() }; const doc = new LivingSpaceModel(docInput); return await doc.save()
} }
@ -51,10 +65,10 @@ export class LivingSpaceService {
if (!buildID) { throw new Error('Build ID is required') } if (!buildID) { throw new Error('Build ID is required') }
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
const livingSpace = await selectedModel.findOne({ uuid }); const userTypeSelected = await this.userTypeModel.findById(new Types.ObjectId(input.userTypeID)).exec(); const newInput: UpdateInput = {} const livingSpace = await selectedModel.findOne({ uuid }); const userTypeSelected = await this.userTypeModel.findById(new Types.ObjectId(input.userTypeID)).exec(); const newInput: UpdateInput = {}
if (userTypeSelected?.isProperty) { if (input?.partID) { newInput.part = new Types.ObjectId(input.partID) } } else { newInput.part = null } if (userTypeSelected?.isProperty) { if (!!input?.partID) { newInput.part = new Types.ObjectId(input.partID) } } else { newInput.part = null }
if (input?.companyID) { newInput.company = new Types.ObjectId(input.companyID) } if (!!input?.companyID) { newInput.company = new Types.ObjectId(input.companyID) }
if (input?.personID) { newInput.person = new Types.ObjectId(input.personID) }; if (input?.userTypeID) { newInput.userType = new Types.ObjectId(input.userTypeID) } if (!!input?.personID) { newInput.person = new Types.ObjectId(input.personID) }; if (!!input?.userTypeID) { newInput.userType = new Types.ObjectId(input.userTypeID) }
if (input?.expiryStarts) { newInput.expiryStarts = input.expiryStarts }; if (input?.expiryEnds) { newInput.expiryEnds = input.expiryEnds } if (!!input?.expiryStarts) { newInput.expiryStarts = input.expiryStarts }; if (!!input?.expiryEnds) { newInput.expiryEnds = input.expiryEnds }
if (!livingSpace) { throw new Error('Company not found') }; livingSpace.set(newInput); return livingSpace.save(); if (!livingSpace) { throw new Error('Company not found') }; livingSpace.set(newInput); return livingSpace.save();
} }

View File

@ -10,9 +10,17 @@ export class BuildParts extends Base {
@Field(() => ID) @Field(() => ID)
readonly _id: string; readonly _id: string;
@Field(() => ID) @Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'Build', required: true }) @Prop({ type: Types.ObjectId, ref: 'Build', required: false })
buildId: Types.ObjectId; buildId?: Types.ObjectId;
@Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
directionId?: Types.ObjectId;
@Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
typeId?: Types.ObjectId;
@Field() @Field()
@Prop({ required: true }) @Prop({ required: true })
@ -50,14 +58,6 @@ export class BuildParts extends Base {
@Prop({ required: true }) @Prop({ required: true })
key: string; key: string;
@Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
directionId: Types.ObjectId;
@Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
typeId: Types.ObjectId;
} }
export type BuildPartsDocument = BuildParts & Document; export type BuildPartsDocument = BuildParts & Document;

View File

@ -2,8 +2,6 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose'; import { Document, Types } from 'mongoose';
import { ObjectType, Field, ID, Int } from '@nestjs/graphql'; import { ObjectType, Field, ID, Int } from '@nestjs/graphql';
import { Base, CreatedBase } from '@/models/base.model'; import { Base, CreatedBase } from '@/models/base.model';
import { Person } from '@/models/person.model';
import { Company } from '@/models/company.model';
import { BuildTypes } from './build-types.model'; import { BuildTypes } from './build-types.model';
@ObjectType() @ObjectType()
@ -13,6 +11,10 @@ export class BuildIban extends Base {
@Field(() => ID) @Field(() => ID)
readonly _id: string; readonly _id: string;
@Field(() => ID, { nullable: true })
@Prop({ type: Types.ObjectId, ref: 'Build', required: false })
buildId?: Types.ObjectId;
@Field() @Field()
@Prop({ required: true }) @Prop({ required: true })
iban: string; iban: string;
@ -144,6 +146,7 @@ export class Build extends CreatedBase {
@Prop({ type: [String], default: [] }) @Prop({ type: [String], default: [] })
areas?: string[]; areas?: string[];
// collect String(ObjectID) to
@Field(() => [String], { nullable: true, defaultValue: [] }) @Field(() => [String], { nullable: true, defaultValue: [] })
@Prop({ type: [String], default: [] }) @Prop({ type: [String], default: [] })
ibans?: string[]; ibans?: string[];

View File

@ -8,7 +8,6 @@ import { Person } from '@/models/person.model';
import { Company } from '@/models/company.model'; import { Company } from '@/models/company.model';
import { UserType } from '@/models/user-type.model'; import { UserType } from '@/models/user-type.model';
@ObjectType() @ObjectType()
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class LivingSpaces extends Base { export class LivingSpaces extends Base {
@ -16,23 +15,23 @@ export class LivingSpaces extends Base {
@Field(() => ID) @Field(() => ID)
readonly _id: string readonly _id: string
@Field(() => ID) @Field(() => Build)
@Prop({ type: Types.ObjectId, ref: Build.name, required: true }) @Prop({ type: Types.ObjectId, ref: Build.name, required: true })
build: Types.ObjectId; build: Types.ObjectId;
@Field(() => ID, { nullable: true }) @Field(() => BuildParts, { nullable: true })
@Prop({ type: Types.ObjectId, ref: BuildParts.name, required: false }) @Prop({ type: Types.ObjectId, ref: BuildParts.name, required: false })
part?: Types.ObjectId | null; part?: Types.ObjectId | null;
@Field(() => ID) @Field(() => UserType)
@Prop({ type: Types.ObjectId, ref: UserType.name, required: true }) @Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
userType: Types.ObjectId; userType: Types.ObjectId;
@Field(() => ID) @Field(() => Company, { nullable: true })
@Prop({ type: Types.ObjectId, ref: Company.name, required: true }) @Prop({ type: Types.ObjectId, ref: Company.name, required: false })
company: Types.ObjectId; company?: Types.ObjectId;
@Field(() => ID) @Field(() => Person)
@Prop({ type: Types.ObjectId, ref: Person.name, required: true }) @Prop({ type: Types.ObjectId, ref: Person.name, required: true })
person: Types.ObjectId; person: Types.ObjectId;

View File

@ -3,6 +3,7 @@ import { ObjectType, Field, ID } from '@nestjs/graphql';
import { Document, Types } from 'mongoose'; import { Document, Types } from 'mongoose';
import { Base } from '@/models/base.model'; import { Base } from '@/models/base.model';
import { Person } from '@/models/person.model'; import { Person } from '@/models/person.model';
import { generateResetToken } from '@/lib/generateToken';
@ObjectType() @ObjectType()
export class CollectionToken { export class CollectionToken {
@ -35,12 +36,12 @@ export class User extends Base {
expiresAt?: Date; expiresAt?: Date;
@Field({ nullable: true }) @Field({ nullable: true })
@Prop() @Prop({ required: false, default: () => generateResetToken().hashedToken })
resetToken?: string; resetToken?: string;
@Field() @Field({ nullable: true })
@Prop({ required: true }) @Prop({ required: false, default: '' })
password: string; password?: string;
@Field(() => [String], { nullable: 'itemsAndList' }) @Field(() => [String], { nullable: 'itemsAndList' })
@Prop({ type: [String], default: [], validate: [(val: string[]) => val.length <= 3, 'History can have max 3 items'] }) @Prop({ type: [String], default: [], validate: [(val: string[]) => val.length <= 3, 'History can have max 3 items'] })

View File

@ -20,11 +20,8 @@ export class CreateUserInput {
@Field({ nullable: true }) @Field({ nullable: true })
avatar?: string; avatar?: string;
@Field() // @Field()
password: string; // password: string;
@Field(() => [String], { nullable: true })
history?: string[];
@Field() @Field()
tag: string; tag: string;

View File

@ -6,8 +6,9 @@ mutation {
email: "test@example.com", email: "test@example.com",
phone: "555123456", phone: "555123456",
collectionTokens: { collectionTokens: {
default: "default-token", defaultSelection: "default-token",
tokens: [{ prefix: "main", token: "abc123" }] selectedBuildIDS: ["64f8b2a4e1234567890abcdef"],
selectedCompanyIDS: ["64f8b2a4e1234567890abcdef"]
}, },
person: "64f8b2a4e1234567890abcdef" person: "64f8b2a4e1234567890abcdef"
}) { }) {
@ -18,11 +19,9 @@ mutation {
phone phone
tag tag
collectionTokens { collectionTokens {
default defaultSelection
tokens { selectedBuildIDS
prefix selectedCompanyIDS
token
}
} }
person person
} }

View File

@ -8,6 +8,9 @@ const endpoint = "http://localhost:3001/graphql";
export async function POST(request: Request) { export async function POST(request: Request) {
const body = await request.json(); const body = await request.json();
const validatedBody = buildIbansAddSchema.parse(body); const validatedBody = buildIbansAddSchema.parse(body);
const url = new URL(request.url)
const buildID = url.searchParams.get('build');
if (!buildID) { return NextResponse.json({ error: 'Build ID is required' }, { status: 400 }) }
try { try {
const client = new GraphQLClient(endpoint); const client = new GraphQLClient(endpoint);
const query = gql` const query = gql`
@ -22,7 +25,7 @@ export async function POST(request: Request) {
} }
} }
`; `;
const variables = { input: validatedBody }; const variables = { input: { ...validatedBody, buildId: buildID } };
const data = await client.request(query, variables); const data = await client.request(query, variables);
return NextResponse.json({ data: data.createBuildIban, status: 200 }); return NextResponse.json({ data: data.createBuildIban, status: 200 });
} catch (err: any) { } catch (err: any) {

View File

@ -0,0 +1,37 @@
'use server';
import { NextResponse } from 'next/server';
import { GraphQLClient, gql } from 'graphql-request';
const endpoint = "http://localhost:3001/graphql";
export async function POST(request: Request) {
const body = await request.json();
const { uuid, buildID } = body;
try {
const client = new GraphQLClient(endpoint);
const query = gql`
query GetLivingSpaceDetail($uuid: String!, $buildID: String!) {
getLivingSpaceDetail(uuid: $uuid, buildID: $buildID) {
_id
company {_id}
userType {_id}
build {_id}
person {_id}
part {_id}
}
}
`;
const variables = { uuid, buildID };
const data = await client.request(query, variables);
if (!data?.getLivingSpaceDetail) { return NextResponse.json({ error: 'Living space not found' }, { status: 404 }) };
return NextResponse.json({
data: {
_id: data.getLivingSpaceDetail._id, company: data.getLivingSpaceDetail?.company?._id, userType: data.getLivingSpaceDetail.userType._id,
build: data.getLivingSpaceDetail.build._id, person: data.getLivingSpaceDetail.person._id, part: data.getLivingSpaceDetail.part._id,
}
});
} catch (err: any) {
console.error(err);
return NextResponse.json({ error: err.message }, { status: 500 });
}
}

View File

@ -0,0 +1,43 @@
'use server';
import { NextResponse } from 'next/server';
import { GraphQLClient, gql } from 'graphql-request';
const endpoint = "http://localhost:3001/graphql";
export async function POST(request: Request) {
const body = await request.json();
const { limit, skip, sort, filters, buildID } = body;
try {
const client = new GraphQLClient(endpoint);
const query = gql`
query GetLivingSpaces($input: ListArguments!, $buildID: String!) {
getLivingSpaces(input: $input, buildID: $buildID) {
data {
_id
uuid
build
part
userType
company
person
isNotificationSend
expiryEnds
expiryStarts
createdAt
updatedAt
isConfirmed
deleted
}
totalCount
}
}
`;
const variables = { input: { limit, skip, sort, filters }, buildID };
const data = await client.request(query, variables);
return NextResponse.json({ data: data.getLivingSpaces.data, totalCount: data.getLivingSpaces.totalCount });
} catch (err: any) {
console.error(err);
return NextResponse.json({ error: err.message }, { status: 500 });
}
}

View File

@ -10,24 +10,40 @@ export async function POST(request: Request) {
try { try {
const client = new GraphQLClient(endpoint); const client = new GraphQLClient(endpoint);
const query = gql` const query = gql`
query GetLivingSpaces($input: ListArguments!, $buildID: String!) { query GetLivingSpaces($buildID: String!, $input: ListArguments!) {
getLivingSpaces(input: $input, buildID: $buildID) { getLivingSpaces(buildID: $buildID, input: $input) {
data { data {
_id _id
uuid uuid
build
part
userType
company
person
isNotificationSend
expiryEnds
expiryStarts
createdAt createdAt
updatedAt updatedAt
isConfirmed expiryStarts
deleted expiryEnds
build {
info {
buildName
buildNo
}
}
part {
no
level
humanLivability
}
person {
firstName
middleName
surname
birthDate
birthPlace
}
userType {
isProperty
description
}
company {
uuid
}
} }
totalCount totalCount
} }

View File

@ -10,7 +10,6 @@ export async function POST(request: Request) {
console.log("BODY") console.log("BODY")
console.dir({ body }) console.dir({ body })
const validatedBody = userAddSchema.parse(body); const validatedBody = userAddSchema.parse(body);
validatedBody.person = "6917732face2287b1d901738"
try { try {
const client = new GraphQLClient(endpoint); const client = new GraphQLClient(endpoint);
const query = gql` const query = gql`
@ -21,12 +20,11 @@ export async function POST(request: Request) {
tag tag
email email
phone phone
tag
collectionTokens { collectionTokens {
default defaultSelection
tokens { selectedBuildIDS
prefix selectedCompanyIDS
token
}
} }
person person
} }

View File

@ -1,29 +1,21 @@
import { z } from "zod" import { z } from "zod"
export const tokenSchema = z.object({
prefix: z.string().min(1, "Prefix is required"),
token: z.string().min(1, "Token is required"),
})
export const collectionTokensSchema = z.object({
default: z.string().optional(),
tokens: z.array(tokenSchema)
})
export const userAddSchema = z.object({ export const userAddSchema = z.object({
expiryStarts: z.string().optional(), expiryStarts: z.string().optional(),
expiryEnds: z.string().optional(), expiryEnds: z.string().optional(),
isConfirmed: z.boolean(), isConfirmed: z.boolean(),
isNotificationSend: z.boolean(), isNotificationSend: z.boolean(),
password: z.string().min(6),
tag: z.string().optional(), tag: z.string().optional(),
email: z.string().email(), email: z.string().email(),
phone: z.string().min(5), phone: z.string().min(5),
person: z.string().optional(), person: z.string(),
collectionTokens: z.object({
defaultSelection: z.string(),
selectedBuildIDS: z.array(z.string()),
selectedCompanyIDS: z.array(z.string()),
}).optional()
collectionTokens: collectionTokensSchema,
}) })
export type UserAdd = z.infer<typeof userAddSchema> export type UserAdd = z.infer<typeof userAddSchema>

View File

@ -36,12 +36,11 @@ export async function POST(request: Request) {
tag tag
email email
phone phone
person
collectionTokens { collectionTokens {
default defaultSelection
tokens { selectedBuildIDS
prefix selectedCompanyIDS
token
}
} }
createdAt createdAt
updatedAt updatedAt

View File

@ -1,28 +1,20 @@
import { z } from "zod" import { z } from "zod"
export const tokenSchema = z.object({
prefix: z.string().min(1, "Prefix is required").optional(),
token: z.string().min(1, "Token is required").optional(),
})
export const collectionTokensSchema = z.object({
default: z.string().optional(),
tokens: z.array(tokenSchema).optional()
})
export const userUpdateSchema = z.object({ export const userUpdateSchema = z.object({
expiryStarts: z.string().optional(), expiryStarts: z.string().optional(),
expiryEnds: z.string().optional(), expiryEnds: z.string().optional(),
isConfirmed: z.boolean(),
isConfirmed: z.boolean().optional(), isNotificationSend: z.boolean(),
isNotificationSend: z.boolean().optional(),
tag: z.string().optional(), tag: z.string().optional(),
email: z.string().email().optional(), email: z.string().email(),
phone: z.string().min(5).optional(), phone: z.string().min(5),
person: z.string().optional(), person: z.string(),
collectionTokens: z.object({
collectionTokens: collectionTokensSchema, defaultSelection: z.string(),
selectedBuildIDS: z.array(z.string()),
selectedCompanyIDS: z.array(z.string()),
}).optional()
}) })
export type UserUpdate = z.infer<typeof userUpdateSchema> export type UserUpdate = z.infer<typeof userUpdateSchema>

View File

@ -62,11 +62,11 @@ const data = {
url: "/build-address", url: "/build-address",
icon: IconAddressBook icon: IconAddressBook
}, },
{ // {
title: "Build Sites", // title: "Build Sites",
url: "/build-sites", // url: "/build-sites",
icon: IconMessageCircle // icon: IconMessageCircle
}, // },
{ {
title: "Build Areas", title: "Build Areas",
url: "/build-areas", url: "/build-areas",

View File

@ -9,35 +9,20 @@ import { DateTimePicker } from "@/components/ui/date-time-picker"
import { BuildIbansAdd, buildIbansAddSchema } from "./schema" import { BuildIbansAdd, buildIbansAddSchema } from "./schema"
import { useAddBuildIbansMutation } from "./queries" import { useAddBuildIbansMutation } from "./queries"
const BuildIbansForm = ({ refetchTable }: { refetchTable: () => void }) => { const BuildIbansForm = ({ refetchTable, buildId }: { refetchTable: () => void, buildId: string }) => {
const form = useForm<BuildIbansAdd>({ const form = useForm<BuildIbansAdd>({
resolver: zodResolver(buildIbansAddSchema), resolver: zodResolver(buildIbansAddSchema), defaultValues: { iban: "", startDate: "", stopDate: "", bankCode: "", xcomment: "", expiryStarts: "", expiryEnds: "" },
defaultValues: {
iban: "",
startDate: "",
stopDate: "",
bankCode: "",
xcomment: "",
expiryStarts: "",
expiryEnds: "",
},
}); });
const { handleSubmit } = form; const { handleSubmit } = form;
const mutation = useAddBuildIbansMutation(); const mutation = useAddBuildIbansMutation();
function onSubmit(values: BuildIbansAdd) { mutation.mutate({ data: values, buildId, refetchTable }) };
function onSubmit(values: BuildIbansAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
return ( return (
<Form {...form}> <Form {...form}>
<form <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4" >
onSubmit={handleSubmit(onSubmit)}
className="space-y-6 p-4"
>
{/* ROW 1 */}
{/* ROW 1 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField <FormField
control={form.control} control={form.control}

View File

@ -3,6 +3,8 @@ import { useState } from 'react';
import { BuildIbansDataTableAdd } from './table/data-table'; import { BuildIbansDataTableAdd } from './table/data-table';
import { BuildIbansForm } from './form'; import { BuildIbansForm } from './form';
import { useGraphQlBuildIbansList } from '../queries'; import { useGraphQlBuildIbansList } from '../queries';
import { useSearchParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
const PageAddBuildIbans = () => { const PageAddBuildIbans = () => {
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
@ -10,14 +12,19 @@ const PageAddBuildIbans = () => {
const [sort, setSort] = useState({ createdAt: 'desc' }); const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({}); const [filters, setFilters] = useState({});
const { data, isLoading, error, refetch } = useGraphQlBuildIbansList({ limit, skip: (page - 1) * limit, sort, filters }); const searchParams = useSearchParams();
const router = useRouter();
const buildId = searchParams?.get('build');
const { data, isLoading, error, refetch } = useGraphQlBuildIbansList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId } });
const noUUIDFound = <>
<div>Back To Build IBANs. No uuid is found on headers</div>
<Button onClick={() => router.push(`/build-ibans?build=${buildId}`)}>Back to Build IBANs</Button>
</>
if (!buildId) { return noUUIDFound }
return ( return (
<> <>
<BuildIbansDataTableAdd <BuildIbansDataTableAdd data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} buildId={buildId} />
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} <BuildIbansForm refetchTable={refetch} buildId={buildId} />
/>
<BuildIbansForm refetchTable={refetch} />
</> </>
) )
} }

View File

@ -3,7 +3,7 @@ import { useMutation } from '@tanstack/react-query'
import { toISOIfNotZ } from '@/lib/utils'; import { toISOIfNotZ } from '@/lib/utils';
import { BuildIbansAdd } from './schema'; import { BuildIbansAdd } from './schema';
const fetchGraphQlBuildIbansAdd = async (record: BuildIbansAdd): Promise<{ data: BuildIbansAdd | null; status: number }> => { const fetchGraphQlBuildIbansAdd = async (record: BuildIbansAdd, buildId: string, refetchTable: () => void): Promise<{ data: BuildIbansAdd | null; status: number }> => {
console.log('Fetching test data from local API'); console.log('Fetching test data from local API');
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined; record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined; record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
@ -11,16 +11,16 @@ const fetchGraphQlBuildIbansAdd = async (record: BuildIbansAdd): Promise<{ data:
record.stopDate = toISOIfNotZ(record.stopDate); record.stopDate = toISOIfNotZ(record.stopDate);
console.dir({ record }) console.dir({ record })
try { try {
const res = await fetch('/api/build-ibans/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) }); const res = await fetch(`/api/build-ibans/add?build=${buildId}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) } if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json(); const data = await res.json(); refetchTable();
return { data: data.data, status: res.status } return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error } } catch (error) { console.error('Error fetching test data:', error); throw error }
}; };
export function useAddBuildIbansMutation() { export function useAddBuildIbansMutation() {
return useMutation({ return useMutation({
mutationFn: ({ data }: { data: BuildIbansAdd }) => fetchGraphQlBuildIbansAdd(data), mutationFn: ({ data, buildId, refetchTable }: { data: BuildIbansAdd, buildId: string, refetchTable: () => void }) => fetchGraphQlBuildIbansAdd(data, buildId, refetchTable),
onSuccess: () => { console.log("Build IBANs created successfully") }, onSuccess: () => { console.log("Build IBANs created successfully") },
onError: (error) => { console.error("Add build IBANs failed:", error) }, onError: (error) => { console.error("Add build IBANs failed:", error) },
}) })

View File

@ -55,6 +55,7 @@ export function BuildIbansDataTableAdd({
onPageChange, onPageChange,
onPageSizeChange, onPageSizeChange,
refetchTable, refetchTable,
buildId
}: { }: {
data: schemaType[], data: schemaType[],
totalCount: number, totalCount: number,
@ -62,7 +63,8 @@ export function BuildIbansDataTableAdd({
pageSize: number, pageSize: number,
onPageChange: (page: number) => void, onPageChange: (page: number) => void,
onPageSizeChange: (size: number) => void, onPageSizeChange: (size: number) => void,
refetchTable: () => void refetchTable: () => void,
buildId: string
}) { }) {
const router = useRouter(); const router = useRouter();
@ -142,9 +144,8 @@ export function BuildIbansDataTableAdd({
})} })}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
<Button variant="outline" size="sm" onClick={() => { router.push("/build-ibans") }}> <Button variant="outline" size="sm" onClick={() => { router.push(`/build-ibans?build=${buildId}`) }}>
<Home /> <Home /><span className="hidden lg:inline">Back to Build IBANs</span>
<span className="hidden lg:inline">Back to Build IBANs</span>
</Button> </Button>
</div> </div>
</div> </div>

View File

@ -78,7 +78,8 @@ export function BuildIbansDataTable({
pageSize = 10, pageSize = 10,
onPageChange, onPageChange,
onPageSizeChange, onPageSizeChange,
refetchTable refetchTable,
buildId
}: { }: {
data: schemaType[], data: schemaType[],
totalCount: number, totalCount: number,
@ -87,6 +88,7 @@ export function BuildIbansDataTable({
onPageChange: (page: number) => void, onPageChange: (page: number) => void,
onPageSizeChange: (size: number) => void, onPageSizeChange: (size: number) => void,
refetchTable: () => void, refetchTable: () => void,
buildId: string
}) { }) {
const router = useRouter(); const router = useRouter();
@ -163,7 +165,7 @@ export function BuildIbansDataTable({
})} })}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
<Button variant="outline" size="sm" onClick={() => { router.push("/build-ibans/add") }}> <Button variant="outline" size="sm" onClick={() => { router.push(`/build-ibans/add?build=${buildId}`) }}>
<IconPlus /> <IconPlus />
<span className="hidden lg:inline">Add Build Iban</span> <span className="hidden lg:inline">Add Build Iban</span>
</Button> </Button>

View File

@ -2,6 +2,8 @@
import { BuildIbansDataTable } from './list/data-table'; import { BuildIbansDataTable } from './list/data-table';
import { useState } from 'react'; import { useState } from 'react';
import { useGraphQlBuildIbansList } from './queries'; import { useGraphQlBuildIbansList } from './queries';
import { useSearchParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
const PageBuildIbans = () => { const PageBuildIbans = () => {
@ -10,7 +12,11 @@ const PageBuildIbans = () => {
const [sort, setSort] = useState({ createdAt: 'desc' }); const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({}); const [filters, setFilters] = useState({});
const { data, isLoading, error, refetch } = useGraphQlBuildIbansList({ limit, skip: (page - 1) * limit, sort, filters }); const searchParams = useSearchParams();
const router = useRouter();
const buildId = searchParams?.get('build');
const { data, isLoading, error, refetch } = useGraphQlBuildIbansList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId } });
const handlePageChange = (newPage: number) => { setPage(newPage) }; const handlePageChange = (newPage: number) => { setPage(newPage) };
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) }; const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
@ -18,7 +24,12 @@ const PageBuildIbans = () => {
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> } if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading build areas</div> } if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading build areas</div> }
return <BuildIbansDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />; const noUUIDFound = <>
<div>Back To Builds. No uuid is found on headers</div>
<Button onClick={() => router.push('/builds')}>Back to Builds</Button>
</>
if (!buildId) { return noUUIDFound }
return <BuildIbansDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} />;
}; };

View File

@ -12,12 +12,9 @@ import { BuildIbansUpdate, buildIbansUpdateSchema } from "@/pages/build-ibans/up
const BuildIbansForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: BuildIbansUpdate, selectedUuid: string }) => { const BuildIbansForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: BuildIbansUpdate, selectedUuid: string }) => {
const form = useForm<BuildIbansUpdate>({ resolver: zodResolver(buildIbansUpdateSchema), defaultValues: { ...initData } }) const form = useForm<BuildIbansUpdate>({ resolver: zodResolver(buildIbansUpdateSchema), defaultValues: { ...initData } })
const { handleSubmit } = form const { handleSubmit } = form
const mutation = useUpdateBuildIbansMutation(); const mutation = useUpdateBuildIbansMutation();
function onSubmit(values: BuildIbansUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, refetchTable }) }
function onSubmit(values: BuildIbansUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 400) }
return ( return (
<Form {...form}> <Form {...form}>

View File

@ -24,10 +24,7 @@ const PageUpdateBuildIbans = () => {
if (!initData) { return backToBuildAddress } if (!initData) { return backToBuildAddress }
return ( return (
<> <>
<BuildIbansDataTableUpdate <BuildIbansDataTableUpdate data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} />
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
/>
<BuildIbansForm refetchTable={refetch} initData={initData} selectedUuid={uuid} /> <BuildIbansForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
</> </>
) )

View File

@ -3,23 +3,22 @@ import { useMutation } from '@tanstack/react-query'
import { UpdateBuildIbansUpdate } from './types'; import { UpdateBuildIbansUpdate } from './types';
import { toISOIfNotZ } from '@/lib/utils'; import { toISOIfNotZ } from '@/lib/utils';
const fetchGraphQlBuildIbansUpdate = async (record: UpdateBuildIbansUpdate, uuid: string): Promise<{ data: UpdateBuildIbansUpdate | null; status: number }> => { const fetchGraphQlBuildIbansUpdate = async (record: UpdateBuildIbansUpdate, uuid: string, refetchTable: () => void): Promise<{ data: UpdateBuildIbansUpdate | null; status: number }> => {
console.log('Fetching test data from local API'); console.log('Fetching test data from local API');
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined; record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined; record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
record.startDate = toISOIfNotZ(record.startDate); record.startDate = toISOIfNotZ(record.startDate); record.stopDate = toISOIfNotZ(record.stopDate);
record.stopDate = toISOIfNotZ(record.stopDate);
try { try {
const res = await fetch(`/api/build-ibans/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) }); const res = await fetch(`/api/build-ibans/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) } if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json(); const data = await res.json(); refetchTable();
return { data: data.data, status: res.status } return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error } } catch (error) { console.error('Error fetching test data:', error); throw error }
}; };
export function useUpdateBuildIbansMutation() { export function useUpdateBuildIbansMutation() {
return useMutation({ return useMutation({
mutationFn: ({ data, uuid }: { data: UpdateBuildIbansUpdate, uuid: string }) => fetchGraphQlBuildIbansUpdate(data, uuid), mutationFn: ({ data, uuid, refetchTable }: { data: UpdateBuildIbansUpdate, uuid: string, refetchTable: () => void }) => fetchGraphQlBuildIbansUpdate(data, uuid, refetchTable),
onSuccess: () => { console.log("Build IBANs updated successfully") }, onSuccess: () => { console.log("Build IBANs updated successfully") },
onError: (error) => { console.error("Update Build IBANs failed:", error) }, onError: (error) => { console.error("Update Build IBANs failed:", error) },
}) })

View File

@ -87,7 +87,7 @@ export function BuildIbansDataTableUpdate({
pageSize: number, pageSize: number,
onPageChange: (page: number) => void, onPageChange: (page: number) => void,
onPageSizeChange: (size: number) => void, onPageSizeChange: (size: number) => void,
refetchTable: () => void refetchTable: () => void,
}) { }) {
const router = useRouter(); const router = useRouter();
@ -100,7 +100,7 @@ export function BuildIbansDataTableUpdate({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data]) const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeletePersonMutation() const deleteMutation = useDeletePersonMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) } const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
const columns = getColumns(router, deleteHandler); const columns = getColumns(router, deleteHandler);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize]) const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize) const totalPages = Math.ceil(totalCount / pageSize)
@ -167,7 +167,7 @@ export function BuildIbansDataTableUpdate({
})} })}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
<Button variant="outline" size="sm" onClick={() => { router.push("/build-ibans") }}> <Button variant="outline" size="sm" onClick={() => { router.push(`/build-ibans`) }}>
<Home /> <Home />
<span className="hidden lg:inline">Back to Build IBANs</span> <span className="hidden lg:inline">Back to Build IBANs</span>
</Button> </Button>

View File

@ -25,6 +25,7 @@ import {
IconChevronRight, IconChevronRight,
IconChevronsLeft, IconChevronsLeft,
IconChevronsRight, IconChevronsRight,
IconCreditCard,
IconLayoutColumns, IconLayoutColumns,
IconPlus, IconPlus,
} from "@tabler/icons-react" } from "@tabler/icons-react"
@ -109,9 +110,9 @@ export function BuildDataTable({
icon: <IconBuildingChurch /> icon: <IconBuildingChurch />
}, },
{ {
url: 'build-sites', url: 'build-ibans',
name: 'Build Sites', name: 'Build IBANs',
icon: <IconBuildingBridge /> icon: <IconCreditCard />
}, },
] ]

View File

@ -22,6 +22,7 @@ const PageLivingSpaceAdd = () => {
const [partID, setPartID] = useState<string | null>(null); const [partID, setPartID] = useState<string | null>(null);
const [companyID, setCompanyID] = useState<string | null>(null); const [companyID, setCompanyID] = useState<string | null>(null);
const [personID, setPersonID] = useState<string | null>(null); const [personID, setPersonID] = useState<string | null>(null);
const [isProperty, setIsProperty] = useState<boolean | null>(null);
const form = createForm({ buildID, userTypeID, partID, companyID, personID }); const form = createForm({ buildID, userTypeID, partID, companyID, personID });
@ -60,7 +61,7 @@ const PageLivingSpaceAdd = () => {
<PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} setIsUserTypeEnabled={setIsUserTypeEnabled} /> <PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} setIsUserTypeEnabled={setIsUserTypeEnabled} />
</TabsContent> </TabsContent>
{isUserTypeEnabled && <TabsContent value="usertype"> {isUserTypeEnabled && <TabsContent value="usertype">
<PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable} /> <PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable} setIsProperty={setIsProperty} />
</TabsContent>} </TabsContent>}
{isPartsEnabled && buildID && <TabsContent value="parts"> {isPartsEnabled && buildID && <TabsContent value="parts">
<PageLivingSpacePartsTableSection buildId={buildID} partID={partID} setPartID={setPartID} setIsPartsEnabled={setIsPartsEnabled} /> <PageLivingSpacePartsTableSection buildId={buildID} partID={partID} setPartID={setPartID} setIsPartsEnabled={setIsPartsEnabled} />

View File

@ -11,7 +11,6 @@ const PageLivingSpaceList = () => {
const router = useRouter(); const router = useRouter();
const [buildID, setBuildID] = useState<string | null>(null); const [buildID, setBuildID] = useState<string | null>(null);
// const [collectionToken, setCollectionToken] = useState<string | null>(null);
const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(false); const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(false);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [limit, setLimit] = useState(10); const [limit, setLimit] = useState(10);
@ -32,9 +31,7 @@ const PageLivingSpaceList = () => {
<div className="flex flex-col gap-2.5"> <div className="flex flex-col gap-2.5">
<PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} setIsUserTypeEnabled={setIsUserTypeEnabled} additionButtons={additionButtons} /> <PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} setIsUserTypeEnabled={setIsUserTypeEnabled} additionButtons={additionButtons} />
<h1 className="text-center justify-center">Living Space Added to selected Build with collectionToken: </h1><h1 className="text-center justify-center text-2xl font-bold">{buildID}</h1> <h1 className="text-center justify-center">Living Space Added to selected Build with collectionToken: </h1><h1 className="text-center justify-center text-2xl font-bold">{buildID}</h1>
{ {buildID && <LivingSpaceDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildID={buildID} />}
buildID && <LivingSpaceDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />
}
</div> </div>
</>; </>;
} }

View File

@ -11,6 +11,19 @@ const fetchGraphQlLivingSpaceList = async (buildID: string, params: ListArgument
} catch (error) { console.error('Error fetching test data:', error); throw error } } catch (error) { console.error('Error fetching test data:', error); throw error }
}; };
const fetchGraphQlLivingSpaceDetail = async (uuid: string, buildID: string): Promise<any> => {
console.log('Fetching test data from local API');
try {
const res = await fetch(`/api/living-space/detail`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ uuid, buildID }) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }; const data = await res.json();
return { data: data.data }
} catch (error) { console.error('Error fetching test data:', error); throw error }
};
export function useGraphQlLivingSpaceList(buildID: string, params: ListArguments) { export function useGraphQlLivingSpaceList(buildID: string, params: ListArguments) {
return useQuery({ queryKey: ['graphql-living-space-list', buildID, params], queryFn: () => fetchGraphQlLivingSpaceList(buildID, params) }) return useQuery({ queryKey: ['graphql-living-space-list', buildID, params], queryFn: () => fetchGraphQlLivingSpaceList(buildID, params) })
} }
export function useGraphQlLivingSpaceDetail(uuid: string, buildID: string) {
return useQuery({ queryKey: ['graphql-living-space-detail', uuid, buildID], queryFn: () => fetchGraphQlLivingSpaceDetail(uuid, buildID) })
}

View File

@ -23,31 +23,62 @@ export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof sche
) )
} }
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] { function getColumns(router: any, deleteHandler: (id: string) => void, buildID: string): ColumnDef<schemaType>[] {
return [ return [
{ {
accessorKey: "uuid", accessorKey: "uuid",
header: "UUID", header: "UUID",
}, },
{ {
accessorKey: "build", accessorKey: "person.firstName",
header: "Build", header: "First Name",
}, },
{ {
accessorKey: "part", accessorKey: "person.middleName",
header: "Part", header: "Middle Name",
}, },
{ {
accessorKey: "userType", accessorKey: "person.surname",
header: "Surname",
},
{
accessorKey: "person.birthDate",
header: "Birth Date",
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
},
{
accessorKey: "build.info.buildName",
header: "Build Name",
},
{
accessorKey: "build.info.buildNo",
header: "Build No",
},
{
accessorKey: "part.no",
header: "Part No",
},
{
accessorKey: "part.level",
header: "Level",
},
{
accessorKey: "part.humanLivability",
header: "Livability",
cell: ({ getValue }) => getValue() ? <div className="text-green-500 px-2 py-1 rounded">Yes</div> : <div className="text-red-500 px-2 py-1 rounded">No</div>
},
{
accessorKey: "person.birthPlace",
header: "Birth Place",
},
{
accessorKey: "userType.description",
header: "User Type", header: "User Type",
}, },
{ {
accessorKey: "company", accessorKey: "userType.isProperty",
header: "Company", header: "Property",
}, cell: ({ getValue }) => getValue() ? <div className="text-green-500 px-2 py-1 rounded">Yes</div> : <div className="text-red-500 px-2 py-1 rounded">No</div>
{
accessorKey: "person",
header: "Person",
}, },
{ {
accessorKey: "createdAt", accessorKey: "createdAt",
@ -75,10 +106,10 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ row }) => { cell: ({ row }) => {
return ( return (
<div> <div>
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/living-spaces/update?uuid=${row.original.uuid}&buildID=${row.original.build}`) }}> <Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/living-spaces/update?uuid=${row.original.uuid}&buildID=${buildID}`) }}>
<Pencil /> <Pencil />
</Button> </Button>
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}> <Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(buildID) }}>
<Trash /> <Trash />
</Button> </Button>
</div> </div>

View File

@ -79,6 +79,7 @@ export function LivingSpaceDataTable({
onPageChange, onPageChange,
onPageSizeChange, onPageSizeChange,
refetchTable, refetchTable,
buildID
}: { }: {
data: schemaType[], data: schemaType[],
totalCount: number, totalCount: number,
@ -87,6 +88,7 @@ export function LivingSpaceDataTable({
onPageChange: (page: number) => void, onPageChange: (page: number) => void,
onPageSizeChange: (size: number) => void, onPageSizeChange: (size: number) => void,
refetchTable: () => void, refetchTable: () => void,
buildID: string
}) { }) {
const router = useRouter() const router = useRouter()
@ -99,7 +101,7 @@ export function LivingSpaceDataTable({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data]) const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeleteLivingSpacesMutation() const deleteMutation = useDeleteLivingSpacesMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) } const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
const columns = getColumns(router, deleteHandler); const columns = getColumns(router, deleteHandler, buildID);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize]) const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize) const totalPages = Math.ceil(totalCount / pageSize)

View File

@ -18,4 +18,3 @@ export function useDeleteLivingSpacesMutation() {
onError: (error) => { console.error("Delete living space failed:", error) }, onError: (error) => { console.error("Delete living space failed:", error) },
}) })
} }

View File

@ -7,10 +7,10 @@ import { useUpdateLivingSpaceMutation } from "./queries";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { IconArrowLeftToArc } from "@tabler/icons-react"; import { IconArrowLeftToArc } from "@tabler/icons-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useGraphQlLivingSpaceList } from "../list/queries"; import { useGraphQlLivingSpaceDetail } from "../list/queries";
import { useSearchParams } from "next/navigation"; import { useSearchParams } from "next/navigation";
import PageLivingSpaceBuildsTableSection from "../tables/builds/page"; // import PageLivingSpaceBuildsTableSection from "../tables/builds/page";
import PageLivingSpaceUserTypesTableSection from "../tables/userType/page"; import PageLivingSpaceUserTypesTableSection from "../tables/userType/page";
import PageLivingSpacePartsTableSection from "../tables/part/page"; import PageLivingSpacePartsTableSection from "../tables/part/page";
import PageLivingSpacePersonTableSection from "../tables/person/page"; import PageLivingSpacePersonTableSection from "../tables/person/page";
@ -22,14 +22,10 @@ const PageLivingSpaceUpdate = () => {
const searchParams = useSearchParams() const searchParams = useSearchParams()
const uuid = searchParams?.get('uuid') || null const uuid = searchParams?.get('uuid') || null
const buildIDFromUrl = searchParams?.get('buildID') || null const buildIDFromUrl = searchParams?.get('buildID') || null
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(10);
const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({});
const backToBuildAddress = <><div>UUID not found in search params</div><Button onClick={() => router.push('/living-spaces')}>Back to Living Space List</Button></> const backToBuildAddress = <><div>UUID not found in search params</div><Button onClick={() => router.push('/living-spaces')}>Back to Living Space List</Button></>
const { data, isLoading, refetch } = useGraphQlLivingSpaceList(buildIDFromUrl || '', { limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } }); const { data, isLoading, refetch } = useGraphQlLivingSpaceDetail(uuid || '', buildIDFromUrl || '');
const initData = data?.data?.[0] || null; const initData = data?.data || null;
const [userTypeID, setUserTypeID] = useState<string | null>(null); const [userTypeID, setUserTypeID] = useState<string | null>(null);
const isPartInit = initData?.part !== null ? true : false; const isPartInit = initData?.part !== null ? true : false;
const [isProperty, setIsProperty] = useState<boolean | null>(isPartInit); const [isProperty, setIsProperty] = useState<boolean | null>(isPartInit);
@ -45,6 +41,7 @@ const PageLivingSpaceUpdate = () => {
setUserTypeID(initData?.userType || ""); setPartID(initData?.part || ""); setCompanyID(initData?.company || ""); setPersonID(initData?.person || ""); setUserTypeID(initData?.userType || ""); setPartID(initData?.part || ""); setCompanyID(initData?.company || ""); setPersonID(initData?.person || "");
} }
}, [initData]) }, [initData])
useEffect(() => { useEffect(() => {
form.setValue("userTypeID", userTypeID || ""); form.setValue("partID", partID || ""); form.setValue("companyID", companyID || ""); form.setValue("personID", personID || ""); form.setValue("userTypeID", userTypeID || ""); form.setValue("partID", partID || ""); form.setValue("companyID", companyID || ""); form.setValue("personID", personID || "");
}, [userTypeID, partID, companyID, personID, form]); }, [userTypeID, partID, companyID, personID, form]);

View File

@ -20,8 +20,8 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
expiryEnds: "", expiryEnds: "",
isConfirmed: false, isConfirmed: false,
isNotificationSend: false, isNotificationSend: false,
password: "", // password: "",
rePassword: "", // rePassword: "",
tag: "", tag: "",
email: "", email: "",
phone: "" phone: ""
@ -31,6 +31,7 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
const [defaultSelection, setDefaultSelection] = useState<string>("") const [defaultSelection, setDefaultSelection] = useState<string>("")
const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([]) const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([])
const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([]) const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([])
const [personID, setPersonID] = useState<string>("")
const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev)) const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev))
const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev)) const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev))
@ -40,12 +41,12 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
const { handleSubmit } = form const { handleSubmit } = form
const mutation = useAddUserMutation(); const mutation = useAddUserMutation();
function onSubmit(values: UserAdd) { mutation.mutate({ data: values as any, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); } function onSubmit(values: UserAdd) { console.dir({ values, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID }); mutation.mutate({ data: values, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable }); }
return ( return (
<div> <div>
<PageAddUserSelections <PageAddUserSelections
selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID} selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID} personID={personID} setPersonID={setPersonID}
removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection}
/> />
<Form {...form}> <Form {...form}>
@ -82,7 +83,7 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
{/* PASSWORD / TAG */} {/* PASSWORD / TAG */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField {/* <FormField
control={form.control} control={form.control}
name="password" name="password"
render={({ field }) => ( render={({ field }) => (
@ -107,7 +108,7 @@ const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> /> */}
<FormField <FormField
control={form.control} control={form.control}

View File

@ -9,15 +9,11 @@ const PageAddUser = () => {
const [limit, setLimit] = useState(10); const [limit, setLimit] = useState(10);
const [sort, setSort] = useState({ createdAt: 'desc' }); const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({}); const [filters, setFilters] = useState({});
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters }); const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters });
return ( return (
<> <>
<UserDataTableAdd <UserDataTableAdd data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} />
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
/>
<UserForm refetchTable={refetch} /> <UserForm refetchTable={refetch} />
</> </>
) )

View File

@ -1,6 +1,6 @@
'use client' 'use client'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import { UserAdd } from './types' import { UserAdd } from './schema'
import { toISOIfNotZ } from '@/lib/utils' import { toISOIfNotZ } from '@/lib/utils'
const fetchGraphQlUsersAdd = async ( const fetchGraphQlUsersAdd = async (
@ -8,15 +8,16 @@ const fetchGraphQlUsersAdd = async (
selectedBuildIDS: string[], selectedBuildIDS: string[],
selectedCompanyIDS: string[], selectedCompanyIDS: string[],
defaultSelection: string, defaultSelection: string,
personID: string,
refetchTable: () => void refetchTable: () => void
): Promise<{ data: UserAdd | null; status: number }> => { ): Promise<{ data: UserAdd | null; status: number }> => {
record.expiryStarts = toISOIfNotZ(record.expiryStarts); record.expiryStarts = record?.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
record.expiryEnds = toISOIfNotZ(record.expiryEnds); record.expiryEnds = record?.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
const payload = { ...record, person: personID, collectionTokens: { defaultSelection, selectedBuildIDS, selectedCompanyIDS } }
try { try {
const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, selectedBuildIDS, selectedCompanyIDS, defaultSelection }) }); const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(payload) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) } if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json(); const data = await res.json(); refetchTable();
refetchTable();
return { data: data.data, status: res.status } return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error } } catch (error) { console.error('Error fetching test data:', error); throw error }
}; };
@ -24,8 +25,12 @@ const fetchGraphQlUsersAdd = async (
export function useAddUserMutation() { export function useAddUserMutation() {
return useMutation({ return useMutation({
mutationFn: ( mutationFn: (
{ data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }: { data: UserAdd, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void } {
) => fetchGraphQlUsersAdd(data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable), data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable
}: {
data: UserAdd, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, personID: string, refetchTable: () => void
}
) => fetchGraphQlUsersAdd(data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable),
onSuccess: () => { console.log("User created successfully") }, onSuccess: () => { console.log("User created successfully") },
onError: (error) => { console.error("Create user failed:", error) }, onError: (error) => { console.error("Create user failed:", error) },
}) })

View File

@ -1,15 +1,15 @@
import { z } from "zod" import { z } from "zod";
export const userAddSchema = z.object({ export const userAddSchema = z.object({
expiryStarts: z.string().optional(), expiryStarts: z.string().optional(),
expiryEnds: z.string().optional(), expiryEnds: z.string().optional(),
isConfirmed: z.boolean(), isConfirmed: z.boolean(),
isNotificationSend: z.boolean(), isNotificationSend: z.boolean(),
password: z.string().min(6), // password: z.string().min(6),
rePassword: z.string().min(6), // rePassword: z.string().min(6),
tag: z.string().optional(), tag: z.string().optional(),
email: z.string().email(), email: z.string().email(),
phone: z.string().min(5), phone: z.string().min(5),

View File

@ -16,117 +16,6 @@ import { schema, schemaType } from "./schema"
import { dateToLocaleString } from "@/lib/utils" import { dateToLocaleString } from "@/lib/utils"
import { Pencil, Trash } from "lucide-react" import { Pencil, Trash } from "lucide-react"
function TableCellViewer({ item }: { item: schemaType }) {
const isMobile = useIsMobile();
return (
<Drawer direction={isMobile ? "bottom" : "right"}>
<DrawerTrigger asChild>
<Button variant="link" className="text-foreground w-fit px-0 text-left">
{item.email ?? "Unknown Email"}
</Button>
</DrawerTrigger>
<DrawerContent>
<DrawerHeader className="gap-1">
<h2 className="text-lg font-semibold">{item.email}</h2>
<p className="text-sm text-muted-foreground">
User details
</p>
</DrawerHeader>
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
{/* BASIC INFO */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Email</Label>
<Input value={item.email ?? ""} readOnly />
</div>
<div>
<Label>Phone</Label>
<Input value={item.phone ?? ""} readOnly />
</div>
<div>
<Label>Tag</Label>
<Input value={item.tag ?? ""} readOnly />
</div>
<div>
<Label>Active</Label>
<Input value={item.active ? "Active" : "Inactive"} readOnly />
</div>
</div>
<Separator />
{/* DATES */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Created At</Label>
<Input
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
readOnly
/>
</div>
<div>
<Label>Updated At</Label>
<Input
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
readOnly
/>
</div>
</div>
<Separator />
{/* TOKENS */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full">
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-72">
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
<DropdownMenuSeparator />
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
<DropdownMenuItem key={i} className="flex flex-col gap-2">
<div className="grid grid-cols-2 gap-2 w-full">
<Input value={t.prefix} readOnly />
<Input value={t.token} readOnly />
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<DrawerFooter>
<DrawerClose asChild>
<Button variant="outline">Close</Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
function DragHandle({ id }: { id: number }) {
const { attributes, listeners } = useSortable({ id })
return (
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
<IconGripVertical className="text-muted-foreground size-3" />
<span className="sr-only">Drag to reorder</span>
</Button>
)
}
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) { export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id }) const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
@ -161,6 +50,16 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
accessorKey: "tag", accessorKey: "tag",
header: "Tag", header: "Tag",
}, },
{
accessorKey: "isNotificationSend",
header: "Notificated?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "isEmailSend",
header: "Email Send?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{ {
accessorKey: "active", accessorKey: "active",
header: "Active", header: "Active",
@ -171,6 +70,11 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Confirmed", header: "Confirmed",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>), cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
}, },
{
accessorKey: "deleted",
header: "Deleted",
cell: ({ getValue }) => getValue() ? (<div className="text-red-600 font-medium">Yes</div>) : (<div className="text-green-600 font-medium">No</div>),
},
{ {
accessorKey: "createdAt", accessorKey: "createdAt",
header: "Created", header: "Created",
@ -191,57 +95,16 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Expiry Ends", header: "Expiry Ends",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-", cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
}, },
{
accessorKey: "crypUuId",
header: "Encrypted UUID",
},
{
accessorKey: "history",
header: "History",
cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
},
{ {
accessorKey: "collectionTokens.tokens", accessorKey: "collectionTokens.tokens",
header: "Tokens", header: "Default Token",
cell: ({ row }) => { cell: ({ row }) => {
const tokens = row.original.collectionTokens?.tokens ?? []; const defaultToken = row.original.collectionTokens?.defaultSelection;
const defaultToken = row.original.collectionTokens?.default;
if (!tokens.length) return "-";
return ( return (
<DropdownMenu> defaultToken ? <div><div className="flex flex-col w-full">
<DropdownMenuTrigger asChild>
<Button variant="outline" className="h-8 px-2 text-xs">
Tokens ({tokens.length})
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-72">
<DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
<DropdownMenuSeparator />
{defaultToken && (
<>
<DropdownMenuItem>
<div className="flex flex-col w-full">
<span className="font-semibold">Default</span> <span className="font-semibold">Default</span>
<span className="font-mono text-xs text-muted-foreground break-all"> <span className="font-mono text-xs text-muted-foreground break-all">{defaultToken}</span>
{defaultToken} </div></div> : <div>No Default Token is registered.</div>
</span>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
{tokens.map((t, i) => (
<DropdownMenuItem key={i} className="flex flex-col items-start">
<div className="w-full flex justify-between">
<span className="font-medium">{t.prefix}</span>
<span className="font-mono text-muted-foreground break-all">
{t.token}
</span>
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
); );
}, },
}, },
@ -251,7 +114,7 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ row }) => { cell: ({ row }) => {
return ( return (
<div> <div>
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update/${row.original.uuid}`) }}> <Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update?uuid=${row.original.uuid}`) }}>
<Pencil /> <Pencil />
</Button> </Button>
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}> <Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>

View File

@ -100,7 +100,7 @@ export function UserDataTableAdd({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data]) const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeleteUserMutation() const deleteMutation = useDeleteUserMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) } const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
const columns = getColumns(router, deleteHandler); const columns = getColumns(router, deleteHandler);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize]) const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize) const totalPages = Math.ceil(totalCount / pageSize)

View File

@ -2,46 +2,23 @@ import { z } from "zod";
export const schema = z.object({ export const schema = z.object({
_id: z.string(), _id: z.string(),
uuid: z.string().nullable().optional(), uuid: z.string(),
expiryStarts: z.string().nullable().optional(), expiryStarts: z.string(),
expiryEnds: z.string().nullable().optional(), expiryEnds: z.string(),
isConfirmed: z.boolean().nullable().optional(), isConfirmed: z.boolean(),
deleted: z.boolean().nullable().optional(), deleted: z.boolean(),
active: z.boolean().nullable().optional(), active: z.boolean(),
crypUuId: z.string().nullable().optional(), isNotificationSend: z.boolean(),
createdCredentialsToken: z.string().nullable().optional(), isEmailSend: z.boolean(),
updatedCredentialsToken: z.string().nullable().optional(), expiresAt: z.string(),
confirmedCredentialsToken: z.string().nullable().optional(), tag: z.string(),
isNotificationSend: z.boolean().nullable().optional(), email: z.string(),
isEmailSend: z.boolean().nullable().optional(), phone: z.string().optional(),
refInt: z.number().nullable().optional(), collectionTokens: z.object({
refId: z.string().nullable().optional(), defaultSelection: z.string().nullable().optional(), selectedBuildIDS: z.array(z.string()).optional(), selectedCompanyIDS: z.array(z.string()).optional()
replicationId: z.number().nullable().optional(), }).nullable().optional(),
expiresAt: z.string().nullable().optional(), createdAt: z.string(),
resetToken: z.string().nullable().optional(), updatedAt: z.string(),
password: z.string().nullable().optional(),
history: z.array(z.string()).optional(),
tag: z.string().nullable().optional(),
email: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
collectionTokens: z
.object({
default: z.string().nullable().optional(),
tokens: z
.array(
z.object({
prefix: z.string(),
token: z.string(),
})
)
.optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
updatedAt: z.string().nullable().optional(),
}); });
export type schemaType = z.infer<typeof schema>; export type schemaType = z.infer<typeof schema>;

View File

@ -9,8 +9,8 @@ interface CollectionTokens {
} }
interface UserAdd { interface UserAdd {
expiryStarts: string; expiryStarts?: string;
expiryEnds: string; expiryEnds?: string;
isConfirmed: boolean; isConfirmed: boolean;
isNotificationSend: boolean; isNotificationSend: boolean;
password: string; password: string;

View File

@ -9,26 +9,12 @@ const PageUsers = () => {
const [limit, setLimit] = useState(10); const [limit, setLimit] = useState(10);
const [sort, setSort] = useState({ createdAt: 'desc' }); const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({}); const [filters, setFilters] = useState({});
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters }); const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters });
const handlePageChange = (newPage: number) => { setPage(newPage) }; const handlePageChange = (newPage: number) => { setPage(newPage) };
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) }; const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> } if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> } if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
return <UserDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
return (
<UserDataTable
data={data?.data || []}
totalCount={data?.totalCount || 0}
currentPage={page}
pageSize={limit}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
refetchTable={refetch}
/>
);
}; };
export { PageUsers }; export { PageUsers };

View File

@ -2,6 +2,7 @@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import PageUsersCompanyTableSection from "./companies/page"; import PageUsersCompanyTableSection from "./companies/page";
import PageUsersBuildingTableSection from "./builds/page"; import PageUsersBuildingTableSection from "./builds/page";
import PageUsersPersonTableSection from "./people/page";
const PageAddUserSelections = ({ const PageAddUserSelections = ({
selectedCompanyIDS, selectedCompanyIDS,
@ -11,7 +12,9 @@ const PageAddUserSelections = ({
appendBuildingID, appendBuildingID,
removeCompanyID, removeCompanyID,
removeBuildingID, removeBuildingID,
setDefaultSelection setDefaultSelection,
personID,
setPersonID,
}: { }: {
selectedCompanyIDS: string[]; selectedCompanyIDS: string[];
selectedBuildingIDS: string[]; selectedBuildingIDS: string[];
@ -21,6 +24,8 @@ const PageAddUserSelections = ({
removeCompanyID: (id: string) => void; removeCompanyID: (id: string) => void;
removeBuildingID: (id: string) => void; removeBuildingID: (id: string) => void;
setDefaultSelection: (id: string) => void; setDefaultSelection: (id: string) => void;
personID: string;
setPersonID: (id: string) => void;
}) => { }) => {
const tabsClassName = "border border-gray-300 rounded-sm h-10" const tabsClassName = "border border-gray-300 rounded-sm h-10"
return ( return (
@ -29,10 +34,12 @@ const PageAddUserSelections = ({
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5 mx-5"> <TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5 mx-5">
<TabsTrigger className={tabsClassName} value="builds">Append Builds</TabsTrigger> <TabsTrigger className={tabsClassName} value="builds">Append Builds</TabsTrigger>
<TabsTrigger className={tabsClassName} value="company">Append Company</TabsTrigger> <TabsTrigger className={tabsClassName} value="company">Append Company</TabsTrigger>
<TabsTrigger className={tabsClassName} value="person">Append Person</TabsTrigger>
</TabsList> </TabsList>
<div className="mt-6"> <div className="mt-6">
<TabsContent value="builds"><PageUsersBuildingTableSection selectedBuildIDS={selectedBuildingIDS} appendBuildID={appendBuildingID} removeBuildID={removeBuildingID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} /></TabsContent> <TabsContent value="builds"><PageUsersBuildingTableSection selectedBuildIDS={selectedBuildingIDS} appendBuildID={appendBuildingID} removeBuildID={removeBuildingID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} /></TabsContent>
<TabsContent value="company"><PageUsersCompanyTableSection selectedCompanyIDS={selectedCompanyIDS} appendCompanyID={appendCompanyID} removeCompanyID={removeCompanyID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} /></TabsContent> <TabsContent value="company"><PageUsersCompanyTableSection selectedCompanyIDS={selectedCompanyIDS} appendCompanyID={appendCompanyID} removeCompanyID={removeCompanyID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} /></TabsContent>
<TabsContent value="person"><PageUsersPersonTableSection personID={personID} setPersonID={setPersonID} /></TabsContent>
</div> </div>
</Tabs> </Tabs>
</div> </div>

View File

@ -8,7 +8,7 @@ import { CSS } from "@dnd-kit/utilities"
import { schema, schemaType } from "./schema" import { schema, schemaType } from "./schema"
import { dateToLocaleString } from "@/lib/utils" import { dateToLocaleString } from "@/lib/utils"
import { Pencil, Trash } from "lucide-react" import { Pencil, Trash } from "lucide-react"
import { IconCircleMinus, IconHandClick } from "@tabler/icons-react" import { IconCircleMinus, IconHandClick, IconHandGrab } from "@tabler/icons-react"
export function DraggableRow({ row, selectedIDs }: { row: Row<z.infer<typeof schema>>; selectedIDs: string[] }) { export function DraggableRow({ row, selectedIDs }: { row: Row<z.infer<typeof schema>>; selectedIDs: string[] }) {
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id }) const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
@ -120,7 +120,12 @@ function getColumns(appendBuildID: (id: string) => void, removeBuildID: (id: str
header: "Actions", header: "Actions",
cell: ({ row }) => { cell: ({ row }) => {
return ( return (
selectedBuildIDS.includes(row.original._id) ? ( <div className="flex items-center gap-2">
{defaultSelection !== row.original._id && <div>
<Button className="bg-amber-600 border-amber-600 text-white" variant="outline" size="sm" onClick={() => { setDefaultSelection(row.original._id) }}>
<IconHandGrab />
</Button></div>}
{!selectedBuildIDS.includes(row.original._id) ? (
<div> <div>
<Button className="bg-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { appendBuildID(row.original._id) }}> <Button className="bg-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { appendBuildID(row.original._id) }}>
<IconHandClick /> <IconHandClick />
@ -132,6 +137,8 @@ function getColumns(appendBuildID: (id: string) => void, removeBuildID: (id: str
<IconCircleMinus /> <IconCircleMinus />
</Button> </Button>
</div> </div>
}
</div>
); );
}, },
} }

View File

@ -29,10 +29,8 @@ const PageUsersBuildsTableSection = (
const handlePageChange = (newPage: number) => { setPage(newPage) }; const handlePageChange = (newPage: number) => { setPage(newPage) };
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) }; const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> } if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> } if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
return <> return <>
<UsersBuildDataTable <UsersBuildDataTable
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange}

View File

@ -0,0 +1,148 @@
"use client"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useSortable } from "@dnd-kit/sortable"
import { IconGripVertical, IconHandClick } from "@tabler/icons-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { Separator } from "@/components/ui/separator"
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
import { TableCell, TableRow } from "@/components/ui/table"
import { CSS } from "@dnd-kit/utilities"
import { schema, schemaType } from "./schema"
import { dateToLocaleString } from "@/lib/utils"
import { Pencil, Trash } from "lucide-react"
function DragHandle({ id }: { id: number }) {
const { attributes, listeners } = useSortable({ id })
return (
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
<IconGripVertical className="text-muted-foreground size-3" />
<span className="sr-only">Drag to reorder</span>
</Button>
)
}
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
return (
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
className={`${selectedID === row.original._id ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
))}
</TableRow>
)
}
function getColumns(personID: string, setPersonID: (id: string) => void): ColumnDef<schemaType>[] {
return [
{
accessorKey: "uuid",
header: "UUID",
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
},
{
accessorKey: "firstName",
header: "First Name",
},
{
accessorKey: "surname",
header: "Surname",
},
{
accessorKey: "middleName",
header: "Middle Name",
},
{
accessorKey: "sexCode",
header: "Sex",
},
{
accessorKey: "personRef",
header: "Person Ref",
},
{
accessorKey: "personTag",
header: "Person Tag",
},
{
accessorKey: "fatherName",
header: "Father Name",
},
{
accessorKey: "motherName",
header: "Mother Name",
},
{
accessorKey: "countryCode",
header: "Country",
},
{
accessorKey: "nationalIdentityId",
header: "National ID",
},
{
accessorKey: "birthPlace",
header: "Birth Place",
},
{
accessorKey: "active",
header: "Active",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "isConfirmed",
header: "Confirmed",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "birthDate",
header: "Birth Date",
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
},
{
accessorKey: "createdAt",
header: "Created",
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
},
{
accessorKey: "updatedAt",
header: "Updated",
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
},
{
accessorKey: "expiryStarts",
header: "Expiry Starts",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
},
{
accessorKey: "expiryEnds",
header: "Expiry Ends",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
return (
personID !== row.original._id && (
<div>
<Button className="bg-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { setPersonID(row.original._id) }}>
<IconHandClick />
</Button>
</div>
)
);
},
}
]
}
export { getColumns };

View File

@ -0,0 +1,282 @@
"use client"
import * as React from "react"
import {
closestCenter,
DndContext,
KeyboardSensor,
MouseSensor,
TouchSensor,
useSensor,
useSensors,
type UniqueIdentifier,
} from "@dnd-kit/core"
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
import {
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable"
import {
IconChevronDown,
IconChevronLeft,
IconChevronRight,
IconChevronsLeft,
IconChevronsRight,
IconLayoutColumns,
IconPlus,
} from "@tabler/icons-react"
import {
ColumnFiltersState,
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getSortedRowModel,
SortingState,
useReactTable,
VisibilityState,
} from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Label } from "@/components/ui/label"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs"
import { schemaType } from "./schema"
import { getColumns, DraggableRow } from "./columns"
import { useRouter } from "next/navigation"
import { useDeleteUserMutation } from "@/pages/users/queries"
import { TableSkeleton } from "@/components/skeletons/tableSkeleton"
export default function TableUsersPersonTableSection({
data,
totalCount,
currentPage = 1,
pageSize = 10,
onPageChange,
onPageSizeChange,
refetchTable,
tableIsLoading,
personID,
setPersonID
}: {
data: schemaType[],
totalCount: number,
currentPage?: number,
pageSize?: number,
onPageChange: (page: number) => void,
onPageSizeChange: (size: number) => void,
refetchTable: () => void,
tableIsLoading: boolean,
personID: string,
setPersonID: (id: string) => void
}) {
const router = useRouter();
const [rowSelection, setRowSelection] = React.useState({})
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
const [sorting, setSorting] = React.useState<SortingState>([])
const sortableId = React.useId()
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const columns = getColumns(personID, setPersonID);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize)
const table = useReactTable({
data,
columns,
pageCount: totalPages,
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
manualPagination: true,
getRowId: (row) => row._id.toString(),
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
})
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
return (
<Tabs
defaultValue="outline"
className="w-full flex-col justify-start gap-6"
>
<div className="flex items-center justify-between px-4 lg:px-6">
<Label htmlFor="view-selector" className="sr-only">
View
</Label>
<Select defaultValue="outline">
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
<SelectValue placeholder="Select a view" />
</SelectTrigger>
<SelectContent>
<SelectItem value="outline">Outline</SelectItem>
<SelectItem value="past-performance">Past Performance</SelectItem>
<SelectItem value="key-personnel">Key Personnel</SelectItem>
<SelectItem value="focus-documents">Focus Documents</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<IconLayoutColumns />
<span className="hidden lg:inline">Customize Columns</span>
<span className="lg:hidden">Columns</span>
<IconChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
return (
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
{column.id}
</DropdownMenuCheckboxItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
<Button variant="outline" size="sm" onClick={() => { router.push("/people/add") }}>
<IconPlus />
<span className="hidden lg:inline">Add Person</span>
</Button>
</div>
</div>
<TabsContent value="outline"
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
>
<div className="overflow-hidden rounded-lg border">
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
<Table>
<TableHeader className="bg-muted sticky top-0 z-10">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody className="**:data-[slot=table-cell]:first:w-8">
{tableIsLoading ?
<TableSkeleton columnCount={table.getAllColumns().length} rowCount={pageSize} hasActions={true} /> :
<SortableContext items={dataIds} strategy={verticalListSortingStrategy}>{table.getRowModel().rows.map(row => <DraggableRow selectedID={personID} key={row.id} row={row} />)}</SortableContext>}
</TableBody>
</Table>
</DndContext>
</div>
<div className="flex items-center justify-between px-4">
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex w-full items-center gap-8 lg:w-fit">
<div className="hidden items-center gap-2 lg:flex">
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
<SelectValue placeholder={pageSize} />
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Page {currentPage} of {totalPages}
</div>
<div className="flex w-fit items-center justify-center text-sm font-medium">
Total Count: {totalCount}
</div>
<div className="ml-auto flex items-center gap-2 lg:ml-0">
<Button
variant="outline"
size="icon"
onClick={() => onPageChange(1)}
disabled={currentPage === 1}
>
<IconChevronsLeft />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 1}
>
<IconChevronLeft />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage >= totalPages}
>
<IconChevronRight />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => onPageChange(totalPages)}
disabled={currentPage >= totalPages}
>
<IconChevronsRight />
</Button>
</div>
</div>
</div>
</TabsContent>
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
</TabsContent>
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
</TabsContent>
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
</TabsContent>
</Tabs>
)
}

View File

@ -0,0 +1,30 @@
'use client';
import { useGraphQlPeopleList } from './queries';
import { useState } from 'react';
import TableUsersPersonTableSection from './data-table';
const PageUsersPersonTableSection = ({
personID,
setPersonID
}: {
personID: string;
setPersonID: (id: string) => void;
}) => {
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(10);
const [sort, setSort] = useState({ createdAt: 'desc' });
const [filters, setFilters] = useState({});
const { data, isFetching, isLoading, error, refetch } = useGraphQlPeopleList({ limit, skip: (page - 1) * limit, sort, filters });
const handlePageChange = (newPage: number) => { setPage(newPage) };
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
return <TableUsersPersonTableSection
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange}
refetchTable={refetch} tableIsLoading={isLoading || isFetching} personID={personID} setPersonID={setPersonID}
/>;
};
export default PageUsersPersonTableSection;

View File

@ -0,0 +1,37 @@
'use client'
import { useQuery, useMutation } from '@tanstack/react-query'
import { schemaType } from './schema'
import { ListArguments } from '@/types/listRequest'
const fetchGraphQlPeopleList = async (params: ListArguments): Promise<{ data: schemaType[], totalCount: number }> => {
console.log('Fetching test data from local API');
const { limit, skip, sort, filters } = params;
try {
const res = await fetch('/api/people/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ limit, skip, sort, filters }) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json()
return { data: data.data, totalCount: data.totalCount }
} catch (error) { console.error('Error fetching test data:', error); throw error }
};
const fetchGraphQlDeletePerson = async (uuid: string, refetchTable: () => void): Promise<boolean> => {
console.log('Fetching test data from local API');
try {
const res = await fetch(`/api/people/delete?uuid=${uuid}`, { method: 'GET', cache: 'no-store', credentials: "include" });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json(); refetchTable();
return data
} catch (error) { console.error('Error fetching test data:', error); throw error }
};
export function useGraphQlPeopleList(params: ListArguments) {
return useQuery({ queryKey: ['graphql-people-list', params], queryFn: () => fetchGraphQlPeopleList(params) })
}
export function useDeletePersonMutation() {
return useMutation({
mutationFn: ({ uuid, refetchTable }: { uuid: string, refetchTable: () => void }) => fetchGraphQlDeletePerson(uuid, refetchTable),
onSuccess: () => { console.log("Person deleted successfully") },
onError: (error) => { console.error("Delete person failed:", error) },
})
}

View File

@ -0,0 +1,27 @@
import { z } from "zod";
export const schema = z.object({
_id: z.string(),
uuid: z.string(),
firstName: z.string().nullable().optional(),
surname: z.string().nullable().optional(),
middleName: z.string().nullable().optional(),
sexCode: z.string().nullable().optional(),
personRef: z.string().nullable().optional(),
personTag: z.string().nullable().optional(),
fatherName: z.string().nullable().optional(),
motherName: z.string().nullable().optional(),
countryCode: z.string().nullable().optional(),
nationalIdentityId: z.string().nullable().optional(),
birthPlace: z.string().nullable().optional(),
birthDate: z.string().nullable().optional(),
taxNo: z.string().nullable().optional(),
birthname: z.string().nullable().optional(),
expiryStarts: z.string().nullable().optional(),
expiryEnds: z.string().nullable().optional(),
createdAt: z.string().nullable().optional(),
updatedAt: z.string().nullable().optional(),
});
export type schemaType = z.infer<typeof schema>;

View File

@ -16,118 +16,6 @@ import { schema, schemaType } from "./schema"
import { dateToLocaleString } from "@/lib/utils" import { dateToLocaleString } from "@/lib/utils"
import { Pencil, Trash } from "lucide-react" import { Pencil, Trash } from "lucide-react"
function TableCellViewer({ item }: { item: schemaType }) {
const isMobile = useIsMobile();
return (
<Drawer direction={isMobile ? "bottom" : "right"}>
<DrawerTrigger asChild>
<Button variant="link" className="text-foreground w-fit px-0 text-left">
{item.email ?? "Unknown Email"}
</Button>
</DrawerTrigger>
<DrawerContent>
<DrawerHeader className="gap-1">
<h2 className="text-lg font-semibold">{item.email}</h2>
<p className="text-sm text-muted-foreground">
User details
</p>
</DrawerHeader>
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
{/* BASIC INFO */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Email</Label>
<Input value={item.email ?? ""} readOnly />
</div>
<div>
<Label>Phone</Label>
<Input value={item.phone ?? ""} readOnly />
</div>
<div>
<Label>Tag</Label>
<Input value={item.tag ?? ""} readOnly />
</div>
<div>
<Label>Active</Label>
<Input value={item.active ? "Active" : "Inactive"} readOnly />
</div>
</div>
<Separator />
{/* DATES */}
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Created At</Label>
<Input
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
readOnly
/>
</div>
<div>
<Label>Updated At</Label>
<Input
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
readOnly
/>
</div>
</div>
<Separator />
{/* TOKENS */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full">
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-72">
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
<DropdownMenuSeparator />
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
<DropdownMenuItem key={i} className="flex flex-col gap-2">
<div className="grid grid-cols-2 gap-2 w-full">
<Input value={t.prefix} readOnly />
<Input value={t.token} readOnly />
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
<DrawerFooter>
<DrawerClose asChild>
<Button variant="outline">Close</Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
function DragHandle({ id }: { id: number }) {
const { attributes, listeners } = useSortable({ id })
return (
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
<IconGripVertical className="text-muted-foreground size-3" />
<span className="sr-only">Drag to reorder</span>
</Button>
)
}
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) { export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id }) const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
return ( return (
@ -161,6 +49,16 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
accessorKey: "tag", accessorKey: "tag",
header: "Tag", header: "Tag",
}, },
{
accessorKey: "isNotificationSend",
header: "Notificated?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{
accessorKey: "isEmailSend",
header: "Email Send?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
},
{ {
accessorKey: "active", accessorKey: "active",
header: "Active", header: "Active",
@ -171,6 +69,11 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Confirmed", header: "Confirmed",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>), cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
}, },
{
accessorKey: "deleted",
header: "Deleted",
cell: ({ getValue }) => getValue() ? (<div className="text-red-600 font-medium">Yes</div>) : (<div className="text-green-600 font-medium">No</div>),
},
{ {
accessorKey: "createdAt", accessorKey: "createdAt",
header: "Created", header: "Created",
@ -191,57 +94,16 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Expiry Ends", header: "Expiry Ends",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-", cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
}, },
{
accessorKey: "crypUuId",
header: "Encrypted UUID",
},
{
accessorKey: "history",
header: "History",
cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
},
{ {
accessorKey: "collectionTokens.tokens", accessorKey: "collectionTokens.tokens",
header: "Tokens", header: "Default Token",
cell: ({ row }) => { cell: ({ row }) => {
const tokens = row.original.collectionTokens?.tokens ?? []; const defaultToken = row.original.collectionTokens?.defaultSelection;
const defaultToken = row.original.collectionTokens?.default;
if (!tokens.length) return "-";
return ( return (
<DropdownMenu> defaultToken ? <div><div className="flex flex-col w-full">
<DropdownMenuTrigger asChild>
<Button variant="outline" className="h-8 px-2 text-xs">
Tokens ({tokens.length})
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-72">
<DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
<DropdownMenuSeparator />
{defaultToken && (
<>
<DropdownMenuItem>
<div className="flex flex-col w-full">
<span className="font-semibold">Default</span> <span className="font-semibold">Default</span>
<span className="font-mono text-xs text-muted-foreground break-all"> <span className="font-mono text-xs text-muted-foreground break-all">{defaultToken}</span>
{defaultToken} </div></div> : <div>No Default Token is registered.</div>
</span>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
{tokens.map((t, i) => (
<DropdownMenuItem key={i} className="flex flex-col items-start">
<div className="w-full flex justify-between">
<span className="font-medium">{t.prefix}</span>
<span className="font-mono text-muted-foreground break-all">
{t.token}
</span>
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
); );
}, },
}, },

View File

@ -100,7 +100,7 @@ export function UserDataTable({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data]) const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeleteUserMutation() const deleteMutation = useDeleteUserMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) } const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
const columns = getColumns(router, deleteHandler); const columns = getColumns(router, deleteHandler);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize]) const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize) const totalPages = Math.ceil(totalCount / pageSize)

View File

@ -2,46 +2,23 @@ import { z } from "zod";
export const schema = z.object({ export const schema = z.object({
_id: z.string(), _id: z.string(),
uuid: z.string().nullable().optional(), uuid: z.string(),
expiryStarts: z.string().nullable().optional(), expiryStarts: z.string(),
expiryEnds: z.string().nullable().optional(), expiryEnds: z.string(),
isConfirmed: z.boolean().nullable().optional(), isConfirmed: z.boolean(),
deleted: z.boolean().nullable().optional(), deleted: z.boolean(),
active: z.boolean().nullable().optional(), active: z.boolean(),
crypUuId: z.string().nullable().optional(), isNotificationSend: z.boolean(),
createdCredentialsToken: z.string().nullable().optional(), isEmailSend: z.boolean(),
updatedCredentialsToken: z.string().nullable().optional(), expiresAt: z.string(),
confirmedCredentialsToken: z.string().nullable().optional(), tag: z.string(),
isNotificationSend: z.boolean().nullable().optional(), email: z.string(),
isEmailSend: z.boolean().nullable().optional(), phone: z.string().optional(),
refInt: z.number().nullable().optional(), collectionTokens: z.object({
refId: z.string().nullable().optional(), defaultSelection: z.string().nullable().optional(), selectedBuildIDS: z.array(z.string()).optional(), selectedCompanyIDS: z.array(z.string()).optional()
replicationId: z.number().nullable().optional(), }).nullable().optional(),
expiresAt: z.string().nullable().optional(), createdAt: z.string(),
resetToken: z.string().nullable().optional(), updatedAt: z.string(),
password: z.string().nullable().optional(),
history: z.array(z.string()).optional(),
tag: z.string().nullable().optional(),
email: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
collectionTokens: z
.object({
default: z.string().nullable().optional(),
tokens: z
.array(
z.object({
prefix: z.string(),
token: z.string(),
})
)
.optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
updatedAt: z.string().nullable().optional(),
}); });
export type schemaType = z.infer<typeof schema>; export type schemaType = z.infer<typeof schema>;

View File

@ -1,11 +1,7 @@
interface UserToken {
prefix: string;
token: string;
}
interface CollectionTokens { interface CollectionTokens {
default: string; defaultSelection: string;
tokens: UserToken[]; selectedBuildIDS: string[];
selectedCompanyIDS: string[];
} }
interface User { interface User {
@ -16,19 +12,9 @@ interface User {
isConfirmed: boolean; isConfirmed: boolean;
deleted: boolean; deleted: boolean;
active: boolean; active: boolean;
crypUuId: string;
createdCredentialsToken: string;
updatedCredentialsToken: string;
confirmedCredentialsToken: string;
isNotificationSend: boolean; isNotificationSend: boolean;
isEmailSend: boolean; isEmailSend: boolean;
refInt: number;
refId: string;
replicationId: number;
expiresAt: string; expiresAt: string;
resetToken?: string | null;
password: string;
history: string[];
tag: string; tag: string;
email: string; email: string;
phone: string; phone: string;

View File

@ -12,7 +12,7 @@ import { useUpdateUserMutation } from "@/pages/users/update/queries"
import { userUpdateSchema, type UserUpdate } from "@/pages/users/update/schema" import { userUpdateSchema, type UserUpdate } from "@/pages/users/update/schema"
import PageAddUserSelections from "../selections/addPage" import PageAddUserSelections from "../selections/addPage"
const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: UserUpdate, selectedUuid: string }) => { const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: any, selectedUuid: string }) => {
const form = useForm<UserUpdate>({ const form = useForm<UserUpdate>({
resolver: zodResolver(userUpdateSchema), resolver: zodResolver(userUpdateSchema),
@ -28,10 +28,10 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
}) })
const { handleSubmit } = form const { handleSubmit } = form
const [defaultSelection, setDefaultSelection] = useState<string>(initData.collectionTokens.defaultSelection)
const [defaultSelection, setDefaultSelection] = useState<string>("") const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>(initData.collectionTokens.selectedBuildIDS)
const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([]) const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>(initData.collectionTokens.selectedCompanyIDS)
const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([]) const [personID, setPersonID] = useState<string>(initData.person)
const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev)) const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev))
const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev)) const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev))
@ -40,12 +40,12 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
const removeCompanyID = (id: string) => setSelectedCompanyIDS((prev) => prev.filter((item) => item !== id)) const removeCompanyID = (id: string) => setSelectedCompanyIDS((prev) => prev.filter((item) => item !== id))
const mutation = useUpdateUserMutation(); const mutation = useUpdateUserMutation();
function onSubmit(values: UserUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); setTimeout(() => refetchTable(), 400) } function onSubmit(values: UserUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable }) }
return ( return (
<div> <div>
<PageAddUserSelections <PageAddUserSelections
selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID} selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID} personID={personID} setPersonID={setPersonID}
removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection} removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection}
/> />
<Form {...form}> <Form {...form}>
@ -82,33 +82,6 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
{/* PASSWORD / TAG */} {/* PASSWORD / TAG */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="•••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="rePassword"
render={({ field }) => (
<FormItem>
<FormLabel>Re-Password</FormLabel>
<FormControl>
<Input type="password" placeholder="•••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField <FormField
control={form.control} control={form.control}
name="tag" name="tag"
@ -188,7 +161,7 @@ const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () =
</div> </div>
<Separator /> <Separator />
<Button type="submit" className="w-full">Create User</Button> <Button type="submit" className="w-full">Update User</Button>
</form> </form>
</Form> </Form>
</div> </div>

View File

@ -24,20 +24,10 @@ const PageUpdateUser = () => {
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } }); const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
const initData = data?.data?.[0] || null; const initData = data?.data?.[0] || null;
if (!initData) { return <><div>Selected User is either deleted or not found</div><Button onClick={() => router.push('/users')}>Back to Users</Button></> }
if (!initData) {
return <>
<div>Selected User is either deleted or not found</div>
<Button onClick={() => router.push('/users')}>Back to Users</Button>
</>
}
return ( return (
<> <>
<UserDataTableUpdate <UserDataTableUpdate data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} />
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
/>
<UserForm refetchTable={refetch} initData={initData} selectedUuid={uuid} /> <UserForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
</> </>
) )

View File

@ -1,13 +1,17 @@
'use client' 'use client'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import { UserUpdate } from './types'; import { UserUpdate } from './schema';
import { toISOIfNotZ } from '@/lib/utils';
const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void): Promise<{ data: UserUpdate | null; status: number }> => { const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, personID: string, refetchTable: () => void): Promise<{ data: UserUpdate | null; status: number }> => {
console.log('Fetching test data from local API'); console.log('Fetching test data from local API');
record.expiryStarts = record?.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
record.expiryEnds = record?.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
const payload = { ...record, person: personID, collectionTokens: { defaultSelection, selectedBuildIDS, selectedCompanyIDS } }
try { try {
const res = await fetch(`/api/users/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, selectedBuildIDS, selectedCompanyIDS, defaultSelection }) }); const res = await fetch(`/api/users/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(payload) });
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) } if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
const data = await res.json(); const data = await res.json(); refetchTable();
return { data: data.data, status: res.status } return { data: data.data, status: res.status }
} catch (error) { console.error('Error fetching test data:', error); throw error } } catch (error) { console.error('Error fetching test data:', error); throw error }
}; };
@ -15,8 +19,8 @@ const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string, selecte
export function useUpdateUserMutation() { export function useUpdateUserMutation() {
return useMutation({ return useMutation({
mutationFn: ( mutationFn: (
{ data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }: { data: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void } { data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable }: { data: UserUpdate, uuid: string, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, personID: string, refetchTable: () => void }
) => fetchGraphQlUsersUpdate(data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable), ) => fetchGraphQlUsersUpdate(data, uuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, personID, refetchTable),
onSuccess: () => { console.log("User updated successfully") }, onSuccess: () => { console.log("User updated successfully") },
onError: (error) => { console.error("Update user failed:", error) }, onError: (error) => { console.error("Update user failed:", error) },
}) })

View File

@ -8,8 +8,8 @@ export const userUpdateSchema = z.object({
isConfirmed: z.boolean(), isConfirmed: z.boolean(),
isNotificationSend: z.boolean(), isNotificationSend: z.boolean(),
password: z.string().min(6), // password: z.string().min(6),
rePassword: z.string().min(6), // rePassword: z.string().min(6),
tag: z.string().optional(), tag: z.string().optional(),
email: z.string().email(), email: z.string().email(),
phone: z.string().min(5), phone: z.string().min(5),

View File

@ -24,7 +24,7 @@ export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
) )
} }
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] { function getColumns(deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
return [ return [
{ {
accessorKey: "uuid", accessorKey: "uuid",
@ -32,48 +32,26 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>), cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
}, },
{ {
accessorKey: "firstName", accessorKey: "email",
header: "First Name", header: "Email",
}, },
{ {
accessorKey: "surname", accessorKey: "phone",
header: "Surname", header: "Phone",
}, },
{ {
accessorKey: "middleName", accessorKey: "tag",
header: "Middle Name", header: "Tag",
}, },
{ {
accessorKey: "sexCode", accessorKey: "isNotificationSend",
header: "Sex", header: "Notificated?",
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
}, },
{ {
accessorKey: "personRef", accessorKey: "isEmailSend",
header: "Person Ref", header: "Email Send?",
}, cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
{
accessorKey: "personTag",
header: "Person Tag",
},
{
accessorKey: "fatherName",
header: "Father Name",
},
{
accessorKey: "motherName",
header: "Mother Name",
},
{
accessorKey: "countryCode",
header: "Country",
},
{
accessorKey: "nationalIdentityId",
header: "National ID",
},
{
accessorKey: "birthPlace",
header: "Birth Place",
}, },
{ {
accessorKey: "active", accessorKey: "active",
@ -86,9 +64,9 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>), cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
}, },
{ {
accessorKey: "birthDate", accessorKey: "deleted",
header: "Birth Date", header: "Deleted",
cell: ({ getValue }) => dateToLocaleString(getValue() as string), cell: ({ getValue }) => getValue() ? (<div className="text-red-600 font-medium">Yes</div>) : (<div className="text-green-600 font-medium">No</div>),
}, },
{ {
accessorKey: "createdAt", accessorKey: "createdAt",
@ -110,15 +88,36 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
header: "Expiry Ends", header: "Expiry Ends",
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-", cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
}, },
{
accessorKey: "collectionTokens.tokens",
header: "Default Token",
cell: ({ row }) => {
const defaultToken = row.original.collectionTokens?.defaultSelection;
return defaultToken ? <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{defaultToken}</span></div></div> : <div>No Default Token</div>;
},
},
{
accessorKey: "collectionTokens.selectedBuildIDS",
header: "Selected Build IDS",
cell: ({ row }) => {
const selectedBuildIDS = row.original.collectionTokens?.selectedBuildIDS;
return selectedBuildIDS && <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{selectedBuildIDS.length}</span></div></div>;
},
},
{
accessorKey: "collectionTokens.selectedCompanyIDS",
header: "Selected Company IDS",
cell: ({ row }) => {
const selectedCompanyIDS = row.original.collectionTokens?.selectedCompanyIDS;
return selectedCompanyIDS && <div><div className="flex flex-col w-full"><span className="font-mono text-xs text-muted-foreground break-all">{selectedCompanyIDS.length}</span></div></div>;
},
},
{ {
id: "actions", id: "actions",
header: "Actions", header: "Actions",
cell: ({ row }) => { cell: ({ row }) => {
return ( return (
<div> <div>
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update?uuid=${row.original.uuid}`) }}>
<Pencil />
</Button>
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}> <Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
<Trash /> <Trash />
</Button> </Button>

View File

@ -100,7 +100,7 @@ export function UserDataTableUpdate({
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data]) const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
const deleteMutation = useDeleteUserMutation() const deleteMutation = useDeleteUserMutation()
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) } const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
const columns = getColumns(router, deleteHandler); const columns = getColumns(router, deleteHandler);
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize]) const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
const totalPages = Math.ceil(totalCount / pageSize) const totalPages = Math.ceil(totalCount / pageSize)

View File

@ -2,46 +2,23 @@ import { z } from "zod";
export const schema = z.object({ export const schema = z.object({
_id: z.string(), _id: z.string(),
uuid: z.string().nullable().optional(), uuid: z.string(),
expiryStarts: z.string().nullable().optional(), expiryStarts: z.string(),
expiryEnds: z.string().nullable().optional(), expiryEnds: z.string(),
isConfirmed: z.boolean().nullable().optional(), isConfirmed: z.boolean(),
deleted: z.boolean().nullable().optional(), deleted: z.boolean(),
active: z.boolean().nullable().optional(), active: z.boolean(),
crypUuId: z.string().nullable().optional(), isNotificationSend: z.boolean(),
createdCredentialsToken: z.string().nullable().optional(), isEmailSend: z.boolean(),
updatedCredentialsToken: z.string().nullable().optional(), expiresAt: z.string(),
confirmedCredentialsToken: z.string().nullable().optional(), tag: z.string(),
isNotificationSend: z.boolean().nullable().optional(), email: z.string(),
isEmailSend: z.boolean().nullable().optional(), phone: z.string().optional(),
refInt: z.number().nullable().optional(), collectionTokens: z.object({
refId: z.string().nullable().optional(), defaultSelection: z.string().nullable().optional(), selectedBuildIDS: z.array(z.string()).optional(), selectedCompanyIDS: z.array(z.string()).optional()
replicationId: z.number().nullable().optional(), }).nullable().optional(),
expiresAt: z.string().nullable().optional(), createdAt: z.string(),
resetToken: z.string().nullable().optional(), updatedAt: z.string(),
password: z.string().nullable().optional(),
history: z.array(z.string()).optional(),
tag: z.string().nullable().optional(),
email: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
collectionTokens: z
.object({
default: z.string().nullable().optional(),
tokens: z
.array(
z.object({
prefix: z.string(),
token: z.string(),
})
)
.optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
updatedAt: z.string().nullable().optional(),
}); });
export type schemaType = z.infer<typeof schema>; export type schemaType = z.infer<typeof schema>;