updated living space add list updagte
This commit is contained in:
parent
eaca36573e
commit
d22fc017df
|
|
@ -7,9 +7,6 @@ export class CreateLivingSpaceInput extends ExpiryBaseInput {
|
||||||
@Field()
|
@Field()
|
||||||
buildID: string;
|
buildID: string;
|
||||||
|
|
||||||
@Field()
|
|
||||||
collectionToken: string;
|
|
||||||
|
|
||||||
@Field()
|
@Field()
|
||||||
partID: string;
|
partID: string;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,12 +4,6 @@ import { InputType, Field } from '@nestjs/graphql';
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdateLivingSpaceInput extends ExpiryBaseInput {
|
export class UpdateLivingSpaceInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
@Field({ nullable: true })
|
|
||||||
buildID?: string;
|
|
||||||
|
|
||||||
@Field({ nullable: true })
|
|
||||||
collectionToken?: string;
|
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
partID?: string;
|
partID?: string;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,13 @@ import { LivingSpaceService } from './living-space.service';
|
||||||
import { LivingSpaceResolver } from './living-space.resolver';
|
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';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [MongooseModule.forFeature([{ name: LivingSpaces.name, schema: LivingSpacesSchema }])],
|
imports: [MongooseModule.forFeature([
|
||||||
|
{ name: LivingSpaces.name, schema: LivingSpacesSchema },
|
||||||
|
{ name: UserType.name, schema: UserTypeSchema },
|
||||||
|
])],
|
||||||
providers: [LivingSpaceService, LivingSpaceResolver]
|
providers: [LivingSpaceService, LivingSpaceResolver]
|
||||||
})
|
})
|
||||||
export class LivingSpaceModule { }
|
export class LivingSpaceModule { }
|
||||||
|
|
|
||||||
|
|
@ -15,23 +15,23 @@ export class LivingSpaceResolver {
|
||||||
constructor(private readonly livingSpaceService: LivingSpaceService) { }
|
constructor(private readonly livingSpaceService: LivingSpaceService) { }
|
||||||
|
|
||||||
@Query(() => ListLivingSpaceResponse, { name: 'getLivingSpaces' })
|
@Query(() => ListLivingSpaceResponse, { name: 'getLivingSpaces' })
|
||||||
async getLivingSpaces(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListLivingSpaceResponse> {
|
async getLivingSpaces(@Info() info: GraphQLResolveInfo, @Args('buildID') buildID: string, @Args('input') input: ListArguments): Promise<ListLivingSpaceResponse> {
|
||||||
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
||||||
return await this.livingSpaceService.findAll(projection, skip, limit, sort, filters);
|
return await this.livingSpaceService.findAll(buildID, projection, skip, limit, sort, filters);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => LivingSpaces, { name: 'getLivingSpace', nullable: true })
|
@Query(() => LivingSpaces, { name: 'getLivingSpace', nullable: true })
|
||||||
async getLivingSpace(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<LivingSpaces | null> {
|
async getLivingSpace(@Args('id', { type: () => ID }) id: string, @Args('buildID') buildID: string, @Info() info: GraphQLResolveInfo): Promise<LivingSpaces | null> {
|
||||||
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields); return this.livingSpaceService.findById(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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@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) }
|
||||||
|
|
||||||
@Mutation(() => LivingSpaces, { name: 'updateLivingSpace' })
|
@Mutation(() => LivingSpaces, { name: 'updateLivingSpace' })
|
||||||
async updateLivingSpace(@Args('uuid') uuid: string, @Args('input') input: UpdateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.update(uuid, input) }
|
async updateLivingSpace(@Args('buildID') buildID: string, @Args('uuid') uuid: string, @Args('input') input: UpdateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.update(buildID, uuid, input) }
|
||||||
|
|
||||||
@Mutation(() => Boolean, { name: 'deleteLivingSpace' })
|
@Mutation(() => Boolean, { name: 'deleteLivingSpace' })
|
||||||
async deleteLivingSpace(@Args('uuid') uuid: string, @Args('collectionToken') collectionToken: string): Promise<boolean> { return this.livingSpaceService.delete(uuid, collectionToken) }
|
async deleteLivingSpace(@Args('buildID') buildID: string, @Args('uuid') uuid: string): Promise<boolean> { return this.livingSpaceService.delete(buildID, uuid) }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,15 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectModel } from '@nestjs/mongoose';
|
import { Types, Connection, Model } from 'mongoose';
|
||||||
import { Types, Model, Connection } from 'mongoose';
|
import { getDynamicLivingSpaceModel, LivingSpacesDocument } from '@/models/living-spaces.model';
|
||||||
import { getDynamicLivingSpaceModel, LivingSpaces, LivingSpacesDocument } from '@/models/living-spaces.model';
|
|
||||||
import { ListLivingSpaceResponse } from './dto/list-living-space.response';
|
import { ListLivingSpaceResponse } from './dto/list-living-space.response';
|
||||||
import { CreateLivingSpaceInput } from './dto/create-living-space.input';
|
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 } from '@nestjs/mongoose';
|
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
|
||||||
|
import { UserTypeDocument } from '@/models/user-type.model';
|
||||||
|
|
||||||
interface UpdateInput {
|
interface UpdateInput {
|
||||||
build?: Types.ObjectId;
|
|
||||||
collectionToken?: string;
|
|
||||||
userType?: Types.ObjectId;
|
userType?: Types.ObjectId;
|
||||||
part?: Types.ObjectId;
|
part?: Types.ObjectId | null;
|
||||||
company?: Types.ObjectId;
|
company?: Types.ObjectId;
|
||||||
person?: Types.ObjectId;
|
person?: Types.ObjectId;
|
||||||
expiryStarts?: Date;
|
expiryStarts?: Date;
|
||||||
|
|
@ -22,27 +20,26 @@ interface UpdateInput {
|
||||||
export class LivingSpaceService {
|
export class LivingSpaceService {
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectModel(LivingSpaces.name) private readonly livingSpaceModel: Model<LivingSpacesDocument>,
|
@InjectConnection() private readonly connection: Connection,
|
||||||
@InjectConnection() private readonly connection: Connection
|
@InjectModel('UserType') private readonly userTypeModel: Model<UserTypeDocument>
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
async findAll(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> {
|
||||||
if (!filters?.collectionToken) { throw new Error('Collection token is required') }
|
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 this.livingSpaceModel.countDocuments(query).exec();
|
const totalCount = await selectedModel.countDocuments(query).exec();
|
||||||
const data = await this.livingSpaceModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
const data = await selectedModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
||||||
return { data, totalCount };
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
async findById(id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> {
|
async findById(buildID: string, id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> {
|
||||||
if (!projection?.collectionToken) { throw new Error('Collection token is required') }
|
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
|
||||||
const selectedModel = getDynamicLivingSpaceModel(projection.collectionToken, 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();
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(input: CreateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
async create(input: CreateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
||||||
if (!input.collectionToken) { throw new Error('Collection token is required') }
|
if (!input.buildID) { throw new Error('Build ID is required') }
|
||||||
const LivingSpaceModel = getDynamicLivingSpaceModel(input.collectionToken, 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: new Types.ObjectId(input.companyID), person: new Types.ObjectId(input.personID),
|
||||||
|
|
@ -50,18 +47,18 @@ export class LivingSpaceService {
|
||||||
}; const doc = new LivingSpaceModel(docInput); return await doc.save()
|
}; const doc = new LivingSpaceModel(docInput); return await doc.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(uuid: string, input: UpdateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
async update(buildID: string, uuid: string, input: UpdateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
||||||
if (!input.collectionToken) { throw new Error('Collection token is required') }
|
if (!buildID) { throw new Error('Build ID is required') }
|
||||||
const selectedModel = getDynamicLivingSpaceModel(input.collectionToken, this.connection);
|
const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
|
||||||
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 (input?.buildID) { newInput.build = new Types.ObjectId(input.buildID) }; if (input?.userTypeID) { newInput.userType = new Types.ObjectId(input.userTypeID) }
|
if (userTypeSelected?.isProperty) { if (input?.partID) { newInput.part = new Types.ObjectId(input.partID) } } else { newInput.part = null }
|
||||||
if (input?.partID) { newInput.part = new Types.ObjectId(input.partID) }; 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?.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 }
|
||||||
const company = await selectedModel.findOne({ uuid }); if (!company) { throw new Error('Company not found') }; company.set(newInput); return company.save();
|
if (!livingSpace) { throw new Error('Company not found') }; livingSpace.set(newInput); return livingSpace.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
async delete(uuid: string, collectionToken: string): Promise<boolean> { if (!collectionToken) { throw new Error('Collection token is required') } const selectedModel = getDynamicLivingSpaceModel(collectionToken, this.connection); const company = await selectedModel.deleteMany({ uuid }); return company.deletedCount > 0 }
|
async delete(buildID: string, uuid: string): Promise<boolean> { if (!buildID) { throw new Error('Build ID is required') } const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const company = await selectedModel.deleteMany({ uuid }); return company.deletedCount > 0 }
|
||||||
|
|
||||||
buildProjection(fields: Record<string, any>): any {
|
buildProjection(fields: Record<string, any>): any {
|
||||||
const projection: any = {};
|
const projection: any = {};
|
||||||
|
|
|
||||||
|
|
@ -20,9 +20,9 @@ export class LivingSpaces extends Base {
|
||||||
@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)
|
@Field(() => ID, { nullable: true })
|
||||||
@Prop({ type: Types.ObjectId, ref: BuildParts.name, required: true })
|
@Prop({ type: Types.ObjectId, ref: BuildParts.name, required: false })
|
||||||
part: Types.ObjectId;
|
part?: Types.ObjectId | null;
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
@Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
|
@Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
|
||||||
|
|
@ -41,8 +41,8 @@ export class LivingSpaces extends Base {
|
||||||
export type LivingSpacesDocument = LivingSpaces & Document;
|
export type LivingSpacesDocument = LivingSpaces & Document;
|
||||||
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);
|
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);
|
||||||
|
|
||||||
export function getDynamicLivingSpaceModel(collectionToken: string, connection: Connection): Model<LivingSpacesDocument> {
|
export function getDynamicLivingSpaceModel(buildID: string, connection: Connection): Model<LivingSpacesDocument> {
|
||||||
const collectionName = `LivingSpaces${collectionToken}`;
|
const collectionName = `LivingSpaces${buildID}`;
|
||||||
const schema = SchemaFactory.createForClass(LivingSpaces);
|
const schema = SchemaFactory.createForClass(LivingSpaces);
|
||||||
if (connection.models[collectionName]) { return connection.models[collectionName] as Model<LivingSpacesDocument> }
|
if (connection.models[collectionName]) { return connection.models[collectionName] as Model<LivingSpacesDocument> }
|
||||||
return connection.model(collectionName, schema, collectionName) as unknown as Model<LivingSpacesDocument>;
|
return connection.model(collectionName, schema, collectionName) as unknown as Model<LivingSpacesDocument>;
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ import { z } from "zod"
|
||||||
|
|
||||||
export const CreateLivingSpaceInputSchema = z.object({
|
export const CreateLivingSpaceInputSchema = z.object({
|
||||||
buildID: z.string(),
|
buildID: z.string(),
|
||||||
collectionToken: z.string(),
|
|
||||||
partID: z.string(),
|
partID: z.string(),
|
||||||
userTypeID: z.string(),
|
userTypeID: z.string(),
|
||||||
companyID: z.string(),
|
companyID: z.string(),
|
||||||
|
|
|
||||||
|
|
@ -8,12 +8,13 @@ export async function GET(request: Request) {
|
||||||
|
|
||||||
const searchParams = new URL(request.url).searchParams;
|
const searchParams = new URL(request.url).searchParams;
|
||||||
const uuid = searchParams.get('uuid');
|
const uuid = searchParams.get('uuid');
|
||||||
console.dir({ uuid }, { depth: null });
|
const buildID = searchParams.get('buildID');
|
||||||
|
console.dir({ uuid, buildID }, { depth: null });
|
||||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||||
try {
|
try {
|
||||||
const client = new GraphQLClient(endpoint);
|
const client = new GraphQLClient(endpoint);
|
||||||
const query = gql`mutation DeleteCompany($uuid: String!) { deleteCompany(uuid: $uuid) }`;
|
const query = gql`mutation DeleteCompany($buildID: String!, $uuid: String!) { deleteCompany(buildID: $buildID, uuid: $uuid) }`;
|
||||||
const data = await client.request(query, { uuid });
|
const data = await client.request(query, { buildID, uuid });
|
||||||
return NextResponse.json({ data: data.deleteUserType, status: 200 });
|
return NextResponse.json({ data: data.deleteUserType, status: 200 });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
|
||||||
|
|
@ -6,40 +6,36 @@ 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 { limit, skip, sort, filters } = body;
|
const { limit, skip, sort, filters, buildID } = body;
|
||||||
try {
|
try {
|
||||||
const client = new GraphQLClient(endpoint);
|
const client = new GraphQLClient(endpoint);
|
||||||
const query = gql`
|
const query = gql`
|
||||||
query GetCompanies($input: ListArguments!) {
|
query GetLivingSpaces($input: ListArguments!, $buildID: String!) {
|
||||||
getCompanies(input:$input) {
|
getLivingSpaces(input: $input, buildID: $buildID) {
|
||||||
data {
|
data {
|
||||||
_id
|
_id
|
||||||
uuid
|
uuid
|
||||||
company_type
|
build
|
||||||
commercial_type
|
part
|
||||||
tax_no
|
userType
|
||||||
default_lang_type
|
company
|
||||||
default_money_type
|
person
|
||||||
is_commercial
|
isNotificationSend
|
||||||
is_blacklist
|
|
||||||
workplace_no
|
|
||||||
official_address
|
|
||||||
top_responsible_company
|
|
||||||
parent_id
|
|
||||||
company_tag
|
|
||||||
formal_name
|
|
||||||
public_name
|
|
||||||
parent_id
|
|
||||||
expiryStarts
|
|
||||||
expiryEnds
|
expiryEnds
|
||||||
|
expiryStarts
|
||||||
|
createdAt
|
||||||
|
updatedAt
|
||||||
|
isConfirmed
|
||||||
|
deleted
|
||||||
|
|
||||||
}
|
}
|
||||||
totalCount
|
totalCount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
const variables = { input: { limit, skip, sort, filters } };
|
const variables = { input: { limit, skip, sort, filters }, buildID };
|
||||||
const data = await client.request(query, variables);
|
const data = await client.request(query, variables);
|
||||||
return NextResponse.json({ data: data.getCompanies.data, totalCount: data.getCompanies.totalCount });
|
return NextResponse.json({ data: data.getLivingSpaces.data, totalCount: data.getLivingSpaces.totalCount });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,15 @@ const endpoint = "http://localhost:3001/graphql";
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const searchUrl = new URL(request.url);
|
const searchUrl = new URL(request.url);
|
||||||
const uuid = searchUrl.searchParams.get("uuid") || "";
|
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||||
|
const buildID = searchUrl.searchParams.get("buildID") || "";
|
||||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||||
|
if (buildID === "") { return NextResponse.json({ error: "Build ID is required" }, { status: 400 }) }
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const validatedBody = UpdateLivingSpaceInputSchema.parse(body);
|
const validatedBody = UpdateLivingSpaceInputSchema.parse(body);
|
||||||
try {
|
try {
|
||||||
const client = new GraphQLClient(endpoint);
|
const client = new GraphQLClient(endpoint);
|
||||||
const query = gql`mutation UpdateLivingSpace($uuid: String!, $input: UpdateLivingSpaceInput!) { updateLivingSpace(uuid:$uuid, input: $input) {_id} }`;
|
const query = gql`mutation UpdateLivingSpace($buildID:String!, $uuid: String!, $input: UpdateLivingSpaceInput!) { updateLivingSpace(buildID: $buildID, uuid: $uuid, input: $input) {_id}} `;
|
||||||
const variables = { uuid: uuid, input: { ...validatedBody } };
|
const variables = { uuid: uuid, buildID: buildID, input: { ...validatedBody } };
|
||||||
const data = await client.request(query, variables);
|
const data = await client.request(query, variables);
|
||||||
return NextResponse.json({ data: data.updateLivingSpace, status: 200 });
|
return NextResponse.json({ data: data.updateLivingSpace, status: 200 });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
|
|
||||||
export const UpdateLivingSpaceInputSchema = z.object({
|
export const UpdateLivingSpaceInputSchema = z.object({
|
||||||
buildID: z.string(),
|
|
||||||
collectionToken: z.string(),
|
|
||||||
partID: z.string(),
|
partID: z.string(),
|
||||||
userTypeID: z.string(),
|
userTypeID: z.string(),
|
||||||
companyID: z.string(),
|
companyID: z.string(),
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// import { PageLivingSpace } from "@/pages/living-space/add/page"
|
import { PageLivingSpaceList } from "@/pages/living-space/list/page";
|
||||||
|
|
||||||
const SSRPageLivingSpace = () => { return <><div>PageLivingSpace</div></> }
|
const SSRPageLivingSpace = () => { return <><div><PageLivingSpaceList /></div></> }
|
||||||
|
|
||||||
export default SSRPageLivingSpace;
|
export default SSRPageLivingSpace;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { PageLivingSpaceUpdate } from "@/pages/living-space/update/page";
|
||||||
|
|
||||||
|
const LivingSpaceUpdatePage = () => { return <PageLivingSpaceUpdate /> }
|
||||||
|
|
||||||
|
export default LivingSpaceUpdatePage;
|
||||||
|
|
@ -26,19 +26,6 @@ const FormAddNewLivingSpace = ({ form, onSubmit, deleteAllSelections }: { form:
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="collectionToken"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem className="mt-3">
|
|
||||||
<FormLabel>Collection Token</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
|
||||||
</FormControl>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="userTypeID"
|
name="userTypeID"
|
||||||
|
|
|
||||||
|
|
@ -3,32 +3,31 @@ import { useState, useEffect } from "react";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { FormValues, createForm } from "./schema";
|
import { FormValues, createForm } from "./schema";
|
||||||
import { FormAddNewLivingSpace } from "./form";
|
import { FormAddNewLivingSpace } from "./form";
|
||||||
|
import { useAddLivingSpaceMutation } from "./queries";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { IconArrowLeftToArc } from "@tabler/icons-react";
|
||||||
|
import { useRouter } 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";
|
||||||
import PageLivingSpaceCompanyTableSection from "../tables/company/page";
|
import PageLivingSpaceCompanyTableSection from "../tables/company/page";
|
||||||
import { useAddLivingSpaceMutation } from "./queries";
|
|
||||||
|
|
||||||
const PageLivingSpaceAdd = () => {
|
const PageLivingSpaceAdd = () => {
|
||||||
const [collectionToken, setCollectionToken] = useState<string | null>(null);
|
|
||||||
|
const router = useRouter();
|
||||||
const [buildID, setBuildID] = useState<string | null>(null);
|
const [buildID, setBuildID] = useState<string | null>(null);
|
||||||
const [userTypeID, setUserTypeID] = useState<string | null>(null);
|
const [userTypeID, setUserTypeID] = useState<string | null>(null);
|
||||||
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 form = createForm({ buildID, collectionToken, userTypeID, partID, companyID, personID });
|
const form = createForm({ buildID, userTypeID, partID, companyID, personID });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
form.setValue("buildID", buildID || "");
|
form.setValue("buildID", buildID || ""); form.setValue("userTypeID", userTypeID || ""); form.setValue("partID", partID || ""); form.setValue("companyID", companyID || ""); form.setValue("personID", personID || "");
|
||||||
form.setValue("collectionToken", collectionToken || "");
|
}, [buildID, userTypeID, partID, companyID, personID, form]);
|
||||||
form.setValue("userTypeID", userTypeID || "");
|
|
||||||
form.setValue("partID", partID || "");
|
|
||||||
form.setValue("companyID", companyID || "");
|
|
||||||
form.setValue("personID", personID || "");
|
|
||||||
}, [buildID, collectionToken, userTypeID, partID, companyID, personID, form]);
|
|
||||||
|
|
||||||
const mutation = useAddLivingSpaceMutation();
|
const mutation = useAddLivingSpaceMutation();
|
||||||
function onSubmit(values: FormValues) { mutation.mutate({ data: values }) }
|
function onSubmit(values: FormValues) { mutation.mutate({ data: values }) }
|
||||||
|
|
@ -40,13 +39,15 @@ const PageLivingSpaceAdd = () => {
|
||||||
|
|
||||||
const tabsClassName = "border border-gray-300 rounded-sm h-10"
|
const tabsClassName = "border border-gray-300 rounded-sm h-10"
|
||||||
const deleteAllSelections = () => {
|
const deleteAllSelections = () => {
|
||||||
setBuildID(null); setCollectionToken(null); setUserTypeID(null); setPartID(null); setCompanyID(null); setPersonID(null);
|
setBuildID(null); setUserTypeID(null); setPartID(null); setCompanyID(null); setPersonID(null); setIsUserTypeEnabled(false); setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(false)
|
||||||
setIsUserTypeEnabled(false); setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
<div className="flex flex-col m-7">
|
<div className="flex flex-col m-7">
|
||||||
<Tabs defaultValue="builds" className="w-full">
|
<Tabs defaultValue="builds" className="w-full">
|
||||||
|
<Button className="my-3 h-10" variant="outline" size="sm" onClick={() => { router.push("/living-spaces") }}>
|
||||||
|
<IconArrowLeftToArc /><span className="hidden lg:inline">Back to Living Space List</span>
|
||||||
|
</Button>
|
||||||
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
|
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
|
||||||
<TabsTrigger className={tabsClassName} value="builds">Builds</TabsTrigger>
|
<TabsTrigger className={tabsClassName} value="builds">Builds</TabsTrigger>
|
||||||
{isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
|
{isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
|
||||||
|
|
@ -56,7 +57,7 @@ const PageLivingSpaceAdd = () => {
|
||||||
</TabsList>
|
</TabsList>
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<TabsContent value="builds">
|
<TabsContent value="builds">
|
||||||
<PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} collectionToken={collectionToken} setCollectionToken={setCollectionToken} 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} />
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ import { toISOIfNotZ } from '@/lib/utils'
|
||||||
|
|
||||||
export const formSchema = z.object({
|
export const formSchema = z.object({
|
||||||
buildID: z.string({ error: "Build ID is required" }),
|
buildID: z.string({ error: "Build ID is required" }),
|
||||||
collectionToken: z.string({ error: "Collection Token is required" }),
|
|
||||||
userTypeID: z.string({ error: "User Type ID is required" }),
|
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||||
partID: z.string({ error: "Part ID is required" }),
|
partID: z.string({ error: "Part ID is required" }),
|
||||||
companyID: z.string({ error: "Company ID is required" }),
|
companyID: z.string({ error: "Company ID is required" }),
|
||||||
|
|
@ -22,7 +21,7 @@ const fetchGraphQlLivingSpaceAdd = async (record: schemaType): Promise<{ data: s
|
||||||
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
||||||
console.dir({ record })
|
console.dir({ record })
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/living-spaces/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
const res = await fetch('/api/living-space/add', { 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();
|
||||||
return { data: data.data, status: res.status }
|
return { data: data.data, status: res.status }
|
||||||
|
|
@ -34,7 +33,7 @@ const fetchGraphQlLivingSpaceUpdate = async (record: schemaType, uuid: string):
|
||||||
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;
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/living-spaces/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
const res = await fetch(`/api/living-space/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();
|
||||||
return { data: data.data, status: res.status }
|
return { data: data.data, status: res.status }
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ import { FormProps } from "./types";
|
||||||
|
|
||||||
export const formSchema = z.object({
|
export const formSchema = z.object({
|
||||||
buildID: z.string({ error: "Build ID is required" }),
|
buildID: z.string({ error: "Build ID is required" }),
|
||||||
collectionToken: z.string({ error: "Collection Token is required" }),
|
|
||||||
userTypeID: z.string({ error: "User Type ID is required" }),
|
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||||
partID: z.string({ error: "Part ID is required" }),
|
partID: z.string({ error: "Part ID is required" }),
|
||||||
companyID: z.string({ error: "Company ID is required" }),
|
companyID: z.string({ error: "Company ID is required" }),
|
||||||
|
|
@ -16,12 +15,11 @@ export const formSchema = z.object({
|
||||||
|
|
||||||
export type FormValues = z.infer<typeof formSchema>;
|
export type FormValues = z.infer<typeof formSchema>;
|
||||||
|
|
||||||
export function createForm({ buildID, collectionToken, userTypeID, partID, companyID, personID }: FormProps) {
|
export function createForm({ buildID, userTypeID, partID, companyID, personID }: FormProps) {
|
||||||
return useForm<FormValues>({
|
return useForm<FormValues>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
buildID: buildID || "",
|
buildID: buildID || "",
|
||||||
collectionToken: collectionToken || "",
|
|
||||||
userTypeID: userTypeID || "",
|
userTypeID: userTypeID || "",
|
||||||
partID: partID || "",
|
partID: partID || "",
|
||||||
companyID: companyID || "",
|
companyID: companyID || "",
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
interface FormProps {
|
interface FormProps {
|
||||||
buildID: string | null;
|
buildID: string | null;
|
||||||
collectionToken: string | null;
|
|
||||||
userTypeID: string | null;
|
userTypeID: string | null;
|
||||||
partID: string | null;
|
partID: string | null;
|
||||||
companyID: string | null;
|
companyID: string | null;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
'use client';
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import PageLivingSpaceBuildsTableSection from "../tables/builds/page";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { IconPlus } from "@tabler/icons-react";
|
||||||
|
import { LivingSpaceDataTable } from "../tables/living-spaces/list/data-table";
|
||||||
|
import { useGraphQlLivingSpaceList } from "./queries";
|
||||||
|
|
||||||
|
const PageLivingSpaceList = () => {
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
const [buildID, setBuildID] = useState<string | null>(null);
|
||||||
|
// const [collectionToken, setCollectionToken] = useState<string | null>(null);
|
||||||
|
const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(false);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [limit, setLimit] = useState(10);
|
||||||
|
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||||
|
const [filters, setFilters] = useState({});
|
||||||
|
|
||||||
|
useEffect(() => { console.log(`buildID: ${buildID} is changed.`) }, [buildID]);
|
||||||
|
const additionButtons = <>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => { router.push("/living-spaces/add") }}>
|
||||||
|
<IconPlus /><span className="hidden lg:inline">Add Living Space</span>
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
const { data, isLoading, refetch } = useGraphQlLivingSpaceList(buildID || '', { limit, skip: (page - 1) * limit, sort, filters });
|
||||||
|
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||||
|
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<div className="flex flex-col gap-2.5">
|
||||||
|
<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>
|
||||||
|
{
|
||||||
|
buildID && <LivingSpaceDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PageLivingSpaceList };
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { ListArguments } from '@/types/listRequest'
|
||||||
|
|
||||||
|
const fetchGraphQlLivingSpaceList = async (buildID: string, params: ListArguments): Promise<any> => {
|
||||||
|
console.log('Fetching test data from local API');
|
||||||
|
const { limit, skip, sort, filters } = params;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/living-space/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ buildID, 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 }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useGraphQlLivingSpaceList(buildID: string, params: ListArguments) {
|
||||||
|
return useQuery({ queryKey: ['graphql-living-space-list', buildID, params], queryFn: () => fetchGraphQlLivingSpaceList(buildID, params) })
|
||||||
|
}
|
||||||
|
|
@ -26,6 +26,10 @@ export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof sche
|
||||||
|
|
||||||
function getColumns(selectionHandler: (id: string, token: string) => void): ColumnDef<schemaType>[] {
|
function getColumns(selectionHandler: (id: string, token: string) => void): ColumnDef<schemaType>[] {
|
||||||
return [
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: "_id",
|
||||||
|
header: "ID",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "buildType.token",
|
accessorKey: "buildType.token",
|
||||||
header: "Token",
|
header: "Token",
|
||||||
|
|
|
||||||
|
|
@ -80,9 +80,8 @@ export function LivingSpaceBuildDataTable({
|
||||||
refetchTable,
|
refetchTable,
|
||||||
buildId,
|
buildId,
|
||||||
setBuildId,
|
setBuildId,
|
||||||
collectionToken,
|
|
||||||
setCollectionToken,
|
|
||||||
setIsUserTypeEnabled,
|
setIsUserTypeEnabled,
|
||||||
|
additionButtons
|
||||||
}: {
|
}: {
|
||||||
data: schemaType[],
|
data: schemaType[],
|
||||||
totalCount: number,
|
totalCount: number,
|
||||||
|
|
@ -93,9 +92,8 @@ export function LivingSpaceBuildDataTable({
|
||||||
refetchTable: () => void,
|
refetchTable: () => void,
|
||||||
buildId: string,
|
buildId: string,
|
||||||
setBuildId: (id: string) => void,
|
setBuildId: (id: string) => void,
|
||||||
collectionToken: string,
|
|
||||||
setCollectionToken: (collectionToken: string) => void,
|
|
||||||
setIsUserTypeEnabled: (enabled: boolean) => void,
|
setIsUserTypeEnabled: (enabled: boolean) => void,
|
||||||
|
additionButtons: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
@ -107,7 +105,7 @@ export function LivingSpaceBuildDataTable({
|
||||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||||
|
|
||||||
const setSelection = (id: string, token: string) => { setBuildId(id); setCollectionToken(token); setIsUserTypeEnabled(true); }
|
const setSelection = (id: string) => { setBuildId(id); setIsUserTypeEnabled(true); }
|
||||||
const columns = getColumns(setSelection);
|
const columns = getColumns(setSelection);
|
||||||
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)
|
||||||
|
|
@ -170,6 +168,7 @@ export function LivingSpaceBuildDataTable({
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
|
{additionButtons && additionButtons}
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -4,12 +4,11 @@ import { useGraphQlBuildsList } from "./queries";
|
||||||
import { LivingSpaceBuildDataTable } from "./data-table";
|
import { LivingSpaceBuildDataTable } from "./data-table";
|
||||||
|
|
||||||
const PageLivingSpaceBuildsTableSection = (
|
const PageLivingSpaceBuildsTableSection = (
|
||||||
{ buildID, setBuildID, collectionToken, setCollectionToken, setIsUserTypeEnabled }: {
|
{ buildID, setBuildID, setIsUserTypeEnabled, additionButtons }: {
|
||||||
buildID: string | null;
|
buildID: string | null;
|
||||||
setBuildID: (id: string | null) => void;
|
setBuildID: (id: string | null) => void;
|
||||||
collectionToken: string | null;
|
|
||||||
setCollectionToken: (token: string | null) => void;
|
|
||||||
setIsUserTypeEnabled: (enabled: boolean) => void;
|
setIsUserTypeEnabled: (enabled: boolean) => void;
|
||||||
|
additionButtons?: React.ReactNode | null;
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
|
@ -27,8 +26,8 @@ const PageLivingSpaceBuildsTableSection = (
|
||||||
return <>
|
return <>
|
||||||
<LivingSpaceBuildDataTable
|
<LivingSpaceBuildDataTable
|
||||||
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}
|
||||||
refetchTable={refetch} buildId={buildID || ""} setBuildId={setBuildID} collectionToken={collectionToken || ""} setCollectionToken={setCollectionToken}
|
refetchTable={refetch} buildId={buildID || ""} setBuildId={setBuildID}
|
||||||
setIsUserTypeEnabled={setIsUserTypeEnabled} />
|
setIsUserTypeEnabled={setIsUserTypeEnabled} additionButtons={additionButtons} />
|
||||||
</>;
|
</>;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,91 @@
|
||||||
|
"use client"
|
||||||
|
import { z } from "zod"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { useSortable } from "@dnd-kit/sortable"
|
||||||
|
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"
|
||||||
|
|
||||||
|
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-dragging={isDragging} ref={setNodeRef}
|
||||||
|
className={`${row.original._id === selectedID ? "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(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: "uuid",
|
||||||
|
header: "UUID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "build",
|
||||||
|
header: "Build",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "part",
|
||||||
|
header: "Part",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "userType",
|
||||||
|
header: "User Type",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "company",
|
||||||
|
header: "Company",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "person",
|
||||||
|
header: "Person",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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 (
|
||||||
|
<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}`) }}>
|
||||||
|
<Pencil />
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||||
|
<Trash />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getColumns };
|
||||||
|
|
@ -0,0 +1,265 @@
|
||||||
|
"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 { useDeleteLivingSpacesMutation } from "./queries"
|
||||||
|
|
||||||
|
export function LivingSpaceDataTable({
|
||||||
|
data,
|
||||||
|
totalCount,
|
||||||
|
currentPage = 1,
|
||||||
|
pageSize = 10,
|
||||||
|
onPageChange,
|
||||||
|
onPageSizeChange,
|
||||||
|
refetchTable,
|
||||||
|
}: {
|
||||||
|
data: schemaType[],
|
||||||
|
totalCount: number,
|
||||||
|
currentPage?: number,
|
||||||
|
pageSize?: number,
|
||||||
|
onPageChange: (page: number) => void,
|
||||||
|
onPageSizeChange: (size: number) => void,
|
||||||
|
refetchTable: () => 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 deleteMutation = useDeleteLivingSpacesMutation()
|
||||||
|
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
|
||||||
|
const columns = getColumns(router, deleteHandler);
|
||||||
|
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>
|
||||||
|
</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">
|
||||||
|
{table.getRowModel().rows?.length ? (
|
||||||
|
<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||||
|
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={""} key={row.id} row={row} />)}
|
||||||
|
</SortableContext>) : (
|
||||||
|
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||||
|
)}
|
||||||
|
</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 >
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
'use client'
|
||||||
|
import { useMutation } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
const fetchGraphQlDeleteLivingSpace = async (uuid: string): Promise<boolean> => {
|
||||||
|
console.log('Fetching test data from local API');
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/living-space/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();
|
||||||
|
return data
|
||||||
|
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useDeleteLivingSpacesMutation() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteLivingSpace(uuid),
|
||||||
|
onSuccess: () => { console.log("Living space deleted successfully") },
|
||||||
|
onError: (error) => { console.error("Delete living space failed:", error) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const schema = z.object({
|
||||||
|
|
||||||
|
_id: z.string(),
|
||||||
|
uuid: z.string(),
|
||||||
|
build: z.string(),
|
||||||
|
part: z.string(),
|
||||||
|
userType: z.string(),
|
||||||
|
company: z.string(),
|
||||||
|
person: z.string(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
expiryEnds: z.string(),
|
||||||
|
expiryStarts: z.string(),
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type schemaType = z.infer<typeof schema>;
|
||||||
|
|
@ -73,7 +73,6 @@ import {
|
||||||
} from "@/components/ui/tabs"
|
} from "@/components/ui/tabs"
|
||||||
import { schemaType } from "./schema"
|
import { schemaType } from "./schema"
|
||||||
import { getColumns, DraggableRow } from "./columns"
|
import { getColumns, DraggableRow } from "./columns"
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
|
|
||||||
export function LivingSpaceUserTypesDataTable({
|
export function LivingSpaceUserTypesDataTable({
|
||||||
data,
|
data,
|
||||||
|
|
@ -84,6 +83,7 @@ export function LivingSpaceUserTypesDataTable({
|
||||||
onPageSizeChange,
|
onPageSizeChange,
|
||||||
refetchTable,
|
refetchTable,
|
||||||
userTypeID,
|
userTypeID,
|
||||||
|
setIsProperty,
|
||||||
setUserTypeID,
|
setUserTypeID,
|
||||||
setIsPartsEnabled,
|
setIsPartsEnabled,
|
||||||
setIsHandleCompanyAndPersonEnable,
|
setIsHandleCompanyAndPersonEnable,
|
||||||
|
|
@ -96,6 +96,7 @@ export function LivingSpaceUserTypesDataTable({
|
||||||
onPageSizeChange: (size: number) => void,
|
onPageSizeChange: (size: number) => void,
|
||||||
refetchTable: () => void,
|
refetchTable: () => void,
|
||||||
userTypeID: string | null;
|
userTypeID: string | null;
|
||||||
|
setIsProperty: (enabled: boolean | null) => void;
|
||||||
setUserTypeID: (id: string | null) => void;
|
setUserTypeID: (id: string | null) => void;
|
||||||
setIsPartsEnabled: (enabled: boolean) => void;
|
setIsPartsEnabled: (enabled: boolean) => void;
|
||||||
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
||||||
|
|
@ -107,7 +108,7 @@ export function LivingSpaceUserTypesDataTable({
|
||||||
const sortableId = React.useId()
|
const sortableId = React.useId()
|
||||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||||
const setSelection = (id: string, isProperty: boolean) => { setUserTypeID(id); isProperty ? setIsPartsEnabled(true) : setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(true) }
|
const setSelection = (id: string, isProperty: boolean) => { setUserTypeID(id); isProperty ? setIsPartsEnabled(true) : setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(true); setIsProperty(isProperty) }
|
||||||
const columns = getColumns(setSelection);
|
const columns = getColumns(setSelection);
|
||||||
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)
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,9 @@ import { useGraphQlUserTypesList } from "./queries";
|
||||||
import { LivingSpaceUserTypesDataTable } from "./data-table";
|
import { LivingSpaceUserTypesDataTable } from "./data-table";
|
||||||
|
|
||||||
const PageLivingSpaceUserTypesTableSection = (
|
const PageLivingSpaceUserTypesTableSection = (
|
||||||
{ userTypeID, setUserTypeID, setIsPartsEnabled, setIsHandleCompanyAndPersonEnable }: {
|
{ userTypeID, setUserTypeID, setIsPartsEnabled, setIsHandleCompanyAndPersonEnable, setIsProperty }: {
|
||||||
userTypeID: string | null;
|
userTypeID: string | null;
|
||||||
|
setIsProperty: (enabled: boolean | null) => void;
|
||||||
setUserTypeID: (id: string | null) => void;
|
setUserTypeID: (id: string | null) => void;
|
||||||
setIsPartsEnabled: (enabled: boolean) => void;
|
setIsPartsEnabled: (enabled: boolean) => void;
|
||||||
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
||||||
|
|
@ -24,7 +25,7 @@ const PageLivingSpaceUserTypesTableSection = (
|
||||||
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 <>
|
||||||
<LivingSpaceUserTypesDataTable
|
<LivingSpaceUserTypesDataTable
|
||||||
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} setIsProperty={setIsProperty}
|
||||||
refetchTable={refetch} userTypeID={userTypeID || ""} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable}
|
refetchTable={refetch} userTypeID={userTypeID || ""} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable}
|
||||||
/>
|
/>
|
||||||
</>;
|
</>;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,131 @@
|
||||||
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||||
|
import { DateTimePicker } from "@/components/ui/date-time-picker";
|
||||||
|
import { FormValues } from "./schema";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
|
||||||
|
const FormUpdateNewLivingSpace = ({ form, onSubmit }: { form: any, onSubmit: (data: FormValues) => void }) => {
|
||||||
|
return <>
|
||||||
|
<Card className="m-7">
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
{/* <FormField
|
||||||
|
control={form.control}
|
||||||
|
name="buildID"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>Build ID</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/> */}
|
||||||
|
{/* <FormField
|
||||||
|
control={form.control}
|
||||||
|
name="collectionToken"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>Collection Token</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/> */}
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="userTypeID"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>User Type ID</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="partID"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>Part ID</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="companyID"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>Company ID</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="personID"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="mt-3">
|
||||||
|
<FormLabel>Person ID</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/* EXPIRY DATES */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-7">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="expiryStarts"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Expiry Starts</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<DateTimePicker {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="expiryEnds"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Expiry Ends</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<DateTimePicker {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-4"><Button type="submit">Submit</Button></div>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
|
||||||
|
export { FormUpdateNewLivingSpace };
|
||||||
|
|
@ -0,0 +1,92 @@
|
||||||
|
'use client';
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { FormValues, createForm } from "./schema";
|
||||||
|
import { FormUpdateNewLivingSpace } from "./form";
|
||||||
|
import { useUpdateLivingSpaceMutation } from "./queries";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { IconArrowLeftToArc } from "@tabler/icons-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useGraphQlLivingSpaceList } from "../list/queries";
|
||||||
|
import { useSearchParams } from "next/navigation";
|
||||||
|
|
||||||
|
import PageLivingSpaceBuildsTableSection from "../tables/builds/page";
|
||||||
|
import PageLivingSpaceUserTypesTableSection from "../tables/userType/page";
|
||||||
|
import PageLivingSpacePartsTableSection from "../tables/part/page";
|
||||||
|
import PageLivingSpacePersonTableSection from "../tables/person/page";
|
||||||
|
import PageLivingSpaceCompanyTableSection from "../tables/company/page";
|
||||||
|
|
||||||
|
const PageLivingSpaceUpdate = () => {
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const uuid = searchParams?.get('uuid') || 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 { data, isLoading, refetch } = useGraphQlLivingSpaceList(buildIDFromUrl || '', { limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||||
|
const initData = data?.data?.[0] || null;
|
||||||
|
const [userTypeID, setUserTypeID] = useState<string | null>(null);
|
||||||
|
const isPartInit = initData?.part !== null ? true : false;
|
||||||
|
const [isProperty, setIsProperty] = useState<boolean | null>(isPartInit);
|
||||||
|
const [partID, setPartID] = useState<string | null>(null);
|
||||||
|
const [companyID, setCompanyID] = useState<string | null>(null);
|
||||||
|
const [personID, setPersonID] = useState<string | null>(null);
|
||||||
|
const form = createForm({ userTypeID: initData?.userType || "", partID: initData?.part || "", companyID: initData?.company || "", personID: initData?.person || "" });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (initData) {
|
||||||
|
form.setValue("userTypeID", initData?.userType || ""); form.setValue("partID", initData?.part || ""); form.setValue("companyID", initData?.company || "");
|
||||||
|
form.setValue("personID", initData?.person || ""); form.setValue("expiryStarts", initData?.expiryStarts || ""); form.setValue("expiryEnds", initData?.expiryEnds || "");
|
||||||
|
setUserTypeID(initData?.userType || ""); setPartID(initData?.part || ""); setCompanyID(initData?.company || ""); setPersonID(initData?.person || "");
|
||||||
|
}
|
||||||
|
}, [initData])
|
||||||
|
useEffect(() => {
|
||||||
|
form.setValue("userTypeID", userTypeID || ""); form.setValue("partID", partID || ""); form.setValue("companyID", companyID || ""); form.setValue("personID", personID || "");
|
||||||
|
}, [userTypeID, partID, companyID, personID, form]);
|
||||||
|
|
||||||
|
const mutation = useUpdateLivingSpaceMutation();
|
||||||
|
function onSubmit(values: FormValues) { mutation.mutate({ data: values, uuid: uuid || "", buildID: buildIDFromUrl || "" }) }
|
||||||
|
const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(true);
|
||||||
|
const [isPartsEnabled, setIsPartsEnabled] = useState(false);
|
||||||
|
const [isHandleCompanyAndPersonEnable, setIsHandleCompanyAndPersonEnable] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => { if (!!isProperty) { setIsPartsEnabled(true) } else { setPartID(null); setIsPartsEnabled(false) } }, [isProperty])
|
||||||
|
useEffect(() => { if (isPartInit) { setIsPartsEnabled(true) } else { setIsPartsEnabled(false) } }, [isPartInit])
|
||||||
|
|
||||||
|
if (!uuid) { return backToBuildAddress }; if (!initData) { return backToBuildAddress }
|
||||||
|
const tabsClassName = "border border-gray-300 rounded-sm h-10"
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<div className="flex flex-col m-7">
|
||||||
|
<Tabs defaultValue="usertype" className="w-full">
|
||||||
|
<Button className="my-3 h-10" variant="outline" size="sm" onClick={() => { router.push("/living-spaces") }}>
|
||||||
|
<IconArrowLeftToArc /><span className="hidden lg:inline">Back to Living Space List</span>
|
||||||
|
</Button>
|
||||||
|
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
|
||||||
|
{isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
|
||||||
|
{isPartsEnabled && <TabsTrigger className={tabsClassName} value="parts">Parts</TabsTrigger>}
|
||||||
|
{isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="company">Company</TabsTrigger>}
|
||||||
|
{isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="person">Person</TabsTrigger>}
|
||||||
|
</TabsList>
|
||||||
|
<div className="mt-6">
|
||||||
|
{isUserTypeEnabled && <TabsContent value="usertype">
|
||||||
|
<PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsProperty={setIsProperty} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable} />
|
||||||
|
</TabsContent>}
|
||||||
|
{isPartsEnabled && buildIDFromUrl && <TabsContent value="parts">
|
||||||
|
<PageLivingSpacePartsTableSection buildId={buildIDFromUrl} partID={partID} setPartID={setPartID} setIsPartsEnabled={setIsPartsEnabled} />
|
||||||
|
</TabsContent>}
|
||||||
|
{isHandleCompanyAndPersonEnable && <TabsContent value="company"><PageLivingSpaceCompanyTableSection companyID={companyID} setCompanyID={setCompanyID} /></TabsContent>}
|
||||||
|
{isHandleCompanyAndPersonEnable && <TabsContent value="person"><PageLivingSpacePersonTableSection personID={personID} setPersonID={setPersonID} /></TabsContent>}
|
||||||
|
</div>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
<div><FormUpdateNewLivingSpace form={form} onSubmit={onSubmit} /></div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PageLivingSpaceUpdate };
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
'use client'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { useMutation } from '@tanstack/react-query'
|
||||||
|
import { toISOIfNotZ } from '@/lib/utils'
|
||||||
|
|
||||||
|
export const formSchema = z.object({
|
||||||
|
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||||
|
partID: z.string({ error: "Part ID is required" }),
|
||||||
|
companyID: z.string({ error: "Company ID is required" }),
|
||||||
|
personID: z.string({ error: "Person ID is required" }),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type schemaType = z.infer<typeof formSchema>;
|
||||||
|
|
||||||
|
const fetchGraphQlLivingSpaceUpdate = async (record: schemaType, uuid: string, buildID: string): Promise<{ data: schemaType | null; status: number }> => {
|
||||||
|
console.log('Fetching test data from local API');
|
||||||
|
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
|
||||||
|
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/living-space/update?uuid=${uuid || ''}&buildID=${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}`) }
|
||||||
|
const data = await res.json();
|
||||||
|
return { data: data.data, status: res.status }
|
||||||
|
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export function useUpdateLivingSpaceMutation() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ data, uuid, buildID }: { data: schemaType, uuid: string, buildID: string }) => fetchGraphQlLivingSpaceUpdate(data, uuid, buildID),
|
||||||
|
onSuccess: () => { console.log("Living Space updated successfully") },
|
||||||
|
onError: (error) => { console.error("Update Living Space update failed:", error) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
import * as z from "zod";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { FormProps } from "./types";
|
||||||
|
|
||||||
|
export const formSchema = z.object({
|
||||||
|
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||||
|
partID: z.string({ error: "Part ID is required" }),
|
||||||
|
companyID: z.string({ error: "Company ID is required" }),
|
||||||
|
personID: z.string({ error: "Person ID is required" }),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type FormValues = z.infer<typeof formSchema>;
|
||||||
|
|
||||||
|
export function createForm({ userTypeID, partID, companyID, personID }: FormProps) {
|
||||||
|
return useForm<FormValues>({
|
||||||
|
resolver: zodResolver(formSchema),
|
||||||
|
defaultValues: {
|
||||||
|
userTypeID: userTypeID || "",
|
||||||
|
partID: partID || "",
|
||||||
|
companyID: companyID || "",
|
||||||
|
personID: personID || "",
|
||||||
|
expiryStarts: "",
|
||||||
|
expiryEnds: ""
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
interface FormProps {
|
||||||
|
userTypeID: string | null;
|
||||||
|
partID: string | null;
|
||||||
|
companyID: string | null;
|
||||||
|
personID: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type { FormProps };
|
||||||
Loading…
Reference in New Issue