parts and areas tested
This commit is contained in:
parent
a5a7a7e7b5
commit
eedfed1a65
|
|
@ -14,6 +14,7 @@ import { BuildTypesModule } from './build-types/build-types.module';
|
||||||
import { BuildAddressModule } from './build-address/build-address.module';
|
import { BuildAddressModule } from './build-address/build-address.module';
|
||||||
import { BuildIbanModule } from './build-iban/build-iban.module';
|
import { BuildIbanModule } from './build-iban/build-iban.module';
|
||||||
import { BuildSitesModule } from './build-sites/build-sites.module';
|
import { BuildSitesModule } from './build-sites/build-sites.module';
|
||||||
|
import { CompanyModule } from './company/company.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
|
@ -33,6 +34,7 @@ import { BuildSitesModule } from './build-sites/build-sites.module';
|
||||||
BuildAddressModule,
|
BuildAddressModule,
|
||||||
BuildIbanModule,
|
BuildIbanModule,
|
||||||
BuildSitesModule,
|
BuildSitesModule,
|
||||||
|
CompanyModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [AppService],
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,13 @@ import { BuildAreaResolver } from './build-area.resolver';
|
||||||
import { BuildAreaService } from './build-area.service';
|
import { BuildAreaService } from './build-area.service';
|
||||||
import { MongooseModule } from '@nestjs/mongoose';
|
import { MongooseModule } from '@nestjs/mongoose';
|
||||||
import { BuildArea, BuildAreaSchema } from '@/models/build-area.model';
|
import { BuildArea, BuildAreaSchema } from '@/models/build-area.model';
|
||||||
|
import { Build, BuildSchema } from '@/models/build.model';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [MongooseModule.forFeature([{ name: BuildArea.name, schema: BuildAreaSchema }])],
|
imports: [MongooseModule.forFeature([
|
||||||
|
{ name: BuildArea.name, schema: BuildAreaSchema },
|
||||||
|
{ name: Build.name, schema: BuildSchema }
|
||||||
|
])],
|
||||||
providers: [BuildAreaResolver, BuildAreaService]
|
providers: [BuildAreaResolver, BuildAreaService]
|
||||||
})
|
})
|
||||||
export class BuildAreaModule { }
|
export class BuildAreaModule { }
|
||||||
|
|
|
||||||
|
|
@ -6,25 +6,32 @@ import { CreateBuildAreaInput } from './dto/create-build-area.input';
|
||||||
import { ListBuildAreaResponse } from './dto/list-build-area.response';
|
import { ListBuildAreaResponse } from './dto/list-build-area.response';
|
||||||
import { UpdateBuildAreaInput } from './dto/update-build-area.input';
|
import { UpdateBuildAreaInput } from './dto/update-build-area.input';
|
||||||
import { ListArguments } from '@/dto/list.input';
|
import { ListArguments } from '@/dto/list.input';
|
||||||
|
import { Build, BuildDocument } from '@/models/build.model';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BuildAreaService {
|
export class BuildAreaService {
|
||||||
|
|
||||||
constructor(@InjectModel(BuildArea.name) private readonly buildAreaModel: Model<BuildAreaDocument>) { }
|
constructor(
|
||||||
|
@InjectModel(BuildArea.name) private readonly buildAreaModel: Model<BuildAreaDocument>,
|
||||||
|
@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>
|
||||||
|
) { }
|
||||||
|
|
||||||
async findAll(projection: any, listArguments: ListArguments): Promise<ListBuildAreaResponse> {
|
async findAll(projection: any, listArguments: ListArguments): Promise<ListBuildAreaResponse> {
|
||||||
const { skip, limit, sort, filters } = listArguments;
|
const { skip, limit, sort, filters } = listArguments;
|
||||||
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 (filters?.buildId) { query.buildId = new Types.ObjectId(filters?.buildId) };
|
||||||
const totalCount = await this.buildAreaModel.countDocuments(query).exec();
|
const totalCount = await this.buildAreaModel.countDocuments(query).exec();
|
||||||
const data = await this.buildAreaModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
const data = await this.buildAreaModel.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<BuildAreaDocument | null> {
|
async findById(id: Types.ObjectId, projection?: any): Promise<BuildAreaDocument | null> { return this.buildAreaModel.findById(id, projection, { lean: false }).populate({ path: 'buildArea', select: projection?.buildArea }).exec() }
|
||||||
return this.buildAreaModel.findById(id, projection, { lean: false }).populate({ path: 'buildArea', select: projection?.buildArea }).exec();
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(input: CreateBuildAreaInput): Promise<BuildAreaDocument> { const buildArea = new this.buildAreaModel(input); return buildArea.save() }
|
async create(input: CreateBuildAreaInput): Promise<BuildAreaDocument> {
|
||||||
|
const getBuildID = await this.buildModel.findById(input?.buildId, { _id: 1 }, { lean: true }).exec();
|
||||||
|
if (getBuildID) { input.buildId = new Types.ObjectId(getBuildID._id) };
|
||||||
|
const buildArea = new this.buildAreaModel(input); return buildArea.save()
|
||||||
|
}
|
||||||
|
|
||||||
async update(uuid: string, input: UpdateBuildAreaInput): Promise<BuildAreaDocument> { const buildArea = await this.buildAreaModel.findOne({ uuid }); if (!buildArea) { throw new Error('BuildArea not found') }; buildArea.set(input); return buildArea.save() }
|
async update(uuid: string, input: UpdateBuildAreaInput): Promise<BuildAreaDocument> { const buildArea = await this.buildAreaModel.findOne({ uuid }); if (!buildArea) { throw new Error('BuildArea not found') }; buildArea.set(input); return buildArea.save() }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,20 @@
|
||||||
|
import { ExpiryBaseInput } from "@/models/base.model";
|
||||||
import { InputType, Field, ID, Float } from "@nestjs/graphql";
|
import { InputType, Field, ID, Float } from "@nestjs/graphql";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class CreateBuildAreaInput {
|
export class CreateBuildAreaInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: false })
|
||||||
|
buildId: Types.ObjectId;
|
||||||
|
|
||||||
@Field(() => ID, { nullable: true })
|
@Field(() => ID, { nullable: true })
|
||||||
build?: Types.ObjectId;
|
partTypeId?: Types.ObjectId;
|
||||||
|
|
||||||
@Field(() => ID, { nullable: true })
|
@Field()
|
||||||
partType?: Types.ObjectId;
|
|
||||||
|
|
||||||
@Field(() => Float)
|
|
||||||
areaName: string;
|
areaName: string;
|
||||||
|
|
||||||
@Field(() => Float)
|
@Field()
|
||||||
areaCode: string;
|
areaCode: string;
|
||||||
|
|
||||||
@Field()
|
@Field()
|
||||||
|
|
@ -22,16 +23,16 @@ export class CreateBuildAreaInput {
|
||||||
@Field()
|
@Field()
|
||||||
areaDirection: string;
|
areaDirection: string;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
areaGrossSize: number;
|
areaGrossSize: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
areaNetSize: number;
|
areaNetSize: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
width: number;
|
width: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
size: number;
|
size: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,10 +10,10 @@ export class UpdateBuildAreaInput {
|
||||||
@Field(() => ID, { nullable: true })
|
@Field(() => ID, { nullable: true })
|
||||||
partType?: Types.ObjectId;
|
partType?: Types.ObjectId;
|
||||||
|
|
||||||
@Field(() => Float, { nullable: true })
|
@Field({ nullable: true })
|
||||||
areaName?: string;
|
areaName?: string;
|
||||||
|
|
||||||
@Field(() => Float, { nullable: true })
|
@Field({ nullable: true })
|
||||||
areaCode?: string;
|
areaCode?: string;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
|
|
@ -22,16 +22,16 @@ export class UpdateBuildAreaInput {
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
areaDirection?: string;
|
areaDirection?: string;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field(() => Float, { nullable: true })
|
||||||
areaGrossSize?: number;
|
areaGrossSize?: number;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field(() => Float, { nullable: true })
|
||||||
areaNetSize?: number;
|
areaNetSize?: number;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field(() => Float, { nullable: true })
|
||||||
width?: number;
|
width?: number;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field(() => Float, { nullable: true })
|
||||||
size?: number;
|
size?: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -31,8 +31,7 @@ export class BuildIbanService {
|
||||||
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 } }
|
if (key === 'buildIban' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`buildIban.${subField}`] = 1 } } else { projection[key] = 1 }
|
||||||
else { projection[key] = 1 }
|
|
||||||
}; return projection;
|
}; return projection;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,12 @@ import { BuildPartsService } from './build-parts.service';
|
||||||
import { BuildPartsResolver } from './build-parts.resolver';
|
import { BuildPartsResolver } from './build-parts.resolver';
|
||||||
import { MongooseModule } from '@nestjs/mongoose';
|
import { MongooseModule } from '@nestjs/mongoose';
|
||||||
import { BuildParts, BuildPartsSchema } from '@/models/build-parts.model';
|
import { BuildParts, BuildPartsSchema } from '@/models/build-parts.model';
|
||||||
|
import { Build, BuildSchema } from '@/models/build.model';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [MongooseModule.forFeature([{ name: BuildParts.name, schema: BuildPartsSchema }])],
|
imports: [MongooseModule.forFeature([
|
||||||
|
{ name: BuildParts.name, schema: BuildPartsSchema },
|
||||||
|
{ name: Build.name, schema: BuildSchema }])],
|
||||||
providers: [BuildPartsService, BuildPartsResolver]
|
providers: [BuildPartsService, BuildPartsResolver]
|
||||||
})
|
})
|
||||||
export class BuildPartsModule { }
|
export class BuildPartsModule { }
|
||||||
|
|
@ -2,27 +2,36 @@ import { Resolver, Query, Args, ID, Info, Mutation } from '@nestjs/graphql';
|
||||||
import { Types } from 'mongoose';
|
import { Types } from 'mongoose';
|
||||||
import { BuildParts } from '@/models/build-parts.model';
|
import { BuildParts } from '@/models/build-parts.model';
|
||||||
import { CreateBuildPartsInput } from './dto/create-build-part.input';
|
import { CreateBuildPartsInput } from './dto/create-build-part.input';
|
||||||
|
import { BuildPartsService } from './build-parts.service';
|
||||||
|
import { ListArguments } from '@/dto/list.input';
|
||||||
|
import { ListBuildPartsResponse } from './dto/list-build-parts.response';
|
||||||
import graphqlFields from 'graphql-fields';
|
import graphqlFields from 'graphql-fields';
|
||||||
import type { GraphQLResolveInfo } from 'graphql';
|
import type { GraphQLResolveInfo } from 'graphql';
|
||||||
import { BuildPartsService } from './build-parts.service';
|
import { UpdateBuildPartsInput } from './dto/update-build-parts.input';
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class BuildPartsResolver {
|
export class BuildPartsResolver {
|
||||||
|
|
||||||
constructor(private readonly buildPartsService: BuildPartsService) { }
|
constructor(private readonly buildPartsService: BuildPartsService) { }
|
||||||
|
|
||||||
@Query(() => [BuildParts], { name: 'BuildParts' })
|
@Query(() => ListBuildPartsResponse, { name: 'buildParts' })
|
||||||
async getBuildParts(@Info() info: GraphQLResolveInfo): Promise<BuildParts[]> {
|
async getBuildParts(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListBuildPartsResponse> {
|
||||||
const fields = graphqlFields(info); const projection = this.buildPartsService.buildProjection(fields); return this.buildPartsService.findAll(projection);
|
const fields = graphqlFields(info); const projection = this.buildPartsService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
||||||
|
return await this.buildPartsService.findAll(projection, skip, limit, sort, filters);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => BuildParts, { name: 'BuildParts', nullable: true })
|
@Query(() => BuildParts, { name: 'buildPart', nullable: true })
|
||||||
async getBuildPart(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<BuildParts | null> {
|
async getBuildPart(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<BuildParts | null> {
|
||||||
const fields = graphqlFields(info); const projection = this.buildPartsService.buildProjection(fields); return this.buildPartsService.findById(new Types.ObjectId(id), projection);
|
const fields = graphqlFields(info); const projection = this.buildPartsService.buildProjection(fields); return this.buildPartsService.findById(new Types.ObjectId(id), projection);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => BuildParts, { name: 'createBuildPart' })
|
@Mutation(() => BuildParts, { name: 'createBuildPart' })
|
||||||
async createBuildPart(@Args('input') input: CreateBuildPartsInput): Promise<BuildParts> {
|
async createBuildPart(@Args('input') input: CreateBuildPartsInput): Promise<BuildParts> { return this.buildPartsService.create(input) }
|
||||||
return this.buildPartsService.create(input);
|
|
||||||
}
|
@Mutation(() => Boolean, { name: 'deleteBuildPart' })
|
||||||
|
async deleteBuildPart(@Args('uuid') uuid: string): Promise<boolean> { return this.buildPartsService.delete(uuid) }
|
||||||
|
|
||||||
|
@Mutation(() => BuildParts, { name: 'updateBuildPart' })
|
||||||
|
async updateBuildPart(@Args('uuid') uuid: string, @Args('input') input: UpdateBuildPartsInput): Promise<BuildParts> { return this.buildPartsService.update(uuid, input) }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,24 @@ import { InjectModel } from '@nestjs/mongoose';
|
||||||
import { Types, Model } from 'mongoose';
|
import { Types, Model } from 'mongoose';
|
||||||
import { BuildParts, BuildPartsDocument } from '@/models/build-parts.model';
|
import { BuildParts, BuildPartsDocument } from '@/models/build-parts.model';
|
||||||
import { CreateBuildPartsInput } from './dto/create-build-part.input';
|
import { CreateBuildPartsInput } from './dto/create-build-part.input';
|
||||||
|
import { ListBuildPartsResponse } from './dto/list-build-parts.response';
|
||||||
|
import { UpdateBuildPartsInput } from './dto/update-build-parts.input';
|
||||||
|
import { Build, BuildDocument } from '@/models/build.model';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BuildPartsService {
|
export class BuildPartsService {
|
||||||
|
|
||||||
constructor(@InjectModel(BuildParts.name) private readonly buildPartsModel: Model<BuildPartsDocument>) { }
|
constructor(
|
||||||
|
@InjectModel(BuildParts.name) private readonly buildPartsModel: Model<BuildPartsDocument>,
|
||||||
|
@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>
|
||||||
|
) { }
|
||||||
|
|
||||||
async findAll(projection?: any): Promise<BuildPartsDocument[]> {
|
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildPartsResponse> {
|
||||||
return this.buildPartsModel.find({}, projection, { lean: false }).populate({ path: 'buildParts', select: projection?.buildParts }).exec();
|
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.buildPartsModel.countDocuments(query).exec();
|
||||||
|
const data = await this.buildPartsModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
||||||
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
async findById(id: Types.ObjectId, projection?: any): Promise<BuildPartsDocument | null> {
|
async findById(id: Types.ObjectId, projection?: any): Promise<BuildPartsDocument | null> {
|
||||||
|
|
@ -18,10 +28,22 @@ export class BuildPartsService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(input: CreateBuildPartsInput): Promise<BuildPartsDocument> {
|
async create(input: CreateBuildPartsInput): Promise<BuildPartsDocument> {
|
||||||
const buildParts = new this.buildPartsModel(input);
|
const getBuildID = await this.buildModel.findById(input?.buildId, { _id: 1 }, { lean: true }).exec();
|
||||||
return buildParts.save();
|
if (getBuildID) { input.buildId = new Types.ObjectId(getBuildID._id) };
|
||||||
|
if (input?.directionId) { input.directionId = new Types.ObjectId(input?.directionId) };
|
||||||
|
if (input?.typeId) { input.typeId = new Types.ObjectId(input?.typeId) };
|
||||||
|
const buildParts = new this.buildPartsModel(input); return buildParts.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async update(uuid: string, input: UpdateBuildPartsInput): Promise<BuildPartsDocument> {
|
||||||
|
const buildParts = await this.buildPartsModel.findOne({ _id: new Types.ObjectId(uuid) }); if (!buildParts) { throw new Error('BuildParts not found') };
|
||||||
|
if (input?.buildId) { const getBuildID = await this.buildModel.findById(input?.buildId, { _id: 1 }, { lean: true }).exec(); if (getBuildID) { input.buildId = new Types.ObjectId(getBuildID._id) } };
|
||||||
|
if (input?.directionId) { input.directionId = new Types.ObjectId(input?.directionId) };
|
||||||
|
if (input?.typeId) { input.typeId = new Types.ObjectId(input?.typeId) }; buildParts.set(input); return buildParts.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(uuid: string): Promise<boolean> { console.log(uuid); const buildParts = await this.buildPartsModel.deleteMany({ _id: new Types.ObjectId(uuid) }); return buildParts.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) {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,55 @@
|
||||||
import { InputType, Field, ID } from '@nestjs/graphql';
|
import { InputType, Field, ID, Float } from '@nestjs/graphql';
|
||||||
|
import { Types } from 'mongoose';
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class CreateBuildPartsInput {
|
export class CreateBuildPartsInput {
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID, { nullable: false })
|
||||||
build: string;
|
buildId: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field({ nullable: false })
|
||||||
|
addressGovCode: string;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: false })
|
||||||
|
no: number;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: false })
|
||||||
|
level: number;
|
||||||
|
|
||||||
|
@Field({ nullable: false })
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: false })
|
||||||
|
grossSize: number;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: false })
|
||||||
|
netSize: number;
|
||||||
|
|
||||||
|
@Field({ nullable: false })
|
||||||
|
defaultAccessory: string;
|
||||||
|
|
||||||
|
@Field({ nullable: false })
|
||||||
|
humanLivability: boolean;
|
||||||
|
|
||||||
|
@Field({ nullable: false })
|
||||||
|
key: string;
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: true })
|
||||||
|
directionId: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: true })
|
||||||
|
typeId: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field(() => Boolean, { nullable: false })
|
||||||
|
active: boolean;
|
||||||
|
|
||||||
|
@Field(() => Boolean, { nullable: false })
|
||||||
|
isConfirmed: boolean;
|
||||||
|
|
||||||
|
@Field(() => String, { nullable: true })
|
||||||
|
expiryStarts: string;
|
||||||
|
|
||||||
|
@Field(() => String, { nullable: true })
|
||||||
|
expiryEnds: string;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { BuildParts } from "@/models/build-parts.model";
|
||||||
|
import { Field, Int, ObjectType } from "@nestjs/graphql";
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class ListBuildPartsResponse {
|
||||||
|
|
||||||
|
@Field(() => [BuildParts], { nullable: true })
|
||||||
|
data?: BuildParts[];
|
||||||
|
|
||||||
|
@Field(() => Int, { nullable: true })
|
||||||
|
totalCount?: number;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
import { ExpiryBaseInput } from "@/models/base.model";
|
||||||
|
import { InputType, Field, ID, Float } from "@nestjs/graphql";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class UpdateBuildPartsInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: true })
|
||||||
|
buildId?: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
addressGovCode?: string;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: true })
|
||||||
|
no?: number;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: true })
|
||||||
|
level?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
code?: string;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: true })
|
||||||
|
grossSize?: number;
|
||||||
|
|
||||||
|
@Field(() => Float, { nullable: true })
|
||||||
|
netSize?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
defaultAccessory?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
humanLivability?: boolean;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
key?: string;
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: true })
|
||||||
|
directionId?: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field(() => ID, { nullable: true })
|
||||||
|
typeId?: Types.ObjectId;
|
||||||
|
|
||||||
|
@Field(() => Boolean, { nullable: true })
|
||||||
|
active?: boolean;
|
||||||
|
|
||||||
|
@Field(() => Boolean, { nullable: true })
|
||||||
|
isConfirmed?: boolean;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,7 @@ import { UpdateBuildSitesInput } from './dto/update-build-sites.input';
|
||||||
import { InjectModel } from '@nestjs/mongoose';
|
import { InjectModel } from '@nestjs/mongoose';
|
||||||
import { BuildSites, BuildSiteDocument } from '@/models/build-site.model';
|
import { BuildSites, BuildSiteDocument } from '@/models/build-site.model';
|
||||||
import { Model } from 'mongoose';
|
import { Model } from 'mongoose';
|
||||||
|
import { Build, BuildDocument } from '@/models/build.model';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BuildSitesService {
|
export class BuildSitesService {
|
||||||
|
|
@ -23,7 +24,10 @@ export class BuildSitesService {
|
||||||
return this.buildSitesModel.findById(id, projection, { lean: false }).populate({ path: 'buildSites', select: projection?.buildSites }).exec();
|
return this.buildSitesModel.findById(id, projection, { lean: false }).populate({ path: 'buildSites', select: projection?.buildSites }).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(input: CreateBuildSitesInput): Promise<BuildSiteDocument> { const buildSite = new this.buildSitesModel(input); return buildSite.save() }
|
async create(input: CreateBuildSitesInput): Promise<BuildSiteDocument> {
|
||||||
|
|
||||||
|
const buildSite = new this.buildSitesModel(input); return buildSite.save()
|
||||||
|
}
|
||||||
|
|
||||||
async update(uuid: string, input: UpdateBuildSitesInput): Promise<BuildSiteDocument> { const buildSite = await this.buildSitesModel.findOne({ uuid }); if (!buildSite) { throw new Error('BuildSite not found') }; buildSite.set(input); return buildSite.save() }
|
async update(uuid: string, input: UpdateBuildSitesInput): Promise<BuildSiteDocument> { const buildSite = await this.buildSitesModel.findOne({ uuid }); if (!buildSite) { throw new Error('BuildSite not found') }; buildSite.set(input); return buildSite.save() }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import { ChangableBase } from "@/models/base.model";
|
import { ExpiryBaseInput } from "@/models/base.model";
|
||||||
import { InputType, Field } from "@nestjs/graphql";
|
import { InputType, Field } from "@nestjs/graphql";
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdateBuildTypesInput extends ChangableBase {
|
export class UpdateBuildTypesInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
type?: string;
|
type?: string;
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,18 @@
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { BuildResolver } from './build.resolver';
|
import { BuildResolver } from './build.resolver';
|
||||||
import { MongooseModule } from '@nestjs/mongoose';
|
import { MongooseModule } from '@nestjs/mongoose';
|
||||||
import { BuildSchema } from '@/models/build.model';
|
import { BuildSchema, BuildIbanSchema } from '@/models/build.model';
|
||||||
import { BuildService } from './build.service';
|
import { BuildService } from './build.service';
|
||||||
|
import { BuildAreaSchema } from '@/models/build-area.model';
|
||||||
|
import { CompanySchema } from '@/models/company.model';
|
||||||
|
import { PersonSchema } from '@/models/person.model';
|
||||||
|
import { BuildTypesSchema } from '@/models/build-types.model';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [MongooseModule.forFeature([{ name: 'Build', schema: BuildSchema }])],
|
imports: [MongooseModule.forFeature([
|
||||||
|
{ name: 'Build', schema: BuildSchema }, { name: 'BuildArea', schema: BuildAreaSchema }, { name: 'BuildIban', schema: BuildIbanSchema },
|
||||||
|
{ name: 'Company', schema: CompanySchema }, { name: 'Person', schema: PersonSchema }, { name: 'BuildTypes', schema: BuildTypesSchema },
|
||||||
|
])],
|
||||||
providers: [BuildResolver, BuildService]
|
providers: [BuildResolver, BuildService]
|
||||||
})
|
})
|
||||||
export class BuildModule { }
|
export class BuildModule { }
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
|
import graphqlFields from 'graphql-fields';
|
||||||
import { Resolver, Query, Args, ID, Info, Mutation } from '@nestjs/graphql';
|
import { Resolver, Query, Args, ID, Info, Mutation } from '@nestjs/graphql';
|
||||||
import { Types } from 'mongoose';
|
import { Types } from 'mongoose';
|
||||||
import { Build } from '@/models/build.model';
|
import { Build } from '@/models/build.model';
|
||||||
import { CreateBuildInput } from './dto/create-build.input';
|
import { CreateBuildInput } from './dto/create-build.input';
|
||||||
import { UpdateBuildResponsibleInput, UpdateBuildAttributeInput } from './dto/update-build.input';
|
import { UpdateBuildResponsibleInput, UpdateBuildAttributeInput, UpdateBuildInput } from './dto/update-build.input';
|
||||||
import graphqlFields from 'graphql-fields';
|
|
||||||
import { BuildService } from './build.service';
|
import { BuildService } from './build.service';
|
||||||
import type { GraphQLResolveInfo } from 'graphql';
|
|
||||||
import { ListArguments } from '@/dto/list.input';
|
import { ListArguments } from '@/dto/list.input';
|
||||||
import { ListBuildResponse } from './dto/list-build.response';
|
import { ListBuildResponse, ListPartialAreaResponse, ListPartialCompanyResponse, ListPartialIbanResponse } from './dto/list-build.response';
|
||||||
|
import type { GraphQLResolveInfo } from 'graphql';
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class BuildResolver {
|
export class BuildResolver {
|
||||||
|
|
@ -16,7 +16,22 @@ export class BuildResolver {
|
||||||
|
|
||||||
@Query(() => ListBuildResponse, { name: 'builds' })
|
@Query(() => ListBuildResponse, { name: 'builds' })
|
||||||
async getBuilds(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListBuildResponse> {
|
async getBuilds(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListBuildResponse> {
|
||||||
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findAll(projection, input.skip, input.limit, input.sort, input.filters);
|
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findAll(input.skip, input.limit, input.sort, input.filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => ListPartialAreaResponse, { name: 'getBuildsAreas' })
|
||||||
|
async getBuildsAreas(@Info() info: GraphQLResolveInfo, @Args('id') id: string, @Args('input') input: ListArguments): Promise<ListPartialAreaResponse> {
|
||||||
|
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findAllAreas(id, input.skip, input.limit, input.sort, input.filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => ListPartialIbanResponse, { name: 'getBuildsIbans' })
|
||||||
|
async getBuildsIbans(@Info() info: GraphQLResolveInfo, @Args('id') id: string, @Args('input') input: ListArguments): Promise<ListPartialIbanResponse> {
|
||||||
|
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findAllIbans(id, input.skip, input.limit, input.sort, input.filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => ListPartialCompanyResponse, { name: 'getBuildsCompaniesAndResponsibles' })
|
||||||
|
async getBuildsCompaniesAndResponsibles(@Info() info: GraphQLResolveInfo, @Args('id') id: string, @Args('input') input: ListArguments): Promise<ListPartialCompanyResponse> {
|
||||||
|
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findAllCompaniesAndResponsibles(id, input.skip, input.limit, input.sort, input.filters);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => Build, { name: 'build', nullable: true })
|
@Query(() => Build, { name: 'build', nullable: true })
|
||||||
|
|
@ -24,17 +39,19 @@ export class BuildResolver {
|
||||||
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findById(new Types.ObjectId(id), projection);
|
const fields = graphqlFields(info); const projection = this.buildService.buildProjection(fields); return this.buildService.findById(new Types.ObjectId(id), projection);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Mutation(() => Boolean, { name: 'deleteBuild' })
|
||||||
|
async deleteBuild(@Args('uuid') uuid: string): Promise<boolean> { return this.buildService.delete(uuid) }
|
||||||
|
|
||||||
@Mutation(() => Build, { name: 'createBuild' })
|
@Mutation(() => Build, { name: 'createBuild' })
|
||||||
async createBuild(@Args('input') input: CreateBuildInput): Promise<Build> { return this.buildService.create(input) }
|
async createBuild(@Args('input') input: CreateBuildInput): Promise<Build> { return this.buildService.create(input) }
|
||||||
|
|
||||||
|
@Mutation(() => Build, { name: 'updateBuild' })
|
||||||
|
async updateBuild(@Args('uuid') uuid: string, @Args('input') input: UpdateBuildInput): Promise<Build> { return this.buildService.update(uuid, input) }
|
||||||
|
|
||||||
@Mutation(() => Build, { name: 'updateBuildResponsible' })
|
@Mutation(() => Build, { name: 'updateBuildResponsible' })
|
||||||
async updateBuildResponsible(@Args('uuid', { type: () => ID }) uuid: string, @Args('input') input: UpdateBuildResponsibleInput): Promise<Build> {
|
async updateBuildResponsible(@Args('uuid') uuid: string, @Args('input') input: UpdateBuildResponsibleInput): Promise<Build> { return this.buildService.updateResponsible(uuid, input) }
|
||||||
return this.buildService.updateResponsible(uuid, input);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Mutation(() => Build, { name: 'updateBuildAttribute' })
|
@Mutation(() => Build, { name: 'updateBuildAttribute' })
|
||||||
async updateBuildAttribute(@Args('uuid', { type: () => ID }) uuid: string, @Args('input') input: UpdateBuildAttributeInput): Promise<Build> {
|
async updateBuildAttribute(@Args('uuid') uuid: string, @Args('input') input: UpdateBuildAttributeInput): Promise<Build> { return this.buildService.updateAttribute(uuid, input) }
|
||||||
return this.buildService.updateAttribute(uuid, input);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,32 @@
|
||||||
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 { Build, BuildDocument } from '@/models/build.model';
|
import { Build, BuildDocument, BuildIban, BuildIbanDocument } from '@/models/build.model';
|
||||||
import { CreateBuildInput } from './dto/create-build.input';
|
import { CreateBuildInput } from './dto/create-build.input';
|
||||||
import { UpdateBuildAttributeInput, UpdateBuildResponsibleInput } from './dto/update-build.input';
|
import { UpdateBuildAttributeInput, UpdateBuildInput, UpdateBuildResponsibleInput } from './dto/update-build.input';
|
||||||
import { ListBuildResponse } from './dto/list-build.response';
|
import { ListBuildResponse, ListPartialAreaResponse, ListPartialCompanyResponse, ListPartialIbanResponse } from './dto/list-build.response';
|
||||||
|
import { cleanRefArrayField } from '@/lib/getListOfModelByIDs';
|
||||||
|
import { BuildArea, BuildAreaDocument } from '@/models/build-area.model';
|
||||||
|
import { Company, CompanyDocument } from '@/models/company.model';
|
||||||
|
import { Person, PersonDocument } from '@/models/person.model';
|
||||||
|
import { BuildTypes, BuildTypesDocument } from '@/models/build-types.model';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BuildService {
|
export class BuildService {
|
||||||
|
|
||||||
constructor(@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>) { }
|
constructor(
|
||||||
|
@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>,
|
||||||
|
@InjectModel(BuildArea.name) private readonly areaModel: Model<BuildAreaDocument>,
|
||||||
|
@InjectModel(BuildIban.name) private readonly ibanModel: Model<BuildIbanDocument>,
|
||||||
|
@InjectModel(Company.name) private readonly companyModel: Model<CompanyDocument>,
|
||||||
|
@InjectModel(Person.name) private readonly personModel: Model<PersonDocument>,
|
||||||
|
@InjectModel(BuildTypes.name) private readonly buildTypeModel: Model<BuildTypesDocument>,
|
||||||
|
) { }
|
||||||
|
|
||||||
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildResponse> {
|
async findAll(skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildResponse> {
|
||||||
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.buildModel.countDocuments(query).exec();
|
const totalCount = await this.buildModel.countDocuments(query).exec();
|
||||||
const data = await this.buildModel.find(query).skip(skip).limit(limit).sort(sort).exec();
|
const data = await this.buildModel.find(query).populate('buildType').skip(skip).limit(limit).sort(sort).exec();
|
||||||
return { data, totalCount };
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -22,14 +34,98 @@ export class BuildService {
|
||||||
return this.buildModel.findById(id, projection, { lean: false }).populate({ path: 'buildArea', select: projection?.buildArea }).exec();
|
return this.buildModel.findById(id, projection, { lean: false }).populate({ path: 'buildArea', select: projection?.buildArea }).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(input: CreateBuildInput): Promise<BuildDocument> { const buildArea = new this.buildModel(input); return buildArea.save() }
|
async create(input: CreateBuildInput): Promise<BuildDocument> {
|
||||||
|
const getObjectIDofToken = await this.buildTypeModel.findOne({ token: input.buildType });
|
||||||
|
const build = new this.buildModel(input);
|
||||||
|
if (!getObjectIDofToken?._id) { throw new Error('Build type not found') }
|
||||||
|
const idOfBuildTypes = new Types.ObjectId(getObjectIDofToken._id)
|
||||||
|
build.set({ buildType: idOfBuildTypes });
|
||||||
|
await build.populate('buildType')
|
||||||
|
return build.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(uuid: string, input: UpdateBuildInput): Promise<BuildDocument> {
|
||||||
|
let idOfBuildTypes: Types.ObjectId | null = null;
|
||||||
|
if (input.buildType) {
|
||||||
|
const buildTypeDoc = await this.buildTypeModel.findOne({ token: input.buildType });
|
||||||
|
if (!buildTypeDoc?._id) { throw new Error('Build type not found') }; idOfBuildTypes = new Types.ObjectId(buildTypeDoc._id);
|
||||||
|
}
|
||||||
|
const build = await this.buildModel.findById(new Types.ObjectId(uuid));
|
||||||
|
if (!build) { throw new Error('Build not found') }
|
||||||
|
const { info, buildType: _ignoredBuildType, ...rest } = input;
|
||||||
|
if (Object.keys(rest).length > 0) { build.set(rest) }
|
||||||
|
if (info) { build.set({ info: { ...(build.info as any)?.toObject?.() ?? build.info ?? {}, ...info } }) }
|
||||||
|
if (idOfBuildTypes) { build.set({ buildType: idOfBuildTypes }) }
|
||||||
|
const saved = await build.save(); await saved.populate('buildType'); return saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(uuid: string): Promise<boolean> {
|
||||||
|
const build = await this.buildModel.deleteMany({ _id: new Types.ObjectId(uuid) }); return build.deletedCount > 0;
|
||||||
|
}
|
||||||
|
|
||||||
async updateResponsible(uuid: string, input: UpdateBuildResponsibleInput): Promise<BuildDocument> {
|
async updateResponsible(uuid: string, input: UpdateBuildResponsibleInput): Promise<BuildDocument> {
|
||||||
const build = await this.buildModel.findOne({ uuid }); if (!build) { throw new Error('Build not found') }; build.set({ responsible: input }); return build.save()
|
const build = await this.buildModel.findOne({ _id: new Types.ObjectId(uuid) }); if (!build) { throw new Error('Build not found') }; build.set({ responsible: input }); return build.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateAttribute(uuid: string, input: UpdateBuildAttributeInput): Promise<BuildDocument> {
|
async updateAttribute(uuid: string, input: UpdateBuildAttributeInput): Promise<BuildDocument> {
|
||||||
const build = await this.buildModel.findOne({ uuid }); if (!build) { throw new Error('Build not found') }; build.set({ attribute: input }); return build.save()
|
const build = await this.buildModel.findOne({ _id: new Types.ObjectId(uuid) }); if (!build) { throw new Error('Build not found') }; build.set({ attribute: input }); return build.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllAreas(id: string, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListPartialAreaResponse> {
|
||||||
|
const buildId = new Types.ObjectId(id);
|
||||||
|
const { keptIds } = await cleanRefArrayField({ parentModel: this.buildModel, refModel: this.areaModel, parentId: buildId, fieldName: "areas", });
|
||||||
|
if (keptIds.length === 0) { return { data: [], totalCount: 0 } }
|
||||||
|
const query: any = { _id: { $in: keptIds } };
|
||||||
|
if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) }
|
||||||
|
const totalCount = await this.areaModel.countDocuments(query).exec();
|
||||||
|
const data = await this.areaModel.find(query).skip(skip).limit(limit).sort(sort).exec();
|
||||||
|
return { data, totalCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllIbans(id: string, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListPartialIbanResponse> {
|
||||||
|
const buildId = new Types.ObjectId(id);
|
||||||
|
const { keptIds } = await cleanRefArrayField({ parentModel: this.buildModel, refModel: this.ibanModel, parentId: buildId, fieldName: "ibans", });
|
||||||
|
if (keptIds.length === 0) { return { data: [], totalCount: 0 } }
|
||||||
|
const query: any = { _id: { $in: keptIds } };
|
||||||
|
if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) }
|
||||||
|
const totalCount = await this.ibanModel.countDocuments(query).exec();
|
||||||
|
const data = await this.ibanModel.find(query).skip(skip).limit(limit).sort(sort).exec();
|
||||||
|
return { data, totalCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllCompaniesAndResponsibles(id: string, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListPartialCompanyResponse> {
|
||||||
|
const buildId = new Types.ObjectId(id);
|
||||||
|
const build = await this.buildModel.findById(buildId).lean();
|
||||||
|
if (!build) throw new Error('Build not found');
|
||||||
|
const responsibles = (build.responsibles || []) as { company?: string; person?: string }[];
|
||||||
|
if (responsibles.length === 0) { return { data: [], totalCount: 0 } }
|
||||||
|
console.dir({ responsibles }, { depth: Infinity });
|
||||||
|
const companyIds = Array.from(new Set(responsibles.map(r => r.company).filter((id): id is string => !!id))).map(id => new Types.ObjectId(id));
|
||||||
|
const personIds = Array.from(new Set(responsibles.map(r => r.person).filter((id): id is string => !!id))).map(id => new Types.ObjectId(id));
|
||||||
|
console.dir({ companyIds, personIds }, { depth: Infinity });
|
||||||
|
const t = await this.companyModel.find({ _id: { $in: companyIds } })
|
||||||
|
const l = await this.companyModel.find({ _id: { $in: companyIds } }).lean()
|
||||||
|
console.dir({ t, l }, { depth: Infinity })
|
||||||
|
const [companies, persons] = await Promise.all([this.companyModel.find({ _id: { $in: companyIds } }).lean(), this.personModel.find({ _id: { $in: personIds } }).lean(),]);
|
||||||
|
console.dir({ companies, persons }, { depth: Infinity })
|
||||||
|
const companyMap = new Map(companies.map(c => [String(c._id), c]));
|
||||||
|
const personMap = new Map(persons.map(p => [String(p._id), p]));
|
||||||
|
const cleanedResponsibles: { company?: string; person?: string }[] = [];
|
||||||
|
const resolvedList: { company?: any; person?: any }[] = [];
|
||||||
|
for (const r of responsibles) {
|
||||||
|
const companyId = r.company && String(r.company);
|
||||||
|
const personId = r.person && String(r.person);
|
||||||
|
const companyDoc = companyId ? companyMap.get(companyId) : undefined;
|
||||||
|
const personDoc = personId ? personMap.get(personId) : undefined;
|
||||||
|
if ((companyId && !companyDoc) || (personId && !personDoc)) { continue }
|
||||||
|
cleanedResponsibles.push({ company: companyId, person: personId });
|
||||||
|
resolvedList.push({ company: companyDoc, person: personDoc });
|
||||||
|
}
|
||||||
|
console.dir({ buildId, cleanedResponsibles, resolvedList }, { depth: Infinity });
|
||||||
|
await this.buildModel.updateOne({ _id: buildId }, { $set: { responsibles: cleanedResponsibles } });
|
||||||
|
const totalCount = resolvedList.length;
|
||||||
|
const data = resolvedList.slice(skip, skip + limit);
|
||||||
|
return { data, totalCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
buildProjection(fields: Record<string, any>): any {
|
buildProjection(fields: Record<string, any>): any {
|
||||||
|
|
|
||||||
|
|
@ -49,15 +49,15 @@ export class CreateBuildInfoInput {
|
||||||
@Field()
|
@Field()
|
||||||
garageCount: number;
|
garageCount: number;
|
||||||
|
|
||||||
@Field()
|
@Field({ nullable: true })
|
||||||
managementRoomId: number;
|
managementRoomId?: string;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class CreateBuildInput extends ExpiryBaseInput {
|
export class CreateBuildInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field()
|
||||||
buildType: string;
|
buildType: string;
|
||||||
|
|
||||||
@Field()
|
@Field()
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
import { Build } from "@/models/build.model";
|
|
||||||
import { Field, Int, ObjectType } from "@nestjs/graphql";
|
import { Field, Int, ObjectType } from "@nestjs/graphql";
|
||||||
|
import { Build, BuildIban } from "@/models/build.model";
|
||||||
|
import { BuildArea } from "@/models/build-area.model";
|
||||||
|
import { Company } from "@/models/company.model";
|
||||||
|
import { Person } from "@/models/person.model";
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class ListBuildResponse {
|
export class ListBuildResponse {
|
||||||
|
|
@ -11,3 +14,44 @@ export class ListBuildResponse {
|
||||||
totalCount?: number;
|
totalCount?: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class ListPartialAreaResponse {
|
||||||
|
|
||||||
|
@Field(() => [BuildArea], { nullable: true })
|
||||||
|
data?: BuildArea[];
|
||||||
|
|
||||||
|
@Field(() => Int, { nullable: true })
|
||||||
|
totalCount?: number;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class ListPartialIbanResponse {
|
||||||
|
|
||||||
|
@Field(() => [BuildIban], { nullable: true })
|
||||||
|
data?: BuildIban[];
|
||||||
|
|
||||||
|
@Field(() => Int, { nullable: true })
|
||||||
|
totalCount?: number;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
class ResponsibleCompanyPerson {
|
||||||
|
@Field(() => Company, { nullable: true })
|
||||||
|
company?: Company;
|
||||||
|
|
||||||
|
@Field(() => Person, { nullable: true })
|
||||||
|
person?: Person;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class ListPartialCompanyResponse {
|
||||||
|
|
||||||
|
@Field(() => [ResponsibleCompanyPerson])
|
||||||
|
data: ResponsibleCompanyPerson[];
|
||||||
|
|
||||||
|
@Field(() => Int)
|
||||||
|
totalCount: number;
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { InputType, Field, ID } from "@nestjs/graphql";
|
import { InputType, Field, ID } from "@nestjs/graphql";
|
||||||
|
import { ExpiryBaseInput } from "@/models/base.model";
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdateResponsibleInput {
|
export class UpdateResponsibleInput {
|
||||||
|
|
@ -41,3 +42,70 @@ export class UpdateBuildResponsibleInput {
|
||||||
person?: string;
|
person?: string;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class UpdateBuildInfoInput {
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
govAddressCode?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
buildName?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
buildNo?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
maxFloor?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
undergroundFloor?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
buildDate?: Date;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
decisionPeriodDate?: Date;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
taxNo?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
liftCount?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
heatingSystem?: boolean;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
coolingSystem?: boolean;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
hotWaterSystem?: boolean;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
blockServiceManCount?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
securityServiceManCount?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
garageCount?: number;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
managementRoomId?: number;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class UpdateBuildInput extends ExpiryBaseInput {
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
buildType?: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
collectionToken?: string;
|
||||||
|
|
||||||
|
@Field(() => UpdateBuildInfoInput, { nullable: true })
|
||||||
|
info?: UpdateBuildInfoInput;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -60,3 +60,53 @@ mutation CreateBuild($input: CreateBuildInput!) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
query ListBuild($input: ListArguments!) {
|
||||||
|
builds(input: $input) {
|
||||||
|
data {
|
||||||
|
_id
|
||||||
|
buildType {
|
||||||
|
token
|
||||||
|
typeToken
|
||||||
|
type
|
||||||
|
}
|
||||||
|
collectionToken
|
||||||
|
info {
|
||||||
|
govAddressCode
|
||||||
|
buildName
|
||||||
|
buildNo
|
||||||
|
maxFloor
|
||||||
|
undergroundFloor
|
||||||
|
buildDate
|
||||||
|
decisionPeriodDate
|
||||||
|
taxNo
|
||||||
|
liftCount
|
||||||
|
heatingSystem
|
||||||
|
coolingSystem
|
||||||
|
hotWaterSystem
|
||||||
|
blockServiceManCount
|
||||||
|
securityServiceManCount
|
||||||
|
garageCount
|
||||||
|
managementRoomId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
totalCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
query GetBuildsAreas($id: String!, $input: ListArguments!) {
|
||||||
|
getBuildsAreas(id: $id, input: $input) {
|
||||||
|
data {
|
||||||
|
_id
|
||||||
|
uuid
|
||||||
|
areaName
|
||||||
|
areaCode
|
||||||
|
areaType
|
||||||
|
areaNetSize
|
||||||
|
areaDirection
|
||||||
|
areaGrossSize
|
||||||
|
}
|
||||||
|
totalCount
|
||||||
|
__typename
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { CompanyService } from './company.service';
|
||||||
|
import { CompanyResolver } from './company.resolver';
|
||||||
|
import { MongooseModule } from '@nestjs/mongoose';
|
||||||
|
import { Company, CompanySchema } from '@/models/company.model';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [MongooseModule.forFeature([{ name: Company.name, schema: CompanySchema }])],
|
||||||
|
providers: [CompanyService, CompanyResolver]
|
||||||
|
})
|
||||||
|
export class CompanyModule { }
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { CompanyResolver } from './company.resolver';
|
||||||
|
|
||||||
|
describe('CompanyResolver', () => {
|
||||||
|
let resolver: CompanyResolver;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [CompanyResolver],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
resolver = module.get<CompanyResolver>(CompanyResolver);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(resolver).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
import { Resolver, Args, ID, Info, Mutation, Query } from '@nestjs/graphql';
|
||||||
|
import { CompanyService } from './company.service';
|
||||||
|
import { Company } from '@/models/company.model';
|
||||||
|
import { CreateCompanyInput } from './dto/create-company.input';
|
||||||
|
import { Types } from 'mongoose';
|
||||||
|
import graphqlFields from 'graphql-fields';
|
||||||
|
import type { GraphQLResolveInfo } from 'graphql';
|
||||||
|
import { ListCompanyResponse } from './dto/list-company.response';
|
||||||
|
import { ListArguments } from '@/dto/list.input';
|
||||||
|
|
||||||
|
@Resolver()
|
||||||
|
export class CompanyResolver {
|
||||||
|
|
||||||
|
constructor(private readonly companyService: CompanyService) { }
|
||||||
|
|
||||||
|
@Query(() => ListCompanyResponse, { name: 'companies' })
|
||||||
|
async getCompanies(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListCompanyResponse> {
|
||||||
|
const fields = graphqlFields(info); const projection = this.companyService.buildProjection(fields); return this.companyService.findAll(input.skip, input.limit, input.sort, input.filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => Company, { name: 'company', nullable: true })
|
||||||
|
async getCompany(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<Company | null> {
|
||||||
|
const fields = graphqlFields(info); const projection = this.companyService.buildProjection(fields); return this.companyService.findById(new Types.ObjectId(id), projection);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mutation(() => Company, { name: 'createCompany' })
|
||||||
|
async createCompany(@Args('input') input: CreateCompanyInput): Promise<Company> { return this.companyService.create(input) }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { CompanyService } from './company.service';
|
||||||
|
|
||||||
|
describe('CompanyService', () => {
|
||||||
|
let service: CompanyService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [CompanyService],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<CompanyService>(CompanyService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectModel } from '@nestjs/mongoose';
|
||||||
|
import { Types, Model } from 'mongoose';
|
||||||
|
import { Company, CompanyDocument } from '@/models/company.model';
|
||||||
|
import { CreateCompanyInput } from './dto/create-company.input';
|
||||||
|
import { ListCompanyResponse } from './dto/list-company.response';
|
||||||
|
import { UpdateCompanyInput } from './dto/update-company.input';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CompanyService {
|
||||||
|
|
||||||
|
constructor(@InjectModel(Company.name) private readonly companyModel: Model<CompanyDocument>) { }
|
||||||
|
|
||||||
|
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListCompanyResponse> {
|
||||||
|
const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
|
||||||
|
const totalCount = await this.companyModel.countDocuments(query).exec();
|
||||||
|
const data = await this.companyModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
||||||
|
return { data, totalCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
async findById(id: Types.ObjectId, projection?: any): Promise<CompanyDocument | null> {
|
||||||
|
return this.companyModel.findById(id, projection, { lean: false }).populate({ path: 'company', select: projection?.company }).exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(input: CreateCompanyInput): Promise<CompanyDocument> { const company = new this.companyModel(input); return company.save() }
|
||||||
|
|
||||||
|
async update(uuid: string, input: UpdateCompanyInput): Promise<CompanyDocument> { const company = await this.companyModel.findOne({ uuid }); if (!company) { throw new Error('Company not found') }; company.set(input); return company.save() }
|
||||||
|
|
||||||
|
async delete(uuid: string): Promise<boolean> { const company = await this.companyModel.deleteMany({ uuid }); return company.deletedCount > 0 }
|
||||||
|
|
||||||
|
buildProjection(fields: Record<string, any>): any {
|
||||||
|
const projection: any = {};
|
||||||
|
for (const key in fields) {
|
||||||
|
if (key === 'buildSites' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`buildSites.${subField}`] = 1 } }
|
||||||
|
else { projection[key] = 1 }
|
||||||
|
}; return projection;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
|
||||||
|
import { InputType, Field, ID } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class CreateCompanyInput {
|
||||||
|
|
||||||
|
@Field()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
import { Field, ObjectType } from "@nestjs/graphql";
|
||||||
|
import { Int } from "@nestjs/graphql";
|
||||||
|
import { Company } from "@/models/company.model";
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class ListCompanyResponse {
|
||||||
|
|
||||||
|
@Field(() => [Company], { nullable: true })
|
||||||
|
data?: Company[];
|
||||||
|
|
||||||
|
@Field(() => Int, { nullable: true })
|
||||||
|
totalCount?: number;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { InputType, Field, ID } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class UpdateCompanyInput {
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { Types, Model } from "mongoose";
|
||||||
|
|
||||||
|
type ObjectIdLike = Types.ObjectId | string;
|
||||||
|
|
||||||
|
interface CleanRefArrayParams {
|
||||||
|
parentModel: Model<any>;
|
||||||
|
refModel: Model<any>;
|
||||||
|
parentId: ObjectIdLike;
|
||||||
|
fieldName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cleanRefArrayField({ parentModel, refModel, parentId, fieldName }: CleanRefArrayParams): Promise<{ keptIds: Types.ObjectId[]; removedIds: Types.ObjectId[] }> {
|
||||||
|
const parent = await parentModel.findById(parentId).lean();
|
||||||
|
if (!parent) { throw new Error("Parent document not found") }
|
||||||
|
const rawIds: ObjectIdLike[] = parent[fieldName] || [];
|
||||||
|
if (!Array.isArray(rawIds) || rawIds.length === 0) { return { keptIds: [], removedIds: [] } }
|
||||||
|
const ids = rawIds.map((id) => typeof id === "string" ? new Types.ObjectId(id) : id);
|
||||||
|
const existing = await refModel.find({ _id: { $in: ids } }).select("_id").lean();
|
||||||
|
const existingSet = new Set(existing.map((d) => String(d._id)));
|
||||||
|
const keptIds = ids.filter((id) => existingSet.has(String(id)));
|
||||||
|
const removedIds = ids.filter((id) => !existingSet.has(String(id)));
|
||||||
|
await parentModel.updateOne({ _id: parentId }, { $set: { [fieldName]: keptIds } });
|
||||||
|
return { keptIds, removedIds };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -10,11 +10,11 @@ export class BuildArea extends Base {
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
readonly _id: string;
|
readonly _id: string;
|
||||||
|
|
||||||
@Field(() => Float)
|
@Field()
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
areaName: string;
|
areaName: string;
|
||||||
|
|
||||||
@Field(() => Float)
|
@Field()
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
areaCode: string;
|
areaCode: string;
|
||||||
|
|
||||||
|
|
@ -26,19 +26,19 @@ export class BuildArea extends Base {
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
areaDirection: string;
|
areaDirection: string;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
areaGrossSize: number;
|
areaGrossSize: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
areaNetSize: number;
|
areaNetSize: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
width: number;
|
width: number;
|
||||||
|
|
||||||
@Field()
|
@Field(() => Float)
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
size: number;
|
size: number;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,9 @@ import { Base } from '@/models/base.model';
|
||||||
@Schema({ timestamps: true })
|
@Schema({ timestamps: true })
|
||||||
export class BuildParts extends Base {
|
export class BuildParts extends Base {
|
||||||
|
|
||||||
|
@Field(() => ID)
|
||||||
|
readonly _id: string;
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
@Prop({ type: Types.ObjectId, ref: 'Build', required: true })
|
@Prop({ type: Types.ObjectId, ref: 'Build', required: true })
|
||||||
buildId: Types.ObjectId;
|
buildId: Types.ObjectId;
|
||||||
|
|
@ -47,13 +50,14 @@ export class BuildParts extends Base {
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
key: string;
|
key: string;
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID, { nullable: true })
|
||||||
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: true })
|
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
|
||||||
directionId: Types.ObjectId;
|
directionId: Types.ObjectId;
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID, { nullable: true })
|
||||||
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: true })
|
@Prop({ type: Types.ObjectId, ref: 'ApiEnumDropdown', required: false })
|
||||||
typeId: Types.ObjectId;
|
typeId: Types.ObjectId;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BuildPartsDocument = BuildParts & Document;
|
export type BuildPartsDocument = BuildParts & Document;
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { ObjectType, Field, ID, Int } from '@nestjs/graphql';
|
||||||
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 { Company } from '@/models/company.model';
|
import { Company } from '@/models/company.model';
|
||||||
|
import { BuildTypes } from './build-types.model';
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
@Schema({ timestamps: true })
|
@Schema({ timestamps: true })
|
||||||
|
|
@ -37,13 +38,13 @@ export class BuildIban extends Base {
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class BuildResponsible {
|
export class BuildResponsible {
|
||||||
|
|
||||||
@Field(() => [String], { nullable: true, defaultValue: [] })
|
@Field(() => String, { nullable: true })
|
||||||
@Prop({ type: [String], default: [] })
|
@Prop({ type: String, default: '' })
|
||||||
company?: string[];
|
company?: string;
|
||||||
|
|
||||||
@Field(() => [String], { nullable: true, defaultValue: [] })
|
@Field(() => String, { nullable: true })
|
||||||
@Prop({ type: [String], default: [] })
|
@Prop({ type: String, default: '' })
|
||||||
person?: string[];
|
person?: string;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -110,9 +111,9 @@ export class BuildInfo {
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
garageCount: number;
|
garageCount: number;
|
||||||
|
|
||||||
@Field(() => Int)
|
@Field(() => String, { nullable: true })
|
||||||
@Prop({ required: true })
|
@Prop({ required: false })
|
||||||
managementRoomId: number;
|
managementRoomId?: string;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -123,13 +124,9 @@ export class Build {
|
||||||
@Field()
|
@Field()
|
||||||
readonly _id: string;
|
readonly _id: string;
|
||||||
|
|
||||||
// @Field(() => ID)
|
@Field(() => BuildTypes)
|
||||||
// @Prop({ type: Types.ObjectId, ref: 'BuildType', required: true })
|
@Prop({ type: Types.ObjectId, ref: BuildTypes.name, required: true })
|
||||||
// buildType: Types.ObjectId;
|
buildType: Types.ObjectId;
|
||||||
|
|
||||||
@Field(() => String, { nullable: true })
|
|
||||||
@Prop({ required: true })
|
|
||||||
buildType: string;
|
|
||||||
|
|
||||||
@Field(() => String, { nullable: true })
|
@Field(() => String, { nullable: true })
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,10 @@ import { Base } from '@/models/base.model';
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
@Schema({ timestamps: true })
|
@Schema({ timestamps: true })
|
||||||
export class Company extends Base {
|
export class Company extends Base {
|
||||||
|
|
||||||
|
@Field(() => ID)
|
||||||
|
readonly _id: string;
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
name: string;
|
name: string;
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import { UserType } from '@/models/user-type.model';
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class LivingSpaces extends Base {
|
export class LivingSpaces extends Base {
|
||||||
|
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
@Prop({ type: Types.ObjectId, ref: BuildParts.name, required: true })
|
@Prop({ type: Types.ObjectId, ref: BuildParts.name, required: true })
|
||||||
part: Types.ObjectId;
|
part: Types.ObjectId;
|
||||||
|
|
@ -25,8 +26,8 @@ export class LivingSpaces extends Base {
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
@Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
|
@Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
|
||||||
userType: Types.ObjectId;
|
userType: Types.ObjectId;
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
export type LivingSpacesDocument = LivingSpaces & Document;
|
export type LivingSpacesDocument = LivingSpaces & Document;
|
||||||
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);
|
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,10 @@ export class User extends Base {
|
||||||
@Field(() => ID)
|
@Field(() => ID)
|
||||||
_id: string;
|
_id: string;
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
@Prop({ required: false, default: '' })
|
||||||
|
avatar?: string;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
@Prop({ default: () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) })
|
@Prop({ default: () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) })
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,9 @@ export class CollectionTokenInput {
|
||||||
@InputType()
|
@InputType()
|
||||||
export class CreateUserInput {
|
export class CreateUserInput {
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
avatar?: string;
|
||||||
|
|
||||||
@Field()
|
@Field()
|
||||||
password: string;
|
password: string;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,9 @@ export class UpdateCollectionTokenInput {
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdateUserInput {
|
export class UpdateUserInput {
|
||||||
|
|
||||||
|
@Field({ nullable: true })
|
||||||
|
avatar?: string;
|
||||||
|
|
||||||
@Field({ nullable: true })
|
@Field({ nullable: true })
|
||||||
tag?: string;
|
tag?: string;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,8 +27,7 @@ export async function POST(request: Request) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
const variables = { input: validatedBody };
|
const data = await client.request(query, { input: validatedBody });
|
||||||
const data = await client.request(query, variables);
|
|
||||||
return NextResponse.json({ data: data.createBuildArea, status: 200 });
|
return NextResponse.json({ data: data.createBuildArea, status: 200 });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
|
|
||||||
export const buildAreaAddSchema = z.object({
|
export const buildAreaAddSchema = z.object({
|
||||||
|
buildId: z.string(),
|
||||||
areaName: z.string(),
|
areaName: z.string(),
|
||||||
areaCode: z.string(),
|
areaCode: z.string(),
|
||||||
areaType: z.string(),
|
areaType: z.string(),
|
||||||
|
|
@ -10,7 +11,7 @@ export const buildAreaAddSchema = z.object({
|
||||||
width: z.number(),
|
width: z.number(),
|
||||||
size: z.number(),
|
size: z.number(),
|
||||||
expiryStarts: z.string().optional(),
|
expiryStarts: z.string().optional(),
|
||||||
expiryEnds: z.string().optional(),
|
expiryEnds: z.string().optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type BuildAreaAdd = z.infer<typeof buildAreaAddSchema>;
|
export type BuildAreaAdd = z.infer<typeof buildAreaAddSchema>;
|
||||||
|
|
|
||||||
|
|
@ -12,26 +12,25 @@ export async function POST(request: Request) {
|
||||||
const query = gql`
|
const query = gql`
|
||||||
query BuildAreas($input: ListArguments!) {
|
query BuildAreas($input: ListArguments!) {
|
||||||
buildAreas(input: $input) {
|
buildAreas(input: $input) {
|
||||||
data {
|
data {
|
||||||
_id
|
_id
|
||||||
uuid
|
uuid
|
||||||
createdAt
|
createdAt
|
||||||
areaName
|
areaName
|
||||||
areaCode
|
areaCode
|
||||||
areaType
|
areaType
|
||||||
areaDirection
|
areaDirection
|
||||||
areaGrossSize
|
areaGrossSize
|
||||||
areaNetSize
|
areaNetSize
|
||||||
width
|
width
|
||||||
size
|
size
|
||||||
expiryStarts
|
expiryStarts
|
||||||
expiryEnds
|
expiryEnds
|
||||||
}
|
}
|
||||||
totalCount
|
totalCount
|
||||||
}
|
}
|
||||||
}`;
|
}`;
|
||||||
const variables = { input: { limit, skip, sort, filters } };
|
const variables = { input: { limit, skip, sort, filters } };
|
||||||
console.dir({ variables })
|
|
||||||
const data = await client.request(query, variables);
|
const data = await client.request(query, variables);
|
||||||
return NextResponse.json({ data: data.buildAreas.data, totalCount: data.buildAreas.totalCount });
|
return NextResponse.json({ data: data.buildAreas.data, totalCount: data.buildAreas.totalCount });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
|
|
||||||
|
|
@ -14,24 +14,13 @@ export async function POST(request: Request) {
|
||||||
try {
|
try {
|
||||||
const client = new GraphQLClient(endpoint);
|
const client = new GraphQLClient(endpoint);
|
||||||
const query = gql`
|
const query = gql`
|
||||||
mutation UpdateBuildAddress($uuid: String!, $input: UpdateBuildAddressInput!) {
|
mutation UpdateBuildArea($uuid:String!, $input: UpdateBuildAreaInput!) {
|
||||||
updateBuildAddress(uuid: $uuid, input: $input) {
|
updateBuildArea(uuid: $uuid, input: $input) { _id }
|
||||||
_id
|
|
||||||
buildNumber
|
|
||||||
doorNumber
|
|
||||||
floorNumber
|
|
||||||
commentAddress
|
|
||||||
letterAddress
|
|
||||||
shortLetterAddress
|
|
||||||
latitude
|
|
||||||
longitude
|
|
||||||
street
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
const variables = { uuid: uuid, input: validatedBody };
|
const variables = { uuid: uuid, input: validatedBody };
|
||||||
const data = await client.request(query, variables);
|
const data = await client.request(query, variables);
|
||||||
return NextResponse.json({ data: data.updateBuildAddress, status: 200 });
|
return NextResponse.json({ data: data.updateBuildArea, status: 200 });
|
||||||
} 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 });
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,17 @@
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
|
|
||||||
export const UpdateBuildAddressSchema = z.object({
|
export const UpdateBuildAddressSchema = z.object({
|
||||||
buildNumber: z.string().optional(),
|
buildId: z.string(),
|
||||||
doorNumber: z.string().optional(),
|
areaName: z.string(),
|
||||||
floorNumber: z.string().optional(),
|
areaCode: z.string(),
|
||||||
commentAddress: z.string().optional(),
|
areaType: z.string(),
|
||||||
letterAddress: z.string().optional(),
|
areaDirection: z.string(),
|
||||||
shortLetterAddress: z.string().optional(),
|
areaGrossSize: z.number(),
|
||||||
latitude: z.number().optional(),
|
areaNetSize: z.number(),
|
||||||
longitude: z.number().optional(),
|
width: z.number(),
|
||||||
street: z.string().optional(),
|
size: z.number(),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type UpdateBuildAddress = z.infer<typeof UpdateBuildAddressSchema>;
|
export type UpdateBuildAddress = z.infer<typeof UpdateBuildAddressSchema>;
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,8 @@ export async function POST(request: Request) {
|
||||||
token
|
token
|
||||||
typeToken
|
typeToken
|
||||||
description
|
description
|
||||||
|
expiryStarts
|
||||||
|
expiryEnds
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,8 @@ export const buildTypesAddSchema = z.object({
|
||||||
token: z.string(),
|
token: z.string(),
|
||||||
typeToken: z.string(),
|
typeToken: z.string(),
|
||||||
description: z.string().optional().default(''),
|
description: z.string().optional().default(''),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
'use server';
|
'use server';
|
||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { GraphQLClient, gql } from 'graphql-request';
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
import { personUpdateSchema } from './schema';
|
import { buildTypesUpdateSchema } from './schema';
|
||||||
|
|
||||||
const endpoint = "http://localhost:3001/graphql";
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 body = await request.json();
|
const body = await request.json();
|
||||||
const validatedBody = personUpdateSchema.parse(body);
|
const validatedBody = buildTypesUpdateSchema.parse(body);
|
||||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||||
try {
|
try {
|
||||||
const client = new GraphQLClient(endpoint);
|
const client = new GraphQLClient(endpoint);
|
||||||
|
|
@ -20,6 +20,8 @@ export async function POST(request: Request) {
|
||||||
token
|
token
|
||||||
typeToken
|
typeToken
|
||||||
description
|
description
|
||||||
|
expiryStarts
|
||||||
|
expiryEnds
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,12 @@
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
|
|
||||||
export const personUpdateSchema = z.object({
|
export const buildTypesUpdateSchema = z.object({
|
||||||
firstName: z.string().optional(),
|
type: z.string().optional(),
|
||||||
surname: z.string().optional(),
|
token: z.string().optional(),
|
||||||
middleName: z.string().optional(),
|
typeToken: z.string().optional(),
|
||||||
sexCode: z.string().optional(),
|
description: z.string().optional().default(''),
|
||||||
personRef: z.string().optional(),
|
expiryStarts: z.string().optional(),
|
||||||
personTag: z.string().optional(),
|
expiryEnds: z.string().optional(),
|
||||||
fatherName: z.string().optional(),
|
|
||||||
motherName: z.string().optional(),
|
|
||||||
countryCode: z.string().optional(),
|
|
||||||
nationalIdentityId: z.string().optional(),
|
|
||||||
birthPlace: z.string().optional(),
|
|
||||||
birthDate: z.string().optional(),
|
|
||||||
taxNo: z.string().optional().optional(),
|
|
||||||
birthname: z.string().optional().optional(),
|
|
||||||
expiryStarts: z.string().optional().optional(),
|
|
||||||
expiryEnds: z.string().optional().optional(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export type PeopleUpdate = z.infer<typeof personUpdateSchema>;
|
export type BuildTypesUpdate = z.infer<typeof buildTypesUpdateSchema>;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
import { buildPartsAddSchema } from './schema';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json();
|
||||||
|
const validatedBody = buildPartsAddSchema.parse({ ...body.data, buildId: body.buildId });
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
mutation CreateBuildParts($input: CreateBuildPartsInput!) {
|
||||||
|
createBuildPart(input: $input) {
|
||||||
|
buildId
|
||||||
|
addressGovCode
|
||||||
|
level
|
||||||
|
no
|
||||||
|
code
|
||||||
|
grossSize
|
||||||
|
netSize
|
||||||
|
defaultAccessory
|
||||||
|
humanLivability
|
||||||
|
key
|
||||||
|
directionId
|
||||||
|
typeId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { input: validatedBody };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.createBuildPart, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const buildPartsAddSchema = z.object({
|
||||||
|
buildId: z.string(),
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().optional(),
|
||||||
|
typeId: z.string().optional(),
|
||||||
|
active: z.boolean().default(true),
|
||||||
|
isConfirmed: z.boolean().default(false),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional()
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BuildPartsAdd = z.infer<typeof buildPartsAddSchema>;
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
|
||||||
|
const searchParams = new URL(request.url).searchParams;
|
||||||
|
const uuid = searchParams.get('uuid');
|
||||||
|
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`mutation DeleteBuildPart($uuid: String!) { deleteBuildPart(uuid: $uuid) }`;
|
||||||
|
const variables = { uuid: uuid };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.deletePerson, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,47 @@
|
||||||
|
'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 } = body;
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
query BuildParts($input: ListArguments!) {
|
||||||
|
buildParts(input: $input) {
|
||||||
|
data {
|
||||||
|
_id
|
||||||
|
uuid
|
||||||
|
addressGovCode
|
||||||
|
no
|
||||||
|
level
|
||||||
|
code
|
||||||
|
grossSize
|
||||||
|
netSize
|
||||||
|
defaultAccessory
|
||||||
|
humanLivability
|
||||||
|
key
|
||||||
|
directionId
|
||||||
|
typeId
|
||||||
|
createdAt
|
||||||
|
updatedAt
|
||||||
|
expiryStarts
|
||||||
|
expiryEnds
|
||||||
|
active
|
||||||
|
isConfirmed
|
||||||
|
}
|
||||||
|
totalCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { input: { limit, skip, sort, filters } };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.buildParts.data, totalCount: data.buildParts.totalCount });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
import { UpdateBuildPartsSchema } from './schema';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const searchUrl = new URL(request.url);
|
||||||
|
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||||
|
const body = await request.json();
|
||||||
|
const validatedBody = UpdateBuildPartsSchema.parse(body);
|
||||||
|
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
mutation UpdateBuildPart($uuid:String!, $input: UpdateBuildPartsInput!) {
|
||||||
|
updateBuildPart(uuid: $uuid, input: $input) {
|
||||||
|
_id
|
||||||
|
buildId
|
||||||
|
addressGovCode
|
||||||
|
code
|
||||||
|
directionId
|
||||||
|
expiryEnds
|
||||||
|
expiryStarts
|
||||||
|
grossSize
|
||||||
|
humanLivability
|
||||||
|
isConfirmed
|
||||||
|
key
|
||||||
|
level
|
||||||
|
netSize
|
||||||
|
no
|
||||||
|
active
|
||||||
|
typeId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { uuid: uuid, input: { ...validatedBody } };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.updateBuildPart, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const UpdateBuildPartsSchema = z.object({
|
||||||
|
|
||||||
|
buildId: z.string().optional(),
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().optional(),
|
||||||
|
typeId: z.string().optional(),
|
||||||
|
active: z.boolean(),
|
||||||
|
isConfirmed: z.boolean(),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional()
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UpdateBuildParts = z.infer<typeof UpdateBuildPartsSchema>;
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
import { buildTypesAddSchema } from './schema';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = await request.json();
|
||||||
|
const validatedBody = buildTypesAddSchema.parse(body);
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
mutation CreateBuild($input: CreateBuildInput!) {
|
||||||
|
createBuild(input: $input) {
|
||||||
|
_id
|
||||||
|
buildType {
|
||||||
|
token
|
||||||
|
typeToken
|
||||||
|
type
|
||||||
|
}
|
||||||
|
collectionToken
|
||||||
|
info {
|
||||||
|
govAddressCode
|
||||||
|
buildName
|
||||||
|
buildNo
|
||||||
|
maxFloor
|
||||||
|
undergroundFloor
|
||||||
|
buildDate
|
||||||
|
decisionPeriodDate
|
||||||
|
taxNo
|
||||||
|
liftCount
|
||||||
|
heatingSystem
|
||||||
|
coolingSystem
|
||||||
|
hotWaterSystem
|
||||||
|
blockServiceManCount
|
||||||
|
securityServiceManCount
|
||||||
|
garageCount
|
||||||
|
managementRoomId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { input: validatedBody };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.createBuild, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const buildTypesAddSchema = z.object({
|
||||||
|
buildType: z.string(),
|
||||||
|
collectionToken: z.string(),
|
||||||
|
info: z.object({
|
||||||
|
govAddressCode: z.string(),
|
||||||
|
buildName: z.string(),
|
||||||
|
buildNo: z.string(),
|
||||||
|
maxFloor: z.number(),
|
||||||
|
undergroundFloor: z.number(),
|
||||||
|
buildDate: z.string(),
|
||||||
|
decisionPeriodDate: z.string(),
|
||||||
|
taxNo: z.string(),
|
||||||
|
liftCount: z.number(),
|
||||||
|
heatingSystem: z.boolean(),
|
||||||
|
coolingSystem: z.boolean(),
|
||||||
|
hotWaterSystem: z.boolean(),
|
||||||
|
blockServiceManCount: z.number(),
|
||||||
|
securityServiceManCount: z.number(),
|
||||||
|
garageCount: z.number(),
|
||||||
|
managementRoomId: z.string(),
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
|
||||||
|
const searchParams = new URL(request.url).searchParams;
|
||||||
|
const uuid = searchParams.get('uuid');
|
||||||
|
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`mutation DeleteBuild($uuid: String!) { deleteBuild(uuid: $uuid) }`;
|
||||||
|
const variables = { uuid: uuid };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.deletePerson, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
'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 } = body;
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
query ListBuild($input: ListArguments!) {
|
||||||
|
builds(input: $input) {
|
||||||
|
data {
|
||||||
|
_id
|
||||||
|
collectionToken
|
||||||
|
buildType {
|
||||||
|
token
|
||||||
|
typeToken
|
||||||
|
type
|
||||||
|
}
|
||||||
|
info {
|
||||||
|
govAddressCode
|
||||||
|
buildName
|
||||||
|
buildNo
|
||||||
|
maxFloor
|
||||||
|
undergroundFloor
|
||||||
|
buildDate
|
||||||
|
decisionPeriodDate
|
||||||
|
taxNo
|
||||||
|
liftCount
|
||||||
|
heatingSystem
|
||||||
|
coolingSystem
|
||||||
|
hotWaterSystem
|
||||||
|
blockServiceManCount
|
||||||
|
securityServiceManCount
|
||||||
|
garageCount
|
||||||
|
managementRoomId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
totalCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { input: { limit, skip, sort, filters } };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.builds.data, totalCount: data.builds.totalCount });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
'use server';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { GraphQLClient, gql } from 'graphql-request';
|
||||||
|
import { personUpdateSchema } from './schema';
|
||||||
|
|
||||||
|
const endpoint = "http://localhost:3001/graphql";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const searchUrl = new URL(request.url);
|
||||||
|
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||||
|
const body = await request.json();
|
||||||
|
const validatedBody = personUpdateSchema.parse(body);
|
||||||
|
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||||
|
try {
|
||||||
|
const client = new GraphQLClient(endpoint);
|
||||||
|
const query = gql`
|
||||||
|
mutation UpdateBuildType($uuid: String!, $input: UpdateBuildTypesInput!) {
|
||||||
|
updateBuildType(uuid: $uuid, input: $input) {
|
||||||
|
type
|
||||||
|
token
|
||||||
|
typeToken
|
||||||
|
description
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
const variables = { uuid: uuid, input: validatedBody };
|
||||||
|
const data = await client.request(query, variables);
|
||||||
|
return NextResponse.json({ data: data.updateBuildType, status: 200 });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error(err);
|
||||||
|
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const personUpdateSchema = z.object({
|
||||||
|
firstName: z.string().optional(),
|
||||||
|
surname: z.string().optional(),
|
||||||
|
middleName: z.string().optional(),
|
||||||
|
sexCode: z.string().optional(),
|
||||||
|
personRef: z.string().optional(),
|
||||||
|
personTag: z.string().optional(),
|
||||||
|
fatherName: z.string().optional(),
|
||||||
|
motherName: z.string().optional(),
|
||||||
|
countryCode: z.string().optional(),
|
||||||
|
nationalIdentityId: z.string().optional(),
|
||||||
|
birthPlace: z.string().optional(),
|
||||||
|
birthDate: z.string().optional(),
|
||||||
|
taxNo: z.string().optional().optional(),
|
||||||
|
birthname: z.string().optional().optional(),
|
||||||
|
expiryStarts: z.string().optional().optional(),
|
||||||
|
expiryEnds: z.string().optional().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PeopleUpdate = z.infer<typeof personUpdateSchema>;
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { PageUpdateBuildSites } from "@/pages/build-areas/update/page";
|
import { PageUpdateBuildAreas } from "@/pages/build-areas/update/page";
|
||||||
|
|
||||||
const BuildAreasUpdate = () => { return <><div><PageUpdateBuildSites /></div></> }
|
const BuildAreasUpdate = () => { return <><div><PageUpdateBuildAreas /></div></> }
|
||||||
|
|
||||||
export default BuildAreasUpdate;
|
export default BuildAreasUpdate;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { PageAddBuildIbans } from "@/pages/build-ibans/add/page";
|
import { PageAddBuildParts } from "@/pages/build-parts/add/page";
|
||||||
|
|
||||||
const BuildPartsAdd = () => { return <><PageAddBuildIbans /></> }
|
const BuildPartsAddToBuild = () => { return <><PageAddBuildParts /></> }
|
||||||
|
|
||||||
export default BuildPartsAdd;
|
export default BuildPartsAddToBuild;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { PageBuildIbans } from "@/pages/build-ibans/page";
|
import PageBuildPartsToBuild from "@/pages/build-parts/page";
|
||||||
|
|
||||||
const BuildParts = () => { return <><PageBuildIbans /></> }
|
const BuildParts = () => { return <><PageBuildPartsToBuild /></> }
|
||||||
|
|
||||||
export default BuildParts;
|
export default BuildParts;
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
import { PageUpdateBuildIbans } from "@/pages/build-ibans/update/page";
|
import { PageUpdateBuildParts } from "@/pages/build-parts/update/page";
|
||||||
|
|
||||||
const BuildPartsUpdate = () => {
|
const BuildPartsUpdate = () => { return <><PageUpdateBuildParts /></> }
|
||||||
return <><PageUpdateBuildIbans /></>
|
|
||||||
}
|
|
||||||
|
|
||||||
export default BuildPartsUpdate;
|
export default BuildPartsUpdate;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { PageAddBuildTypes } from "@/pages/build-types/add/page";
|
import { PageAddBuilds } from "@/pages/builds/add/page";
|
||||||
|
|
||||||
const AddBuildPage = () => { return <><PageAddBuildTypes /></> }
|
const AddBuildPage = () => { return <><PageAddBuilds /></> }
|
||||||
|
|
||||||
export default AddBuildPage;
|
export default AddBuildPage;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { PageUpdateBuildTypes } from '@/pages/build-types/update/page';
|
import { PageUpdateBuild } from "@/pages/builds/update/page";
|
||||||
|
|
||||||
const UpdateBuildPage = async () => { return <PageUpdateBuildTypes /> }
|
const UpdateBuildPage = async () => { return <PageUpdateBuild /> }
|
||||||
|
|
||||||
export default UpdateBuildPage;
|
export default UpdateBuildPage;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
'use client';
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
interface Person {
|
||||||
|
id: number;
|
||||||
|
firstName: string;
|
||||||
|
middleName: string;
|
||||||
|
surname: string;
|
||||||
|
avatar: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PersonSelections = () => {
|
||||||
|
|
||||||
|
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const people: Person[] = [
|
||||||
|
{ id: 1, firstName: 'John', middleName: 'Michael', surname: 'Doe', avatar: 'https://placehold.co/100x100/4F46E5/FFFFFF?text=JD' },
|
||||||
|
{ id: 2, firstName: 'Jane', middleName: 'Elizabeth', surname: 'Smith', avatar: 'https://placehold.co/100x100/EC4899/FFFFFF?text=JS' },
|
||||||
|
{ id: 3, firstName: 'Robert', middleName: 'James', surname: 'Johnson', avatar: 'https://placehold.co/100x100/10B981/FFFFFF?text=RJ' },
|
||||||
|
{ id: 4, firstName: 'Emily', middleName: 'Rose', surname: 'Williams', avatar: 'https://placehold.co/100x100/F59E0B/FFFFFF?text=EW' },
|
||||||
|
{ id: 5, firstName: 'Michael', middleName: 'Thomas', surname: 'Brown', avatar: 'https://placehold.co/100x100/EF4444/FFFFFF?text=MB' },
|
||||||
|
{ id: 6, firstName: 'Sarah', middleName: 'Ann', surname: 'Davis', avatar: 'https://placehold.co/100x100/8B5CF6/FFFFFF?text=SD' },
|
||||||
|
{ id: 7, firstName: 'David', middleName: 'Charles', surname: 'Miller', avatar: 'https://placehold.co/100x100/06B6D4/FFFFFF?text=DM' },
|
||||||
|
{ id: 8, firstName: 'Lisa', middleName: 'Marie', surname: 'Wilson', avatar: 'https://placehold.co/100x100/84CC16/FFFFFF?text=LW' },
|
||||||
|
{ id: 9, firstName: 'James', middleName: 'Patrick', surname: 'Moore', avatar: 'https://placehold.co/100x100/F97316/FFFFFF?text=JM' },
|
||||||
|
{ id: 10, firstName: 'Jennifer', middleName: 'Lynn', surname: 'Taylor', avatar: 'https://placehold.co/100x100/6366F1/FFFFFF?text=JT' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const handleSelect = (id: number) => { console.log('Selected row ID:', id); setSelectedId(id) };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed top-30 w-1/2 h-1/3 bg-white border border-gray-300 shadow-lg overflow-hidden ml-5">
|
||||||
|
<div className="h-full overflow-y-auto">
|
||||||
|
{people.map((person) => (
|
||||||
|
<div key={person.id} className={`flex items-center p-4 border-b border-gray-200 hover:bg-gray-50 transition-colors ${selectedId === person.id ? 'bg-blue-50' : ''}`}>
|
||||||
|
<div className="w-1/3 flex items-center justify-center">
|
||||||
|
<img src={person.avatar} alt={`${person.firstName} ${person.surname}`} className="w-16 h-16 rounded-full object-cover border-2 border-gray-300" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 flex flex-col justify-center space-y-1 ml-4">
|
||||||
|
<div className="font-semibold text-gray-800">{person.firstName}</div>
|
||||||
|
<div className="text-sm text-gray-600">{person.middleName}</div>
|
||||||
|
<div className="text-sm text-gray-600">{person.surname}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-24 flex justify-end">
|
||||||
|
<button onClick={() => handleSelect(person.id)} className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors text-sm font-medium">Select</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PersonSelections;
|
||||||
|
|
@ -9,21 +9,12 @@ import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||||
import { BuildAreasAdd, buildAreasAddSchema } from "./schema"
|
import { BuildAreasAdd, buildAreasAddSchema } from "./schema"
|
||||||
import { useAddBuildAreasMutation } from "./queries"
|
import { useAddBuildAreasMutation } from "./queries"
|
||||||
|
|
||||||
const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
const BuildAreasForm = ({ refetchTable, buildId }: { refetchTable: () => void, buildId: string }) => {
|
||||||
|
|
||||||
const form = useForm<BuildAreasAdd>({
|
const form = useForm<BuildAreasAdd>({
|
||||||
resolver: zodResolver(buildAreasAddSchema),
|
resolver: zodResolver(buildAreasAddSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
areaName: "",
|
areaName: "", areaCode: "", areaType: "", areaDirection: "", areaGrossSize: 0, areaNetSize: 0, width: 0, size: 0, expiryStarts: "", expiryEnds: "",
|
||||||
areaCode: "",
|
|
||||||
areaType: "",
|
|
||||||
areaDirection: "",
|
|
||||||
areaGrossSize: 0,
|
|
||||||
areaNetSize: 0,
|
|
||||||
width: 0,
|
|
||||||
size: 0,
|
|
||||||
expiryStarts: "",
|
|
||||||
expiryEnds: "",
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -31,17 +22,13 @@ const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||||
|
|
||||||
const mutation = useAddBuildAreasMutation();
|
const mutation = useAddBuildAreasMutation();
|
||||||
|
|
||||||
function onSubmit(values: BuildAreasAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
|
function onSubmit(values: BuildAreasAdd) { mutation.mutate({ data: values, buildId }); 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}
|
||||||
name="areaName"
|
name="areaName"
|
||||||
|
|
@ -110,7 +97,7 @@ const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Area Gross Size</FormLabel>
|
<FormLabel>Area Gross Size</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="Area Gross Size" {...field} />
|
<Input type="number" placeholder="Area Gross Size" {...field} onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|
@ -124,7 +111,7 @@ const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Area Net Size</FormLabel>
|
<FormLabel>Area Net Size</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="Area Net Size" {...field} />
|
<Input type="number" placeholder="Area Net Size" {...field} onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|
@ -140,7 +127,7 @@ const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Width</FormLabel>
|
<FormLabel>Width</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="Width" {...field} />
|
<Input type="number" placeholder="Width" {...field} onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|
@ -154,7 +141,7 @@ const BuildAreasForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Size</FormLabel>
|
<FormLabel>Size</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="Size" {...field} />
|
<Input type="number" placeholder="Size" {...field} onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ import { useState } from 'react';
|
||||||
import { BuildAreasDataTableAdd } from './table/data-table';
|
import { BuildAreasDataTableAdd } from './table/data-table';
|
||||||
import { useGraphQlBuildAreasList } from '@/pages/build-areas/queries';
|
import { useGraphQlBuildAreasList } from '@/pages/build-areas/queries';
|
||||||
import { BuildAreasForm } from './form';
|
import { BuildAreasForm } from './form';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useSearchParams, useRouter } from 'next/navigation';
|
||||||
|
|
||||||
const PageAddBuildAreas = () => {
|
const PageAddBuildAreas = () => {
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
|
@ -10,14 +12,19 @@ const PageAddBuildAreas = () => {
|
||||||
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 } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters });
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
|
const buildId = searchParams?.get('build');
|
||||||
|
const { data, isLoading, error, refetch } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId: buildId } });
|
||||||
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<BuildAreasDataTableAdd
|
<BuildAreasDataTableAdd
|
||||||
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} buildId={buildId}
|
||||||
/>
|
/>
|
||||||
<BuildAreasForm refetchTable={refetch} />
|
<BuildAreasForm refetchTable={refetch} buildId={buildId} />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,13 +3,12 @@ import { useMutation } from '@tanstack/react-query'
|
||||||
import { toISOIfNotZ } from '@/lib/utils';
|
import { toISOIfNotZ } from '@/lib/utils';
|
||||||
import { BuildAreasAdd } from './schema';
|
import { BuildAreasAdd } from './schema';
|
||||||
|
|
||||||
const fetchGraphQlBuildSitesAdd = async (record: BuildAreasAdd): Promise<{ data: BuildAreasAdd | null; status: number }> => {
|
const fetchGraphQlBuildSitesAdd = async (record: BuildAreasAdd, buildId: string): Promise<{ data: BuildAreasAdd | 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;
|
||||||
console.dir({ record })
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/build-areas/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
const res = await fetch('/api/build-areas/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, 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}`) }
|
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 }
|
||||||
|
|
@ -18,7 +17,7 @@ const fetchGraphQlBuildSitesAdd = async (record: BuildAreasAdd): Promise<{ data:
|
||||||
|
|
||||||
export function useAddBuildAreasMutation() {
|
export function useAddBuildAreasMutation() {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ data }: { data: BuildAreasAdd }) => fetchGraphQlBuildSitesAdd(data),
|
mutationFn: ({ data, buildId }: { data: BuildAreasAdd, buildId: string }) => fetchGraphQlBuildSitesAdd(data, buildId),
|
||||||
onSuccess: () => { console.log("Build areas created successfully") },
|
onSuccess: () => { console.log("Build areas created successfully") },
|
||||||
onError: (error) => { console.error("Add build areas failed:", error) },
|
onError: (error) => { console.error("Add build areas failed:", error) },
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -105,9 +105,6 @@ 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(`/build-sites/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>
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,7 @@ export function BuildAreasDataTableAdd({
|
||||||
onPageChange,
|
onPageChange,
|
||||||
onPageSizeChange,
|
onPageSizeChange,
|
||||||
refetchTable,
|
refetchTable,
|
||||||
|
buildId
|
||||||
}: {
|
}: {
|
||||||
data: schemaType[],
|
data: schemaType[],
|
||||||
totalCount: number,
|
totalCount: number,
|
||||||
|
|
@ -62,7 +63,8 @@ export function BuildAreasDataTableAdd({
|
||||||
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,7 +144,7 @@ export function BuildAreasDataTableAdd({
|
||||||
})}
|
})}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-areas") }}>
|
<Button variant="outline" size="sm" onClick={() => { router.push(`/build-areas?build=${buildId}`) }}>
|
||||||
<Home />
|
<Home />
|
||||||
<span className="hidden lg:inline">Back to Build Areas</span>
|
<span className="hidden lg:inline">Back to Build Areas</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
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",
|
||||||
|
|
@ -88,7 +88,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(`/build-areas/update?uuid=${row.original.uuid}`) }}>
|
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/build-areas/update?uuid=${row.original.uuid}&build=${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(row.original.uuid || "") }}>
|
||||||
|
|
|
||||||
|
|
@ -78,7 +78,8 @@ export function BuildAreasDataTable({
|
||||||
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 BuildAreasDataTable({
|
||||||
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();
|
||||||
|
|
@ -100,7 +102,7 @@ export function BuildAreasDataTable({
|
||||||
|
|
||||||
const deleteMutation = useDeleteBuildAreaMutation()
|
const deleteMutation = useDeleteBuildAreaMutation()
|
||||||
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)
|
||||||
|
|
||||||
|
|
@ -163,7 +165,7 @@ export function BuildAreasDataTable({
|
||||||
})}
|
})}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-areas/add") }}>
|
<Button variant="outline" size="sm" onClick={() => { router.push(`/build-areas/add?build=${buildId}`) }}>
|
||||||
<IconPlus />
|
<IconPlus />
|
||||||
<span className="hidden lg:inline">Add Build Areas</span>
|
<span className="hidden lg:inline">Add Build Areas</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
'use client';
|
'use client';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
import { BuildAreasDataTable } from './list/data-table';
|
import { BuildAreasDataTable } from './list/data-table';
|
||||||
import { useGraphQlBuildAreasList } from './queries';
|
import { useGraphQlBuildAreasList } from './queries';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { useSearchParams, useRouter } from 'next/navigation';
|
||||||
|
|
||||||
const PageBuildAreas = () => {
|
const PageBuildAreas = () => {
|
||||||
|
|
||||||
|
|
@ -9,16 +11,17 @@ const PageBuildAreas = () => {
|
||||||
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 searchParams = useSearchParams();
|
||||||
const { data, isLoading, error, refetch } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters });
|
const router = useRouter();
|
||||||
|
const buildId = searchParams?.get('build');
|
||||||
|
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 }
|
||||||
|
const { data, isLoading, error, refetch } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId: 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) };
|
||||||
|
|
||||||
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 <BuildAreasDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} />;
|
||||||
return <BuildAreasDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||||
import { useUpdateBuildSitesMutation } from "@/pages/build-sites/update/queries"
|
import { useUpdateBuildSitesMutation } from "@/pages/build-sites/update/queries"
|
||||||
import { BuildAreasUpdate, buildAreasUpdateSchema } from "@/pages/build-areas/update/schema"
|
import { BuildAreasUpdate, buildAreasUpdateSchema } from "@/pages/build-areas/update/schema"
|
||||||
|
|
||||||
const BuildAreasForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: BuildAreasUpdate, selectedUuid: string }) => {
|
const BuildAreasForm = ({ refetchTable, initData, selectedUuid, buildId }: { refetchTable: () => void, initData: BuildAreasUpdate, selectedUuid: string, buildId: string }) => {
|
||||||
|
|
||||||
const form = useForm<BuildAreasUpdate>({ resolver: zodResolver(buildAreasUpdateSchema), defaultValues: { ...initData } })
|
const form = useForm<BuildAreasUpdate>({ resolver: zodResolver(buildAreasUpdateSchema), defaultValues: { ...initData } })
|
||||||
|
|
||||||
|
|
@ -17,7 +17,7 @@ const BuildAreasForm = ({ refetchTable, initData, selectedUuid }: { refetchTable
|
||||||
|
|
||||||
const mutation = useUpdateBuildSitesMutation();
|
const mutation = useUpdateBuildSitesMutation();
|
||||||
|
|
||||||
function onSubmit(values: BuildAreasUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 400) }
|
function onSubmit(values: BuildAreasUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, buildId }); setTimeout(() => refetchTable(), 400) }
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button';
|
||||||
import { BuildAreasDataTableUpdate } from './table/data-table';
|
import { BuildAreasDataTableUpdate } from './table/data-table';
|
||||||
import { useGraphQlBuildAreasList } from '../queries';
|
import { useGraphQlBuildAreasList } from '../queries';
|
||||||
|
|
||||||
const PageUpdateBuildSites = () => {
|
const PageUpdateBuildAreas = () => {
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [limit, setLimit] = useState(10);
|
const [limit, setLimit] = useState(10);
|
||||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||||
|
|
@ -14,23 +14,21 @@ const PageUpdateBuildSites = () => {
|
||||||
const searchParams = useSearchParams()
|
const searchParams = useSearchParams()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const uuid = searchParams?.get('uuid') || null
|
const uuid = searchParams?.get('uuid') || null
|
||||||
const backToBuildAddress = <>
|
const backToBuildAddress = <><div>UUID not found in search params</div><Button onClick={() => router.push('/build-areas')}>Back to Build Areas</Button></>
|
||||||
<div>UUID not found in search params</div>
|
const buildId = searchParams?.get('build');
|
||||||
<Button onClick={() => router.push('/build-areas')}>Back to Build Areas</Button>
|
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 }; if (!uuid) { return backToBuildAddress }
|
||||||
if (!uuid) { return backToBuildAddress }
|
const { data, isLoading, error, refetch } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId, uuid } });
|
||||||
const { data, isLoading, error, refetch } = useGraphQlBuildAreasList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
|
||||||
const initData = data?.data?.[0] || null;
|
const initData = data?.data?.[0] || null;
|
||||||
if (!initData) { return backToBuildAddress }
|
if (!initData) { return backToBuildAddress }
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<BuildAreasDataTableUpdate
|
<BuildAreasDataTableUpdate
|
||||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} buildID={buildId}
|
||||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
|
||||||
/>
|
/>
|
||||||
<BuildAreasForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
|
<BuildAreasForm refetchTable={refetch} initData={initData} selectedUuid={uuid} buildId={buildId} />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export { PageUpdateBuildSites };
|
export { PageUpdateBuildAreas };
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,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",
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,7 @@ export function BuildAreasDataTableUpdate({
|
||||||
onPageChange,
|
onPageChange,
|
||||||
onPageSizeChange,
|
onPageSizeChange,
|
||||||
refetchTable,
|
refetchTable,
|
||||||
|
buildID
|
||||||
}: {
|
}: {
|
||||||
data: schemaType[],
|
data: schemaType[],
|
||||||
totalCount: number,
|
totalCount: number,
|
||||||
|
|
@ -87,7 +88,8 @@ export function BuildAreasDataTableUpdate({
|
||||||
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();
|
||||||
|
|
@ -101,7 +103,7 @@ export function BuildAreasDataTableUpdate({
|
||||||
|
|
||||||
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 }); setTimeout(() => { refetchTable() }, 200) }
|
||||||
const columns = getColumns(router, deleteHandler);
|
const columns = getColumns(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 +169,7 @@ export function BuildAreasDataTableUpdate({
|
||||||
})}
|
})}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-areas") }}>
|
<Button variant="outline" size="sm" onClick={() => { router.push(`/build-areas?build=${buildID}`) }}>
|
||||||
<Home />
|
<Home />
|
||||||
<span className="hidden lg:inline">Back to Build Areas</span>
|
<span className="hidden lg:inline">Back to Build Areas</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@ export function BuildIbansDataTableUpdate({
|
||||||
</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 Areas</span>
|
<span className="hidden lg:inline">Back to Build IBANs</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
|
|
||||||
interface UpdateBuildIbansUpdate {
|
interface UpdateBuildIbansUpdate {
|
||||||
|
|
||||||
iban: string;
|
iban: string;
|
||||||
startDate: string;
|
startDate: string;
|
||||||
stopDate: string;
|
stopDate: string;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,306 @@
|
||||||
|
"use client"
|
||||||
|
import { useForm } from "react-hook-form"
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod"
|
||||||
|
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||||
|
import { BuildPartsAdd, buildPartsAddSchema } from "./schema"
|
||||||
|
import { useAddBuildAreasMutation } from "./queries"
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
|
|
||||||
|
const BuildPartsForm = ({ refetchTable, selectedBuildId }: { refetchTable: () => void, selectedBuildId: string }) => {
|
||||||
|
|
||||||
|
const form = useForm<BuildPartsAdd>({
|
||||||
|
resolver: zodResolver(buildPartsAddSchema),
|
||||||
|
defaultValues: {
|
||||||
|
addressGovCode: "", no: 0, level: 0, code: "", grossSize: 0, netSize: 0, defaultAccessory: "", humanLivability: false, key: "",
|
||||||
|
directionId: "", typeId: "", active: false, isConfirmed: false, expiryStarts: "", expiryEnds: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { handleSubmit } = form;
|
||||||
|
|
||||||
|
const mutation = useAddBuildAreasMutation();
|
||||||
|
|
||||||
|
function onSubmit(values: BuildPartsAdd) { mutation.mutate({ data: values, buildId: selectedBuildId }); setTimeout(() => refetchTable(), 400) };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form {...form}>
|
||||||
|
<form
|
||||||
|
onSubmit={handleSubmit(onSubmit)}
|
||||||
|
className="space-y-6 p-4"
|
||||||
|
>
|
||||||
|
{/* ROW 1 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="addressGovCode"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Address Gov Code</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="TR-34-XXX-XXXX" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="no"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>No</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Area No"
|
||||||
|
{...field}
|
||||||
|
onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 2 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="level"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Level</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Floor / Level"
|
||||||
|
{...field}
|
||||||
|
onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="code"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Code</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Part Code (e.g. A5)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 3 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="key"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Key</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Unique Key (e.g. BLK-A5-L5-N3)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="grossSize"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Gross Size</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Gross Size (m²)"
|
||||||
|
{...field}
|
||||||
|
onBlur={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 4 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="netSize"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Net Size</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Net Size (m²)"
|
||||||
|
{...field}
|
||||||
|
onBlur={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="defaultAccessory"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Default Accessory</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="e.g. balcony, terrace..." {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 5 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="directionId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Direction Id</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Direction ObjectId (optional)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="typeId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Type Id</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Type ObjectId (optional)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* BOOLEAN ROW */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
|
||||||
|
{/* boşluk kalmasın diye aktif alanını buraya koydum */}
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="active"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Active
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="humanLivability"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Human Livability
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="isConfirmed"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Is Confirmed
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
{/* EXPIRY DATES */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<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>
|
||||||
|
<Button type="submit" className="w-full">Add Build Address</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { BuildPartsForm }
|
||||||
|
|
@ -0,0 +1,41 @@
|
||||||
|
'use client';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { BuildPartsDataTableAdd } from './table/data-table';
|
||||||
|
import { BuildPartsForm } from './form';
|
||||||
|
import { useGraphQlBuildPartsList } from '@/pages/build-parts/queries';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
|
const PageAddBuildParts = () => {
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [limit, setLimit] = useState(10);
|
||||||
|
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||||
|
const [filters, setFilters] = useState({});
|
||||||
|
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
|
const buildId = searchParams?.get('build');
|
||||||
|
|
||||||
|
const { data, isLoading, error, refetch } = useGraphQlBuildPartsList({ limit: 10, skip: 0, sort: { createdAt: -1 }, filters: { ...filters, buildId } });
|
||||||
|
|
||||||
|
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||||
|
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<>
|
||||||
|
<BuildPartsDataTableAdd
|
||||||
|
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId}
|
||||||
|
/>
|
||||||
|
<BuildPartsForm refetchTable={refetch} selectedBuildId={buildId} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PageAddBuildParts };
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
'use client'
|
||||||
|
import { useMutation } from '@tanstack/react-query'
|
||||||
|
import { toISOIfNotZ } from '@/lib/utils';
|
||||||
|
import { BuildPartsAdd } from './schema';
|
||||||
|
|
||||||
|
const fetchGraphQlBuildSitesAdd = async (record: BuildPartsAdd, buildId: string): Promise<{ data: BuildPartsAdd | 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/builds-parts/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ data: record, 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, status: res.status }
|
||||||
|
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useAddBuildAreasMutation() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ data, buildId }: { data: BuildPartsAdd, buildId: string }) => fetchGraphQlBuildSitesAdd(data, buildId),
|
||||||
|
onSuccess: () => { console.log("Build areas created successfully") },
|
||||||
|
onError: (error) => { console.error("Add build areas failed:", error) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const buildPartsAddSchema = z.object({
|
||||||
|
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().optional(),
|
||||||
|
typeId: z.string().optional(),
|
||||||
|
active: z.boolean(),
|
||||||
|
isConfirmed: z.boolean(),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional()
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BuildPartsAdd = z.infer<typeof buildPartsAddSchema>;
|
||||||
|
|
@ -0,0 +1,115 @@
|
||||||
|
"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 } 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"
|
||||||
|
|
||||||
|
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||||
|
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||||
|
return (
|
||||||
|
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||||
|
className="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: "addressGovCode",
|
||||||
|
header: "Address Gov Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "no",
|
||||||
|
header: "No",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "level",
|
||||||
|
header: "Level",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "code",
|
||||||
|
header: "Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "grossSize",
|
||||||
|
header: "Gross Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "netSize",
|
||||||
|
header: "Net Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "defaultAccessory",
|
||||||
|
header: "Default Accessory",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "humanLivability",
|
||||||
|
header: "Human Livability",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "key",
|
||||||
|
header: "Key",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "directionId",
|
||||||
|
header: "Direction ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "typeId",
|
||||||
|
header: "Type ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original._id || "") }}>
|
||||||
|
<Trash />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getColumns };
|
||||||
|
|
@ -0,0 +1,256 @@
|
||||||
|
"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,
|
||||||
|
} 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 } from "@/components/ui/tabs"
|
||||||
|
import { schemaType } from "./schema"
|
||||||
|
import { getColumns, DraggableRow } from "./columns"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
import { Home } from "lucide-react"
|
||||||
|
import { useDeleteBuildPartMutation } from "@/pages/build-parts/queries"
|
||||||
|
|
||||||
|
export function BuildPartsDataTableAdd({
|
||||||
|
data,
|
||||||
|
totalCount,
|
||||||
|
currentPage,
|
||||||
|
pageSize,
|
||||||
|
onPageChange,
|
||||||
|
onPageSizeChange,
|
||||||
|
refetchTable,
|
||||||
|
buildId
|
||||||
|
}: {
|
||||||
|
data: schemaType[],
|
||||||
|
totalCount: number,
|
||||||
|
currentPage: number,
|
||||||
|
pageSize: number,
|
||||||
|
onPageChange: (page: number) => void,
|
||||||
|
onPageSizeChange: (size: number) => void,
|
||||||
|
refetchTable: () => void,
|
||||||
|
buildId: string
|
||||||
|
}) {
|
||||||
|
|
||||||
|
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 = useDeleteBuildPartMutation()
|
||||||
|
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,
|
||||||
|
enableRowSelection: true,
|
||||||
|
getRowId: (row) => row._id.toString(),
|
||||||
|
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(`/build-parts?build=${buildId}`) }}>
|
||||||
|
<Home />
|
||||||
|
<span className="hidden lg:inline">Back to Build Parts</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">
|
||||||
|
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||||
|
{table.getRowModel().rows.map((row) => <DraggableRow 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,28 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const schema = z.object({
|
||||||
|
|
||||||
|
_id: z.string(),
|
||||||
|
uuid: z.string(),
|
||||||
|
buildId: z.string(),
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().nullable().optional(),
|
||||||
|
typeId: z.string().nullable().optional(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
expiryStarts: z.string(),
|
||||||
|
expiryEnds: z.string(),
|
||||||
|
active: z.boolean(),
|
||||||
|
isConfirmed: z.boolean(),
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type schemaType = z.infer<typeof schema>;
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
|
||||||
|
interface PeopleAdd {
|
||||||
|
|
||||||
|
firstName: string;
|
||||||
|
surname: string;
|
||||||
|
middleName?: string;
|
||||||
|
sexCode: string;
|
||||||
|
personRef?: string;
|
||||||
|
personTag?: string;
|
||||||
|
fatherName?: string;
|
||||||
|
motherName?: string;
|
||||||
|
countryCode: string;
|
||||||
|
nationalIdentityId: string;
|
||||||
|
birthPlace: string;
|
||||||
|
birthDate: string;
|
||||||
|
taxNo?: string;
|
||||||
|
birthname?: string;
|
||||||
|
expiryStarts?: string;
|
||||||
|
expiryEnds?: string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type { PeopleAdd };
|
||||||
|
|
@ -0,0 +1,111 @@
|
||||||
|
"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 }: { row: Row<z.infer<typeof schema>> }) {
|
||||||
|
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||||
|
return (
|
||||||
|
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||||
|
className="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, buildId: string): ColumnDef<schemaType>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: "addressGovCode",
|
||||||
|
header: "Address Gov Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "no",
|
||||||
|
header: "No",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "level",
|
||||||
|
header: "Level",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "code",
|
||||||
|
header: "Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "grossSize",
|
||||||
|
header: "Gross Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "netSize",
|
||||||
|
header: "Net Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "defaultAccessory",
|
||||||
|
header: "Default Accessory",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "humanLivability",
|
||||||
|
header: "Human Livability",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "key",
|
||||||
|
header: "Key",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "directionId",
|
||||||
|
header: "Direction ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "typeId",
|
||||||
|
header: "Type ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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(`/build-parts/update?build=${buildId}&uuid=${row.original._id}`) }}>
|
||||||
|
<Pencil />
|
||||||
|
</Button>
|
||||||
|
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original._id || "") }}>
|
||||||
|
<Trash />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getColumns };
|
||||||
|
|
@ -0,0 +1,277 @@
|
||||||
|
"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 { useDeleteBuildPartMutation } from "@/pages/build-parts/queries"
|
||||||
|
import { Home } from "lucide-react"
|
||||||
|
|
||||||
|
export function BuildPartsDataTable({
|
||||||
|
data,
|
||||||
|
totalCount,
|
||||||
|
currentPage = 1,
|
||||||
|
pageSize = 10,
|
||||||
|
onPageChange,
|
||||||
|
onPageSizeChange,
|
||||||
|
refetchTable,
|
||||||
|
buildId
|
||||||
|
}: {
|
||||||
|
data: schemaType[],
|
||||||
|
totalCount: number,
|
||||||
|
currentPage?: number,
|
||||||
|
pageSize?: number,
|
||||||
|
onPageChange: (page: number) => void,
|
||||||
|
onPageSizeChange: (size: number) => void,
|
||||||
|
refetchTable: () => void,
|
||||||
|
buildId: string,
|
||||||
|
}) {
|
||||||
|
|
||||||
|
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 = useDeleteBuildPartMutation()
|
||||||
|
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
|
||||||
|
const columns = getColumns(router, deleteHandler, buildId);
|
||||||
|
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(`/build-parts/add?build=${buildId}`) }}>
|
||||||
|
<IconPlus />
|
||||||
|
<span className="hidden lg:inline">Add Build Part</span>
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => { router.push(`/builds`) }}>
|
||||||
|
<Home />
|
||||||
|
<span className="hidden lg:inline">Back to Builds</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">
|
||||||
|
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||||
|
{table.getRowModel().rows.map((row) => <DraggableRow 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,28 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const schema = z.object({
|
||||||
|
|
||||||
|
_id: z.string(),
|
||||||
|
uuid: z.string(),
|
||||||
|
buildId: z.string(),
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().nullable().optional(),
|
||||||
|
typeId: z.string().nullable().optional(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
expiryStarts: z.string(),
|
||||||
|
expiryEnds: z.string(),
|
||||||
|
active: z.boolean(),
|
||||||
|
isConfirmed: z.boolean(),
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type schemaType = z.infer<typeof schema>;
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
'use client';
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useSearchParams, useRouter } from "next/navigation";
|
||||||
|
import { useGraphQlBuildPartsList } from "./queries";
|
||||||
|
import { BuildPartsDataTable } from "./list/data-table";
|
||||||
|
|
||||||
|
const PageBuildPartsToBuild = () => {
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [limit, setLimit] = useState(10);
|
||||||
|
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||||
|
const [filters, setFilters] = useState({});
|
||||||
|
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
|
const buildId = searchParams?.get('build');
|
||||||
|
|
||||||
|
const { data, isLoading, error, refetch } = useGraphQlBuildPartsList({ limit: 10, skip: 0, sort: { createdAt: -1 }, filters: { ...filters, buildId } });
|
||||||
|
|
||||||
|
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||||
|
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||||
|
|
||||||
|
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 <><BuildPartsDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} buildId={buildId} /></>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PageBuildPartsToBuild;
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
'use client'
|
||||||
|
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||||
|
import { ListArguments } from '@/types/listRequest'
|
||||||
|
|
||||||
|
const fetchGraphQlBuildPartsList = async (params: ListArguments): Promise<any> => {
|
||||||
|
console.log('Fetching test data from local API');
|
||||||
|
const { limit, skip, sort, filters } = params;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/builds-parts/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 fetchGraphQlDeleteBuildPart = async (uuid: string): Promise<boolean> => {
|
||||||
|
console.log('Fetching test data from local API');
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/builds-parts/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 useGraphQlBuildPartsList(params: ListArguments) {
|
||||||
|
return useQuery({ queryKey: ['graphql-build-parts-list', params], queryFn: () => fetchGraphQlBuildPartsList(params) })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteBuildPartMutation() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteBuildPart(uuid),
|
||||||
|
onSuccess: () => { console.log("Build part deleted successfully") },
|
||||||
|
onError: (error) => { console.error("Delete build part failed:", error) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,299 @@
|
||||||
|
"use client"
|
||||||
|
import { useForm } from "react-hook-form"
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod"
|
||||||
|
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||||
|
import { Input } from "@/components/ui/input"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||||
|
import { BuildPartsUpdate, buildPartsUpdateSchema } from "@/pages/build-parts/update/schema"
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
|
import { useUpdateBuildPartsMutation } from "@/pages/build-parts/update/queries"
|
||||||
|
|
||||||
|
const BuildPartsForm = ({ refetchTable, initData, selectedUuid, buildId }: { refetchTable: () => void, initData: BuildPartsUpdate, selectedUuid: string, buildId: string }) => {
|
||||||
|
|
||||||
|
const form = useForm<BuildPartsUpdate>({
|
||||||
|
resolver: zodResolver(buildPartsUpdateSchema), defaultValues: { ...initData, directionId: initData.directionId ?? '', typeId: initData.typeId ?? '' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const { handleSubmit } = form
|
||||||
|
|
||||||
|
const mutation = useUpdateBuildPartsMutation();
|
||||||
|
|
||||||
|
function onSubmit(values: BuildPartsUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, buildId, refetchTable }) }
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
|
||||||
|
{/* ROW 1 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="addressGovCode"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Address Gov Code</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="TR-34-XXX-XXXX" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="no"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>No</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Area No"
|
||||||
|
{...field}
|
||||||
|
onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 2 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="level"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Level</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Floor / Level"
|
||||||
|
{...field}
|
||||||
|
onChange={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="code"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Code</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Part Code (e.g. A5)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 3 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="key"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Key</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Unique Key (e.g. BLK-A5-L5-N3)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="grossSize"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Gross Size</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Gross Size (m²)"
|
||||||
|
{...field}
|
||||||
|
onBlur={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 4 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="netSize"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Net Size</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Net Size (m²)"
|
||||||
|
{...field}
|
||||||
|
onBlur={(e) => field.onChange(e.target.value === "" ? undefined : Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="defaultAccessory"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Default Accessory</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="e.g. balcony, terrace..." {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* ROW 5 */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="directionId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Direction Id</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Direction ObjectId (optional)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="typeId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Type Id</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Type ObjectId (optional)" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* BOOLEAN ROW */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
|
||||||
|
{/* boşluk kalmasın diye aktif alanını buraya koydum */}
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="active"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Active
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="humanLivability"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Human Livability
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="isConfirmed"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-md border p-3">
|
||||||
|
<FormLabel className="text-sm font-medium">
|
||||||
|
Is Confirmed
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
{/* EXPIRY DATES */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<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>
|
||||||
|
<Button type="submit" className="w-full">Update Build Address</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export { BuildPartsForm }
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
'use client';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { BuildPartsForm } from '@/pages/build-parts/update/form';
|
||||||
|
import { useSearchParams, useRouter } from 'next/navigation'
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { BuildPartsDataTableUpdate } from './table/data-table';
|
||||||
|
import { useGraphQlBuildPartsList } from '../queries';
|
||||||
|
|
||||||
|
const PageUpdateBuildParts = () => {
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [limit, setLimit] = useState(10);
|
||||||
|
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||||
|
const [filters, setFilters] = useState({});
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const router = useRouter()
|
||||||
|
const uuid = searchParams?.get('uuid') || null
|
||||||
|
const buildId = searchParams?.get('build') || null
|
||||||
|
const backToBuildAddress = <>
|
||||||
|
<div>UUID not found in search params</div>
|
||||||
|
<Button onClick={() => router.push('/build-parts')}>Back to Build IBANs</Button>
|
||||||
|
</>
|
||||||
|
if (!uuid || !buildId) { return backToBuildAddress }
|
||||||
|
const { data, isLoading, error, refetch } = useGraphQlBuildPartsList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, _id: uuid } });
|
||||||
|
const initData = data?.data?.[0] || null;
|
||||||
|
if (!initData) { return backToBuildAddress }
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<BuildPartsDataTableUpdate
|
||||||
|
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} buildId={buildId}
|
||||||
|
/>
|
||||||
|
<BuildPartsForm refetchTable={refetch} initData={initData} selectedUuid={uuid} buildId={buildId} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PageUpdateBuildParts };
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
'use client'
|
||||||
|
import { useMutation } from '@tanstack/react-query'
|
||||||
|
import { UpdateBuildPartsUpdate } from './types';
|
||||||
|
import { toISOIfNotZ } from '@/lib/utils';
|
||||||
|
|
||||||
|
const fetchGraphQlBuildPartsUpdate = async (record: UpdateBuildPartsUpdate, uuid: string, buildId: string, refetchTable: () => void): Promise<{ data: UpdateBuildPartsUpdate | 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/builds-parts/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, 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();
|
||||||
|
refetchTable();
|
||||||
|
return { data: data.data, status: res.status }
|
||||||
|
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useUpdateBuildPartsMutation() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ data, uuid, buildId, refetchTable }: { data: UpdateBuildPartsUpdate, uuid: string, buildId: string, refetchTable: () => void }) => fetchGraphQlBuildPartsUpdate(data, uuid, buildId, refetchTable),
|
||||||
|
onSuccess: () => { console.log("Build Parts updated successfully") },
|
||||||
|
onError: (error) => { console.error("Update Build Parts failed:", error) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const buildPartsUpdateSchema = z.object({
|
||||||
|
|
||||||
|
addressGovCode: z.string(),
|
||||||
|
no: z.number(),
|
||||||
|
level: z.number(),
|
||||||
|
code: z.string(),
|
||||||
|
grossSize: z.number(),
|
||||||
|
netSize: z.number(),
|
||||||
|
defaultAccessory: z.string(),
|
||||||
|
humanLivability: z.boolean(),
|
||||||
|
key: z.string(),
|
||||||
|
directionId: z.string().optional(),
|
||||||
|
typeId: z.string().optional(),
|
||||||
|
active: z.boolean(),
|
||||||
|
isConfirmed: z.boolean(),
|
||||||
|
expiryStarts: z.string().optional(),
|
||||||
|
expiryEnds: z.string().optional()
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BuildPartsUpdate = z.infer<typeof buildPartsUpdateSchema>;
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
"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 } 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"
|
||||||
|
|
||||||
|
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||||
|
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||||
|
return (
|
||||||
|
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||||
|
className="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(deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: "addressGovCode",
|
||||||
|
header: "Address Gov Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "no",
|
||||||
|
header: "No",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "level",
|
||||||
|
header: "Level",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "code",
|
||||||
|
header: "Code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "grossSize",
|
||||||
|
header: "Gross Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "netSize",
|
||||||
|
header: "Net Size",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "defaultAccessory",
|
||||||
|
header: "Default Accessory",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "humanLivability",
|
||||||
|
header: "Human Livability",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "key",
|
||||||
|
header: "Key",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "directionId",
|
||||||
|
header: "Direction ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "typeId",
|
||||||
|
header: "Type ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original._id || "") }}>
|
||||||
|
<Trash />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getColumns };
|
||||||
|
|
@ -0,0 +1,281 @@
|
||||||
|
"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,
|
||||||
|
} 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 { Home } from "lucide-react"
|
||||||
|
import { useDeletePersonMutation } from "@/pages/people/queries"
|
||||||
|
|
||||||
|
export function BuildPartsDataTableUpdate({
|
||||||
|
data,
|
||||||
|
totalCount,
|
||||||
|
currentPage,
|
||||||
|
pageSize,
|
||||||
|
onPageChange,
|
||||||
|
onPageSizeChange,
|
||||||
|
refetchTable,
|
||||||
|
buildId,
|
||||||
|
}: {
|
||||||
|
data: schemaType[],
|
||||||
|
totalCount: number,
|
||||||
|
currentPage: number,
|
||||||
|
pageSize: number,
|
||||||
|
onPageChange: (page: number) => void,
|
||||||
|
onPageSizeChange: (size: number) => void,
|
||||||
|
refetchTable: () => void,
|
||||||
|
buildId: string
|
||||||
|
}) {
|
||||||
|
|
||||||
|
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 = useDeletePersonMutation()
|
||||||
|
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||||
|
const columns = getColumns(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,
|
||||||
|
enableRowSelection: true,
|
||||||
|
getRowId: (row) => row._id.toString(),
|
||||||
|
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(`/build-parts?build=${buildId}`) }}>
|
||||||
|
<Home />
|
||||||
|
<span className="hidden lg:inline">Back to Build Parts</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">
|
||||||
|
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||||
|
{table.getRowModel().rows.map((row) => <DraggableRow 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue