updated living space
This commit is contained in:
parent
3aebb79d36
commit
eaca36573e
|
|
@ -15,6 +15,7 @@ import { BuildAddressModule } from './build-address/build-address.module';
|
|||
import { BuildIbanModule } from './build-iban/build-iban.module';
|
||||
import { BuildSitesModule } from './build-sites/build-sites.module';
|
||||
import { CompanyModule } from './company/company.module';
|
||||
import { LivingSpaceModule } from './living-space/living-space.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
|
@ -35,6 +36,7 @@ import { CompanyModule } from './company/company.module';
|
|||
BuildIbanModule,
|
||||
BuildSitesModule,
|
||||
CompanyModule,
|
||||
LivingSpaceModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
|
|
|||
|
|
@ -3,22 +3,24 @@ 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';
|
||||
import { UpdateCompanyInput } from './dto/update-company.input';
|
||||
import type { GraphQLResolveInfo } from 'graphql';
|
||||
import graphqlFields from 'graphql-fields';
|
||||
|
||||
@Resolver()
|
||||
export class CompanyResolver {
|
||||
|
||||
constructor(private readonly companyService: CompanyService) { }
|
||||
|
||||
@Query(() => ListCompanyResponse, { name: 'companies' })
|
||||
@Query(() => ListCompanyResponse, { name: 'getCompanies' })
|
||||
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);
|
||||
const fields = graphqlFields(info); const projection = this.companyService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
||||
return await this.companyService.findAll(projection, skip, limit, sort, filters);
|
||||
}
|
||||
|
||||
@Query(() => Company, { name: 'company', nullable: true })
|
||||
@Query(() => Company, { name: 'getCompany', 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);
|
||||
}
|
||||
|
|
@ -26,4 +28,10 @@ export class CompanyResolver {
|
|||
@Mutation(() => Company, { name: 'createCompany' })
|
||||
async createCompany(@Args('input') input: CreateCompanyInput): Promise<Company> { return this.companyService.create(input) }
|
||||
|
||||
@Mutation(() => Company, { name: 'updateCompany' })
|
||||
async updateCompany(@Args('uuid') uuid: string, @Args('input') input: UpdateCompanyInput): Promise<Company> { return this.companyService.update(uuid, input) }
|
||||
|
||||
@Mutation(() => Boolean, { name: 'deleteCompany' })
|
||||
async deleteCompany(@Args('uuid') uuid: string): Promise<boolean> { return this.companyService.delete(uuid) }
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,49 @@
|
|||
|
||||
import { ExpiryBaseInput } from '@/models/base.model';
|
||||
import { InputType, Field, ID } from '@nestjs/graphql';
|
||||
|
||||
|
||||
@InputType()
|
||||
export class CreateCompanyInput {
|
||||
export class CreateCompanyInput extends ExpiryBaseInput {
|
||||
|
||||
@Field()
|
||||
name: string;
|
||||
formal_name: string;
|
||||
|
||||
@Field()
|
||||
company_type: string;
|
||||
|
||||
@Field()
|
||||
commercial_type: string;
|
||||
|
||||
@Field()
|
||||
tax_no: string;
|
||||
|
||||
@Field()
|
||||
public_name: string;
|
||||
|
||||
@Field()
|
||||
company_tag: string;
|
||||
|
||||
@Field({ defaultValue: 'TR' })
|
||||
default_lang_type: string;
|
||||
|
||||
@Field({ defaultValue: 'TL' })
|
||||
default_money_type: string;
|
||||
|
||||
@Field({ defaultValue: false })
|
||||
is_commercial?: boolean;
|
||||
|
||||
@Field({ defaultValue: false })
|
||||
is_blacklist?: boolean;
|
||||
|
||||
@Field()
|
||||
parent_id?: string;
|
||||
|
||||
@Field()
|
||||
workplace_no?: string;
|
||||
|
||||
@Field()
|
||||
official_address?: string;
|
||||
|
||||
@Field()
|
||||
top_responsible_company?: string;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,48 @@
|
|||
import { InputType, Field, ID } from '@nestjs/graphql';
|
||||
import { InputType, Field } from '@nestjs/graphql';
|
||||
|
||||
@InputType()
|
||||
export class UpdateCompanyInput {
|
||||
|
||||
@Field({ nullable: true })
|
||||
name?: string;
|
||||
formal_name?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
company_type?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
commercial_type?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
tax_no?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
public_name?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
company_tag?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
default_lang_type?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
default_money_type?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
is_commercial?: boolean;
|
||||
|
||||
@Field({ nullable: true })
|
||||
is_blacklist?: boolean;
|
||||
|
||||
@Field({ nullable: true })
|
||||
parent_id?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
workplace_no?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
official_address?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
top_responsible_company?: string;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,4 +22,3 @@ export async function cleanRefArrayField({ parentModel, refModel, parentId, fiel
|
|||
await parentModel.updateOne({ _id: parentId }, { $set: { [fieldName]: keptIds } });
|
||||
return { keptIds, removedIds };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
import { ExpiryBaseInput } from '@/models/base.model';
|
||||
import { InputType, Field } from '@nestjs/graphql';
|
||||
|
||||
@InputType()
|
||||
export class CreateLivingSpaceInput extends ExpiryBaseInput {
|
||||
|
||||
@Field()
|
||||
buildID: string;
|
||||
|
||||
@Field()
|
||||
collectionToken: string;
|
||||
|
||||
@Field()
|
||||
partID: string;
|
||||
|
||||
@Field()
|
||||
userTypeID: string;
|
||||
|
||||
@Field()
|
||||
companyID: string;
|
||||
|
||||
@Field()
|
||||
personID: string;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { Field, ObjectType } from "@nestjs/graphql";
|
||||
import { Int } from "@nestjs/graphql";
|
||||
import { LivingSpaces } from "@/models/living-spaces.model";
|
||||
|
||||
@ObjectType()
|
||||
export class ListLivingSpaceResponse {
|
||||
|
||||
@Field(() => [LivingSpaces], { nullable: true })
|
||||
data?: LivingSpaces[];
|
||||
|
||||
@Field(() => Int, { nullable: true })
|
||||
totalCount?: number;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { ExpiryBaseInput } from '@/models/base.model';
|
||||
import { InputType, Field } from '@nestjs/graphql';
|
||||
|
||||
@InputType()
|
||||
export class UpdateLivingSpaceInput extends ExpiryBaseInput {
|
||||
|
||||
@Field({ nullable: true })
|
||||
buildID?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
collectionToken?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
partID?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
userTypeID?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
companyID?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
personID?: string;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { LivingSpaceService } from './living-space.service';
|
||||
import { LivingSpaceResolver } from './living-space.resolver';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { LivingSpaces, LivingSpacesSchema } from '@/models/living-spaces.model';
|
||||
|
||||
@Module({
|
||||
imports: [MongooseModule.forFeature([{ name: LivingSpaces.name, schema: LivingSpacesSchema }])],
|
||||
providers: [LivingSpaceService, LivingSpaceResolver]
|
||||
})
|
||||
export class LivingSpaceModule { }
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { LivingSpaceResolver } from './living-space.resolver';
|
||||
|
||||
describe('LivingSpaceResolver', () => {
|
||||
let resolver: LivingSpaceResolver;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [LivingSpaceResolver],
|
||||
}).compile();
|
||||
|
||||
resolver = module.get<LivingSpaceResolver>(LivingSpaceResolver);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(resolver).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { Resolver, Args, ID, Info, Mutation, Query } from '@nestjs/graphql';
|
||||
import { Types } from 'mongoose';
|
||||
import { ListArguments } from '@/dto/list.input';
|
||||
import { LivingSpaces } from '@/models/living-spaces.model';
|
||||
import { ListLivingSpaceResponse } from './dto/list-living-space.response';
|
||||
import { CreateLivingSpaceInput } from './dto/create-living-space.input';
|
||||
import { UpdateLivingSpaceInput } from './dto/update-living-space.input';
|
||||
import { LivingSpaceService } from './living-space.service';
|
||||
import type { GraphQLResolveInfo } from 'graphql';
|
||||
import graphqlFields from 'graphql-fields';
|
||||
|
||||
@Resolver()
|
||||
export class LivingSpaceResolver {
|
||||
|
||||
constructor(private readonly livingSpaceService: LivingSpaceService) { }
|
||||
|
||||
@Query(() => ListLivingSpaceResponse, { name: 'getLivingSpaces' })
|
||||
async getLivingSpaces(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListLivingSpaceResponse> {
|
||||
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
||||
return await this.livingSpaceService.findAll(projection, skip, limit, sort, filters);
|
||||
}
|
||||
|
||||
@Query(() => LivingSpaces, { name: 'getLivingSpace', nullable: true })
|
||||
async getLivingSpace(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<LivingSpaces | null> {
|
||||
const fields = graphqlFields(info); const projection = this.livingSpaceService.buildProjection(fields); return this.livingSpaceService.findById(new Types.ObjectId(id), projection);
|
||||
}
|
||||
|
||||
@Mutation(() => LivingSpaces, { name: 'createLivingSpace' })
|
||||
async createLivingSpace(@Args('input') input: CreateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.create(input) }
|
||||
|
||||
@Mutation(() => LivingSpaces, { name: 'updateLivingSpace' })
|
||||
async updateLivingSpace(@Args('uuid') uuid: string, @Args('input') input: UpdateLivingSpaceInput): Promise<LivingSpaces> { return this.livingSpaceService.update(uuid, input) }
|
||||
|
||||
@Mutation(() => Boolean, { name: 'deleteLivingSpace' })
|
||||
async deleteLivingSpace(@Args('uuid') uuid: string, @Args('collectionToken') collectionToken: string): Promise<boolean> { return this.livingSpaceService.delete(uuid, collectionToken) }
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { LivingSpaceService } from './living-space.service';
|
||||
|
||||
describe('LivingSpaceService', () => {
|
||||
let service: LivingSpaceService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [LivingSpaceService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<LivingSpaceService>(LivingSpaceService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Types, Model, Connection } from 'mongoose';
|
||||
import { getDynamicLivingSpaceModel, LivingSpaces, LivingSpacesDocument } from '@/models/living-spaces.model';
|
||||
import { ListLivingSpaceResponse } from './dto/list-living-space.response';
|
||||
import { CreateLivingSpaceInput } from './dto/create-living-space.input';
|
||||
import { UpdateLivingSpaceInput } from './dto/update-living-space.input';
|
||||
import { InjectConnection } from '@nestjs/mongoose';
|
||||
|
||||
interface UpdateInput {
|
||||
build?: Types.ObjectId;
|
||||
collectionToken?: string;
|
||||
userType?: Types.ObjectId;
|
||||
part?: Types.ObjectId;
|
||||
company?: Types.ObjectId;
|
||||
person?: Types.ObjectId;
|
||||
expiryStarts?: Date;
|
||||
expiryEnds?: Date;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class LivingSpaceService {
|
||||
|
||||
constructor(
|
||||
@InjectModel(LivingSpaces.name) private readonly livingSpaceModel: Model<LivingSpacesDocument>,
|
||||
@InjectConnection() private readonly connection: Connection
|
||||
) { }
|
||||
|
||||
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListLivingSpaceResponse> {
|
||||
if (!filters?.collectionToken) { throw new Error('Collection token is required') }
|
||||
const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
|
||||
const totalCount = await this.livingSpaceModel.countDocuments(query).exec();
|
||||
const data = await this.livingSpaceModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
||||
return { data, totalCount };
|
||||
}
|
||||
|
||||
async findById(id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> {
|
||||
if (!projection?.collectionToken) { throw new Error('Collection token is required') }
|
||||
const selectedModel = getDynamicLivingSpaceModel(projection.collectionToken, this.connection);
|
||||
return selectedModel.findById(id, projection, { lean: false }).populate({ path: 'company', select: projection?.company }).exec();
|
||||
}
|
||||
|
||||
async create(input: CreateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
||||
if (!input.collectionToken) { throw new Error('Collection token is required') }
|
||||
const LivingSpaceModel = getDynamicLivingSpaceModel(input.collectionToken, this.connection);
|
||||
const docInput: Partial<LivingSpacesDocument> = {
|
||||
build: new Types.ObjectId(input.buildID), part: new Types.ObjectId(input.partID), userType: new Types.ObjectId(input.userTypeID),
|
||||
company: new Types.ObjectId(input.companyID), person: new Types.ObjectId(input.personID),
|
||||
expiryStarts: input.expiryStarts ? new Date(input.expiryStarts) : new Date(), expiryEnds: input.expiryEnds ? new Date(input.expiryEnds) : new Date('2099-12-31'),
|
||||
}; const doc = new LivingSpaceModel(docInput); return await doc.save()
|
||||
}
|
||||
|
||||
async update(uuid: string, input: UpdateLivingSpaceInput): Promise<LivingSpacesDocument> {
|
||||
if (!input.collectionToken) { throw new Error('Collection token is required') }
|
||||
const selectedModel = getDynamicLivingSpaceModel(input.collectionToken, this.connection);
|
||||
const newInput: UpdateInput = {}
|
||||
if (input?.buildID) { newInput.build = new Types.ObjectId(input.buildID) }; if (input?.userTypeID) { newInput.userType = new Types.ObjectId(input.userTypeID) }
|
||||
if (input?.partID) { newInput.part = new Types.ObjectId(input.partID) }; if (input?.companyID) { newInput.company = new Types.ObjectId(input.companyID) }
|
||||
if (input?.personID) { newInput.person = new Types.ObjectId(input.personID) };
|
||||
if (input?.expiryStarts) { newInput.expiryStarts = input.expiryStarts }; if (input?.expiryEnds) { newInput.expiryEnds = input.expiryEnds }
|
||||
const company = await selectedModel.findOne({ uuid }); if (!company) { throw new Error('Company not found') }; company.set(newInput); return company.save();
|
||||
}
|
||||
|
||||
async delete(uuid: string, collectionToken: string): Promise<boolean> { if (!collectionToken) { throw new Error('Collection token is required') } const selectedModel = getDynamicLivingSpaceModel(collectionToken, this.connection); const company = await selectedModel.deleteMany({ uuid }); return company.deletedCount > 0 }
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -90,8 +90,6 @@ export class CreatedBase {
|
|||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ObjectType({ isAbstract: true })
|
||||
export class ExpiryBase {
|
||||
|
||||
|
|
|
|||
|
|
@ -10,9 +10,61 @@ export class Company extends Base {
|
|||
@Field(() => ID)
|
||||
readonly _id: string;
|
||||
|
||||
@Field(() => ID)
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
name: string;
|
||||
formal_name: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
company_type: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
commercial_type: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
tax_no: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
public_name: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
company_tag: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true, default: 'TR' })
|
||||
default_lang_type: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true, default: 'TL' })
|
||||
default_money_type: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true, default: false })
|
||||
is_commercial: boolean;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true, default: false })
|
||||
is_blacklist: boolean;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: false })
|
||||
parent_id: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: false })
|
||||
workplace_no: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: false })
|
||||
official_address: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: false })
|
||||
top_responsible_company: string;
|
||||
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { Document, Model, Types, Connection, connection as defaultConnection } from 'mongoose';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { Prop, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { Document, Model, Types, Connection } from 'mongoose';
|
||||
import { Prop, SchemaFactory, Schema } from '@nestjs/mongoose';
|
||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
import { Base } from '@/models/base.model';
|
||||
import { Build } from '@/models/build.model';
|
||||
|
|
@ -9,9 +8,14 @@ import { Person } from '@/models/person.model';
|
|||
import { Company } from '@/models/company.model';
|
||||
import { UserType } from '@/models/user-type.model';
|
||||
|
||||
|
||||
@ObjectType()
|
||||
@Schema({ timestamps: true })
|
||||
export class LivingSpaces extends Base {
|
||||
|
||||
@Field(() => ID)
|
||||
readonly _id: string
|
||||
|
||||
@Field(() => ID)
|
||||
@Prop({ type: Types.ObjectId, ref: Build.name, required: true })
|
||||
build: Types.ObjectId;
|
||||
|
|
@ -37,9 +41,9 @@ export class LivingSpaces extends Base {
|
|||
export type LivingSpacesDocument = LivingSpaces & Document;
|
||||
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);
|
||||
|
||||
export function getDynamicLivingSpaceModel(collectionToken: string, conn?: Connection): Model<LivingSpacesDocument> {
|
||||
const connection = conn || defaultConnection;
|
||||
export function getDynamicLivingSpaceModel(collectionToken: string, connection: Connection): Model<LivingSpacesDocument> {
|
||||
const collectionName = `LivingSpaces${collectionToken}`;
|
||||
const schema = SchemaFactory.createForClass(LivingSpaces);
|
||||
if (connection.models[collectionName]) { return connection.models[collectionName] as Model<LivingSpacesDocument> }
|
||||
throw new Error('No Living Spaces is found')
|
||||
return connection.model(collectionName, schema, collectionName) as unknown as Model<LivingSpacesDocument>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { CreateCompanyInputSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validatedBody = CreateCompanyInputSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation createCompany($input: CreateCompanyInput!) { createCompany(input: $input) {_id}}`;
|
||||
const variables = { input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.createCompany, 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 CreateCompanyInputSchema = z.object({
|
||||
formal_name: z.string(),
|
||||
company_type: z.string(),
|
||||
commercial_type: z.string(),
|
||||
tax_no: z.string(),
|
||||
public_name: z.string(),
|
||||
company_tag: z.string(),
|
||||
|
||||
default_lang_type: z.string().default("TR"),
|
||||
default_money_type: z.string().default("TL"),
|
||||
|
||||
is_commercial: z.boolean().default(false),
|
||||
is_blacklist: z.boolean().default(false),
|
||||
|
||||
parent_id: z.string().optional(),
|
||||
workplace_no: z.string().optional(),
|
||||
official_address: z.string().optional(),
|
||||
top_responsible_company: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
|
||||
});
|
||||
|
||||
export type CreateCompanyInput = z.infer<typeof CreateCompanyInputSchema>;
|
||||
|
|
@ -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');
|
||||
console.dir({ uuid }, { depth: null });
|
||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation DeleteCompany($uuid: String!) { deleteCompany(uuid: $uuid) }`;
|
||||
const data = await client.request(query, { uuid });
|
||||
return NextResponse.json({ data: data.deleteUserType, 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 GetCompanies($input: ListArguments!) {
|
||||
getCompanies(input:$input) {
|
||||
data {
|
||||
_id
|
||||
uuid
|
||||
company_type
|
||||
commercial_type
|
||||
tax_no
|
||||
default_lang_type
|
||||
default_money_type
|
||||
is_commercial
|
||||
is_blacklist
|
||||
workplace_no
|
||||
official_address
|
||||
top_responsible_company
|
||||
parent_id
|
||||
company_tag
|
||||
formal_name
|
||||
public_name
|
||||
parent_id
|
||||
expiryStarts
|
||||
expiryEnds
|
||||
}
|
||||
totalCount
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: { limit, skip, sort, filters } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.getCompanies.data, totalCount: data.getCompanies.totalCount });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { UpdateCompanyInputSchema } 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") || "";
|
||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||
const body = await request.json();
|
||||
const validatedBody = UpdateCompanyInputSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation UpdateCompany($uuid: String!, $input: UpdateCompanyInput!) { updateCompany(uuid:$uuid, input: $input) {_id} }`;
|
||||
const variables = { uuid: uuid, input: { ...validatedBody } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.updateCompany, 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 UpdateCompanyInputSchema = z.object({
|
||||
formal_name: z.string(),
|
||||
company_type: z.string(),
|
||||
commercial_type: z.string(),
|
||||
tax_no: z.string(),
|
||||
public_name: z.string(),
|
||||
company_tag: z.string(),
|
||||
default_lang_type: z.string().default("TR"),
|
||||
default_money_type: z.string().default("TL"),
|
||||
is_commercial: z.boolean().default(false),
|
||||
is_blacklist: z.boolean().default(false),
|
||||
parent_id: z.string().optional(),
|
||||
workplace_no: z.string().optional(),
|
||||
official_address: z.string().optional(),
|
||||
top_responsible_company: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
|
||||
});
|
||||
|
||||
export type UpdateCompanyInput = z.infer<typeof UpdateCompanyInputSchema>;
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { CreateLivingSpaceInputSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validatedBody = CreateLivingSpaceInputSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation CreateLivingSpace($input: CreateLivingSpaceInput!) { createLivingSpace(input:$input) { _id }}`;
|
||||
const variables = { input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.createLivingSpace, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const CreateLivingSpaceInputSchema = z.object({
|
||||
buildID: z.string(),
|
||||
collectionToken: z.string(),
|
||||
partID: z.string(),
|
||||
userTypeID: z.string(),
|
||||
companyID: z.string(),
|
||||
personID: z.string(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type CreateLivingSpaceInput = z.infer<typeof CreateLivingSpaceInputSchema>;
|
||||
|
|
@ -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');
|
||||
console.dir({ uuid }, { depth: null });
|
||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation DeleteCompany($uuid: String!) { deleteCompany(uuid: $uuid) }`;
|
||||
const data = await client.request(query, { uuid });
|
||||
return NextResponse.json({ data: data.deleteUserType, 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 GetCompanies($input: ListArguments!) {
|
||||
getCompanies(input:$input) {
|
||||
data {
|
||||
_id
|
||||
uuid
|
||||
company_type
|
||||
commercial_type
|
||||
tax_no
|
||||
default_lang_type
|
||||
default_money_type
|
||||
is_commercial
|
||||
is_blacklist
|
||||
workplace_no
|
||||
official_address
|
||||
top_responsible_company
|
||||
parent_id
|
||||
company_tag
|
||||
formal_name
|
||||
public_name
|
||||
parent_id
|
||||
expiryStarts
|
||||
expiryEnds
|
||||
}
|
||||
totalCount
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: { limit, skip, sort, filters } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.getCompanies.data, totalCount: data.getCompanies.totalCount });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { UpdateLivingSpaceInputSchema } 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") || "";
|
||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||
const body = await request.json();
|
||||
const validatedBody = UpdateLivingSpaceInputSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation UpdateLivingSpace($uuid: String!, $input: UpdateLivingSpaceInput!) { updateLivingSpace(uuid:$uuid, input: $input) {_id} }`;
|
||||
const variables = { uuid: uuid, input: { ...validatedBody } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.updateLivingSpace, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const UpdateLivingSpaceInputSchema = z.object({
|
||||
buildID: z.string(),
|
||||
collectionToken: z.string(),
|
||||
partID: z.string(),
|
||||
userTypeID: z.string(),
|
||||
companyID: z.string(),
|
||||
personID: z.string(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type UpdateLivingSpaceInput = z.infer<typeof UpdateLivingSpaceInputSchema>;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageLivingSpaceAdd } from "@/pages/living-space/add/page";
|
||||
|
||||
const SSRPageLivingSpaceAdd = () => { return <><PageLivingSpaceAdd /></> }
|
||||
|
||||
export default SSRPageLivingSpaceAdd;
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { PageLivingSpace } from "@/pages/living-space/tables/page"
|
||||
// import { PageLivingSpace } from "@/pages/living-space/add/page"
|
||||
|
||||
const SSRPageLivingSpace = () => { return <><PageLivingSpace /></> }
|
||||
const SSRPageLivingSpace = () => { return <><div>PageLivingSpace</div></> }
|
||||
|
||||
export default SSRPageLivingSpace;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { XCircle } from "lucide-react";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker";
|
||||
import { FormValues } from "./schema";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
const FormAddNewLivingSpace = ({ form, onSubmit, deleteAllSelections }: { form: any, onSubmit: (data: FormValues) => void, deleteAllSelections: () => void }) => {
|
||||
return <>
|
||||
<Card className="m-7">
|
||||
<CardContent className="pt-6">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="buildID"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>Build ID</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="collectionToken"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>Collection Token</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="userTypeID"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>User Type ID</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="partID"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>Part ID</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="companyID"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>Company ID</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="personID"
|
||||
render={({ field }) => (
|
||||
<FormItem className="mt-3">
|
||||
<FormLabel>Person ID</FormLabel>
|
||||
<FormControl>
|
||||
<Label {...field} >{field.value ? field.value : "Not Selected"}</Label>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{/* EXPIRY DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-4">
|
||||
<Button variant="outline" type="button" className="text-destructive hover:text-destructive" onClick={deleteAllSelections}>
|
||||
<XCircle className="h-4 w-4 mr-2" />Clear All
|
||||
</Button>
|
||||
<Button type="submit">Submit</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
}
|
||||
|
||||
export { FormAddNewLivingSpace };
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
'use client';
|
||||
import { useState, useEffect } from "react";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { FormValues, createForm } from "./schema";
|
||||
import { FormAddNewLivingSpace } from "./form";
|
||||
|
||||
import PageLivingSpaceBuildsTableSection from "../tables/builds/page";
|
||||
import PageLivingSpaceUserTypesTableSection from "../tables/userType/page";
|
||||
import PageLivingSpacePartsTableSection from "../tables/part/page";
|
||||
import PageLivingSpacePersonTableSection from "../tables/person/page";
|
||||
import PageLivingSpaceCompanyTableSection from "../tables/company/page";
|
||||
import { useAddLivingSpaceMutation } from "./queries";
|
||||
|
||||
const PageLivingSpaceAdd = () => {
|
||||
const [collectionToken, setCollectionToken] = useState<string | null>(null);
|
||||
const [buildID, setBuildID] = useState<string | null>(null);
|
||||
const [userTypeID, setUserTypeID] = useState<string | null>(null);
|
||||
const [partID, setPartID] = useState<string | null>(null);
|
||||
const [companyID, setCompanyID] = useState<string | null>(null);
|
||||
const [personID, setPersonID] = useState<string | null>(null);
|
||||
|
||||
const form = createForm({ buildID, collectionToken, userTypeID, partID, companyID, personID });
|
||||
|
||||
useEffect(() => {
|
||||
form.setValue("buildID", buildID || "");
|
||||
form.setValue("collectionToken", collectionToken || "");
|
||||
form.setValue("userTypeID", userTypeID || "");
|
||||
form.setValue("partID", partID || "");
|
||||
form.setValue("companyID", companyID || "");
|
||||
form.setValue("personID", personID || "");
|
||||
}, [buildID, collectionToken, userTypeID, partID, companyID, personID, form]);
|
||||
|
||||
const mutation = useAddLivingSpaceMutation();
|
||||
function onSubmit(values: FormValues) { mutation.mutate({ data: values }) }
|
||||
console.dir({ input: form.getValues() })
|
||||
|
||||
const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(false);
|
||||
const [isPartsEnabled, setIsPartsEnabled] = useState(false);
|
||||
const [isHandleCompanyAndPersonEnable, setIsHandleCompanyAndPersonEnable] = useState(false);
|
||||
|
||||
const tabsClassName = "border border-gray-300 rounded-sm h-10"
|
||||
const deleteAllSelections = () => {
|
||||
setBuildID(null); setCollectionToken(null); setUserTypeID(null); setPartID(null); setCompanyID(null); setPersonID(null);
|
||||
setIsUserTypeEnabled(false); setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(false)
|
||||
}
|
||||
|
||||
return <>
|
||||
<div className="flex flex-col m-7">
|
||||
<Tabs defaultValue="builds" className="w-full">
|
||||
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
|
||||
<TabsTrigger className={tabsClassName} value="builds">Builds</TabsTrigger>
|
||||
{isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
|
||||
{isPartsEnabled && <TabsTrigger className={tabsClassName} value="parts">Parts</TabsTrigger>}
|
||||
{isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="company">Company</TabsTrigger>}
|
||||
{isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="person">Person</TabsTrigger>}
|
||||
</TabsList>
|
||||
<div className="mt-6">
|
||||
<TabsContent value="builds">
|
||||
<PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} collectionToken={collectionToken} setCollectionToken={setCollectionToken} setIsUserTypeEnabled={setIsUserTypeEnabled} />
|
||||
</TabsContent>
|
||||
{isUserTypeEnabled && <TabsContent value="usertype">
|
||||
<PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable} />
|
||||
</TabsContent>}
|
||||
{isPartsEnabled && buildID && <TabsContent value="parts">
|
||||
<PageLivingSpacePartsTableSection buildId={buildID} partID={partID} setPartID={setPartID} setIsPartsEnabled={setIsPartsEnabled} />
|
||||
</TabsContent>}
|
||||
{isHandleCompanyAndPersonEnable && <TabsContent value="company"><PageLivingSpaceCompanyTableSection companyID={companyID} setCompanyID={setCompanyID} /></TabsContent>}
|
||||
{isHandleCompanyAndPersonEnable && <TabsContent value="person"><PageLivingSpacePersonTableSection personID={personID} setPersonID={setPersonID} /></TabsContent>}
|
||||
</div>
|
||||
</Tabs>
|
||||
</div>
|
||||
<div><FormAddNewLivingSpace form={form} onSubmit={onSubmit} deleteAllSelections={deleteAllSelections} /></div>
|
||||
</>
|
||||
}
|
||||
|
||||
export { PageLivingSpaceAdd };
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
'use client'
|
||||
import { z } from 'zod'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { toISOIfNotZ } from '@/lib/utils'
|
||||
|
||||
export const formSchema = z.object({
|
||||
buildID: z.string({ error: "Build ID is required" }),
|
||||
collectionToken: z.string({ error: "Collection Token is required" }),
|
||||
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||
partID: z.string({ error: "Part ID is required" }),
|
||||
companyID: z.string({ error: "Company ID is required" }),
|
||||
personID: z.string({ error: "Person ID is required" }),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof formSchema>;
|
||||
|
||||
const fetchGraphQlLivingSpaceAdd = async (record: schemaType): Promise<{ data: schemaType | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
|
||||
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
||||
console.dir({ record })
|
||||
try {
|
||||
const res = await fetch('/api/living-spaces/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, status: res.status }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlLivingSpaceUpdate = async (record: schemaType, uuid: string): Promise<{ data: schemaType | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
|
||||
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
||||
try {
|
||||
const res = await fetch(`/api/living-spaces/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
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 useAddLivingSpaceMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data }: { data: schemaType }) => fetchGraphQlLivingSpaceAdd(data),
|
||||
onSuccess: () => { console.log("Living Space added successfully") },
|
||||
onError: (error) => { console.error("Add Living Space add failed:", error) },
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateLivingSpaceMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data, uuid }: { data: schemaType, uuid: string }) => fetchGraphQlLivingSpaceUpdate(data, uuid),
|
||||
onSuccess: () => { console.log("Living Space updated successfully") },
|
||||
onError: (error) => { console.error("Update Living Space update failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import * as z from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormProps } from "./types";
|
||||
|
||||
export const formSchema = z.object({
|
||||
buildID: z.string({ error: "Build ID is required" }),
|
||||
collectionToken: z.string({ error: "Collection Token is required" }),
|
||||
userTypeID: z.string({ error: "User Type ID is required" }),
|
||||
partID: z.string({ error: "Part ID is required" }),
|
||||
companyID: z.string({ error: "Company ID is required" }),
|
||||
personID: z.string({ error: "Person ID is required" }),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export function createForm({ buildID, collectionToken, userTypeID, partID, companyID, personID }: FormProps) {
|
||||
return useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
buildID: buildID || "",
|
||||
collectionToken: collectionToken || "",
|
||||
userTypeID: userTypeID || "",
|
||||
partID: partID || "",
|
||||
companyID: companyID || "",
|
||||
personID: personID || "",
|
||||
expiryStarts: "",
|
||||
expiryEnds: ""
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
interface FormProps {
|
||||
buildID: string | null;
|
||||
collectionToken: string | null;
|
||||
userTypeID: string | null;
|
||||
partID: string | null;
|
||||
companyID: string | null;
|
||||
personID: string | null;
|
||||
}
|
||||
|
||||
|
||||
export type { FormProps };
|
||||
|
|
@ -10,11 +10,11 @@ import { dateToLocaleString } from "@/lib/utils"
|
|||
import { Pencil, Trash } from "lucide-react"
|
||||
import { IconHandClick } from "@tabler/icons-react"
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
className={`${row.original._id === selectedID ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
|
|
|
|||
|
|
@ -171,10 +171,6 @@ export function LivingSpaceBuildDataTable({
|
|||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{/* <Button variant="outline" size="sm" onClick={() => { router.push(`/build-sites/add`) }}>
|
||||
<IconPlus />
|
||||
<span className="hidden lg:inline">Add Build Sites</span>
|
||||
</Button> */}
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
|
|
@ -196,7 +192,7 @@ export function LivingSpaceBuildDataTable({
|
|||
</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} />)}
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={buildId} key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,127 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical, IconHandClick } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
|
||||
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className={`${row.original._id === selectedID ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(selectionHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "formal_name",
|
||||
header: "Formal Name",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "company_type",
|
||||
header: "Company Type",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "commercial_type",
|
||||
header: "Commercial Type",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_no",
|
||||
header: "Tax No",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "public_name",
|
||||
header: "Public Name",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "company_tag",
|
||||
header: "Company Tag",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "default_lang_type",
|
||||
header: "Default Language",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "default_money_type",
|
||||
header: "Default Money Type",
|
||||
cell: ({ getValue }) => getValue(),
|
||||
},
|
||||
{
|
||||
accessorKey: "is_commercial",
|
||||
header: "Is Commercial",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "is_blacklist",
|
||||
header: "Is Blacklist",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
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-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { selectionHandler(row.original._id) }}>
|
||||
<IconHandClick />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,267 @@
|
|||
"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"
|
||||
|
||||
export function LivingSpaceCompanyDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
companyID,
|
||||
setCompanyID,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
companyID: string,
|
||||
setCompanyID: (id: string | null) => void,
|
||||
}) {
|
||||
|
||||
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 selectionHandler = (id: string) => { setCompanyID(id); }
|
||||
const columns = getColumns(selectionHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data, columns, pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">View</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={companyID} 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,25 @@
|
|||
'use client';
|
||||
import { useState } from "react";
|
||||
import { useGraphQlCompanyList } from "./queries";
|
||||
import { LivingSpaceCompanyDataTable } from "./data-table";
|
||||
|
||||
const PageLivingSpaceCompanyTableSection = ({ companyID, setCompanyID }: { companyID: string | null; setCompanyID: (id: string | null) => void }) => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const { data, isLoading, error, refetch } = useGraphQlCompanyList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
|
||||
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
|
||||
|
||||
return < LivingSpaceCompanyDataTable
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange} refetchTable={refetch} companyID={companyID || ""} setCompanyID={setCompanyID}
|
||||
/>
|
||||
|
||||
}
|
||||
|
||||
export default PageLivingSpaceCompanyTableSection;
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
'use client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
import { schemaType } from "./schema";
|
||||
|
||||
const fetchGraphQlCompanyList = async (params: ListArguments): Promise<{ data: schemaType[], totalCount: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
const { limit, skip, sort, filters } = params;
|
||||
try {
|
||||
const res = await fetch('/api/company/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 }
|
||||
};
|
||||
|
||||
export function useGraphQlCompanyList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-company-list', params], queryFn: () => fetchGraphQlCompanyList(params) })
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
formal_name: z.string(),
|
||||
company_type: z.string(),
|
||||
commercial_type: z.string(),
|
||||
tax_no: z.string(),
|
||||
public_name: z.string(),
|
||||
company_tag: z.string(),
|
||||
default_lang_type: z.string().default("TR"),
|
||||
default_money_type: z.string().default("TL"),
|
||||
is_commercial: z.boolean().default(false),
|
||||
is_blacklist: z.boolean().default(false),
|
||||
parent_id: z.string().optional(),
|
||||
workplace_no: z.string().optional(),
|
||||
official_address: z.string().optional(),
|
||||
top_responsible_company: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
'use client';
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { XCircle } from "lucide-react";
|
||||
import PageLivingSpaceBuildsTableSection from "./builds/page";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import PageLivingSpaceUserTypesTableSection from "./userType/page";
|
||||
|
||||
|
||||
const PageLivingSpace = () => {
|
||||
|
||||
const [collectionToken, setCollectionToken] = useState<string | null>(null);
|
||||
const [buildID, setBuildID] = useState<string | null>(null);
|
||||
const [userTypeID, setUserTypeID] = useState<string | null>(null);
|
||||
const [partID, setPartID] = useState<string | null>(null);
|
||||
const [companyID, setCompanyID] = useState<string | null>(null);
|
||||
const [personID, setPersonID] = useState<string | null>(null);
|
||||
|
||||
const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(false);
|
||||
const [isPartsEnabled, setIsPartsEnabled] = useState(false);
|
||||
const [isCompanyEnabled, setIsCompanyEnabled] = useState(false);
|
||||
const [isPersonEnabled, setIsPersonEnabled] = useState(false);
|
||||
|
||||
|
||||
const tabsClassName = "border border-gray-300 rounded-sm h-10"
|
||||
const deleteAllSelections = () => {
|
||||
setBuildID(null); setCollectionToken(null); setUserTypeID(null); setPartID(null); setCompanyID(null); setPersonID(null);
|
||||
setIsUserTypeEnabled(false); setIsPartsEnabled(false); setIsCompanyEnabled(false); setIsPersonEnabled(false);
|
||||
}
|
||||
return <>
|
||||
<Card className="mb-6">
|
||||
<CardContent className="pt-6 flex justify-between items-start">
|
||||
<div className="grid grid-cols-6 gap-x-12 gap-y-2">
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">Build ID:</span>
|
||||
<span>{buildID || '-'}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">Collection Token:</span>
|
||||
<span>{collectionToken || '-'}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">User Type ID:</span>
|
||||
<span>{userTypeID || '-'}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">Part ID:</span>
|
||||
<span>{partID || '-'}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">Company ID:</span>
|
||||
<span>{companyID || '-'}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-medium text-gray-500">Person ID:</span>
|
||||
<span>{personID || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-4 text-destructive hover:text-destructive" onClick={deleteAllSelections}>
|
||||
<XCircle className="h-4 w-4 mr-2" />Clear All
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="flex flex-col m-7">
|
||||
<Tabs defaultValue="builds" className="w-full">
|
||||
<TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
|
||||
<TabsTrigger className={tabsClassName} value="builds">Builds</TabsTrigger>
|
||||
{isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
|
||||
{isPartsEnabled && <TabsTrigger className={tabsClassName} value="parts">Parts</TabsTrigger>}
|
||||
{isCompanyEnabled && <TabsTrigger className={tabsClassName} value="company">Company</TabsTrigger>}
|
||||
{isPersonEnabled && <TabsTrigger className={tabsClassName} value="person">Person</TabsTrigger>}
|
||||
</TabsList>
|
||||
<div className="mt-6">
|
||||
<TabsContent value="builds">
|
||||
<PageLivingSpaceBuildsTableSection buildID={buildID} setBuildID={setBuildID} collectionToken={collectionToken} setCollectionToken={setCollectionToken} setIsUserTypeEnabled={setIsUserTypeEnabled} />
|
||||
</TabsContent>
|
||||
{isUserTypeEnabled && <TabsContent value="usertype">
|
||||
<PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsCompanyEnabled={setIsCompanyEnabled} setIsPersonEnabled={setIsPersonEnabled} />
|
||||
</TabsContent>}
|
||||
{isPartsEnabled && <TabsContent value="parts">{/* Add Parts section component here */}</TabsContent>}
|
||||
{isCompanyEnabled && <TabsContent value="company">{/* Add Company section component here */}</TabsContent>}
|
||||
{isPersonEnabled && <TabsContent value="person"> {/* Add Person section component here */}</TabsContent>}
|
||||
</div>
|
||||
</Tabs>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
|
||||
export { PageLivingSpace };
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
"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"
|
||||
import { IconHandClick } from "@tabler/icons-react"
|
||||
|
||||
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-dragging={isDragging} ref={setNodeRef}
|
||||
className={`${row.original._id === selectedID ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(selectionHandler: (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-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { selectionHandler(row.original._id) }}>
|
||||
<IconHandClick />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,267 @@
|
|||
"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"
|
||||
|
||||
export function LivingSpaceBuildPartsDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
buildId,
|
||||
partID,
|
||||
setPartID,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
buildId: string,
|
||||
partID: string | null,
|
||||
setPartID: (id: string | null) => void
|
||||
}) {
|
||||
|
||||
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 selectionHandler = (id: string) => { setPartID(id); }
|
||||
const columns = getColumns(selectionHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className='w-56'>
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id} >
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (
|
||||
<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={partID || ""} 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,35 @@
|
|||
'use client';
|
||||
import { useState } from "react";
|
||||
import { useGraphQlBuildPartsList } from "./queries";
|
||||
import { LivingSpaceBuildPartsDataTable } from "./data-table";
|
||||
|
||||
|
||||
const PageLivingSpacePartsTableSection = (
|
||||
{ buildId, partID, setPartID, setIsPartsEnabled }: {
|
||||
buildId: string;
|
||||
partID: string | null;
|
||||
setPartID: (id: string | null) => void;
|
||||
setIsPartsEnabled: (enabled: boolean) => void;
|
||||
}
|
||||
) => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildPartsList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, buildId: buildId } });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
|
||||
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
|
||||
|
||||
return <>
|
||||
<LivingSpaceBuildPartsDataTable
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange}
|
||||
refetchTable={refetch} buildId={buildId} partID={partID} setPartID={setPartID} />
|
||||
</>;
|
||||
|
||||
}
|
||||
|
||||
export default PageLivingSpacePartsTableSection;
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
'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 }
|
||||
};
|
||||
|
||||
export function useGraphQlBuildPartsList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-build-parts-list', params], queryFn: () => fetchGraphQlBuildPartsList(params) })
|
||||
}
|
||||
|
|
@ -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,146 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical, IconHandClick } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className={`${row.original._id === selectedID ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(selectionHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "firstName",
|
||||
header: "First Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "surname",
|
||||
header: "Surname",
|
||||
},
|
||||
{
|
||||
accessorKey: "middleName",
|
||||
header: "Middle Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "sexCode",
|
||||
header: "Sex",
|
||||
},
|
||||
{
|
||||
accessorKey: "personRef",
|
||||
header: "Person Ref",
|
||||
},
|
||||
{
|
||||
accessorKey: "personTag",
|
||||
header: "Person Tag",
|
||||
},
|
||||
{
|
||||
accessorKey: "fatherName",
|
||||
header: "Father Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "motherName",
|
||||
header: "Mother Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "countryCode",
|
||||
header: "Country",
|
||||
},
|
||||
{
|
||||
accessorKey: "nationalIdentityId",
|
||||
header: "National ID",
|
||||
},
|
||||
{
|
||||
accessorKey: "birthPlace",
|
||||
header: "Birth Place",
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: "Active",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "isConfirmed",
|
||||
header: "Confirmed",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "birthDate",
|
||||
header: "Birth Date",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-blue-600 border-blue-600 text-white" variant="outline" size="sm" onClick={() => { selectionHandler(row.original._id) }}>
|
||||
<IconHandClick />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,267 @@
|
|||
"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"
|
||||
|
||||
export function LivingSpacePeopleDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
personID,
|
||||
setPersonID,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
personID: string,
|
||||
setPersonID: (id: string | null) => void,
|
||||
}) {
|
||||
|
||||
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 selectionHandler = (id: string) => { setPersonID(id); }
|
||||
const columns = getColumns(selectionHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data, columns, pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">View</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={personID} 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,24 @@
|
|||
'use client';
|
||||
import { useState } from "react";
|
||||
import { useGraphQlPeopleList } from "./queries";
|
||||
import { LivingSpacePeopleDataTable } from "./data-table";
|
||||
|
||||
const PageLivingSpacePersonTableSection = ({ personID, setPersonID }: { personID: string | null, setPersonID: (id: string | null) => void }) => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const { data, isLoading, error, refetch } = useGraphQlPeopleList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
|
||||
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
|
||||
|
||||
return < LivingSpacePeopleDataTable
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange} refetchTable={refetch} personID={personID || ""} setPersonID={setPersonID}
|
||||
/>
|
||||
}
|
||||
|
||||
export default PageLivingSpacePersonTableSection;
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
'use client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
import { schemaType } from "./schema";
|
||||
|
||||
const fetchGraphQlPeopleList = async (params: ListArguments): Promise<{ data: schemaType[], totalCount: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
const { limit, skip, sort, filters } = params;
|
||||
try {
|
||||
const res = await fetch('/api/people/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ limit, skip, sort, filters }) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, totalCount: data.totalCount }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useGraphQlPeopleList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-people-list', params], queryFn: () => fetchGraphQlPeopleList(params) })
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
firstName: z.string().nullable().optional(),
|
||||
surname: z.string().nullable().optional(),
|
||||
middleName: z.string().nullable().optional(),
|
||||
sexCode: z.string().nullable().optional(),
|
||||
personRef: z.string().nullable().optional(),
|
||||
personTag: z.string().nullable().optional(),
|
||||
fatherName: z.string().nullable().optional(),
|
||||
motherName: z.string().nullable().optional(),
|
||||
countryCode: z.string().nullable().optional(),
|
||||
nationalIdentityId: z.string().nullable().optional(),
|
||||
birthPlace: z.string().nullable().optional(),
|
||||
birthDate: z.string().nullable().optional(),
|
||||
taxNo: z.string().nullable().optional(),
|
||||
birthname: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -16,11 +16,11 @@ import { schema, schemaType } from "./schema"
|
|||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash, TextSelect } from "lucide-react"
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
export function DraggableRow({ row, selectedID }: { row: Row<z.infer<typeof schema>>; selectedID: string }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
className={`${row.original._id === selectedID ? "bg-blue-700/50 hover:bg-blue-700/50" : ""} relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80`}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
|
|
|
|||
|
|
@ -86,8 +86,7 @@ export function LivingSpaceUserTypesDataTable({
|
|||
userTypeID,
|
||||
setUserTypeID,
|
||||
setIsPartsEnabled,
|
||||
setIsCompanyEnabled,
|
||||
setIsPersonEnabled,
|
||||
setIsHandleCompanyAndPersonEnable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
|
|
@ -99,12 +98,8 @@ export function LivingSpaceUserTypesDataTable({
|
|||
userTypeID: string | null;
|
||||
setUserTypeID: (id: string | null) => void;
|
||||
setIsPartsEnabled: (enabled: boolean) => void;
|
||||
setIsCompanyEnabled: (enabled: boolean) => void;
|
||||
setIsPersonEnabled: (enabled: boolean) => void;
|
||||
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
|
|
@ -112,17 +107,12 @@ export function LivingSpaceUserTypesDataTable({
|
|||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
const setSelection = (id: string, isProperty: boolean) => {
|
||||
setUserTypeID(id); isProperty ? setIsPartsEnabled(true) : setIsPartsEnabled(false); setIsCompanyEnabled(true); setIsPersonEnabled(true)
|
||||
}
|
||||
const setSelection = (id: string, isProperty: boolean) => { setUserTypeID(id); isProperty ? setIsPartsEnabled(true) : setIsPartsEnabled(false); setIsHandleCompanyAndPersonEnable(true) }
|
||||
const columns = getColumns(setSelection);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
data, columns, pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
|
|
@ -138,7 +128,6 @@ export function LivingSpaceUserTypesDataTable({
|
|||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
|
|
@ -197,7 +186,7 @@ export function LivingSpaceUserTypesDataTable({
|
|||
</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} />)}
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow selectedID={userTypeID || ""} key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -4,33 +4,31 @@ import { useGraphQlUserTypesList } from "./queries";
|
|||
import { LivingSpaceUserTypesDataTable } from "./data-table";
|
||||
|
||||
const PageLivingSpaceUserTypesTableSection = (
|
||||
{ userTypeID, setUserTypeID, setIsPartsEnabled, setIsCompanyEnabled, setIsPersonEnabled }: {
|
||||
{ userTypeID, setUserTypeID, setIsPartsEnabled, setIsHandleCompanyAndPersonEnable }: {
|
||||
userTypeID: string | null;
|
||||
setUserTypeID: (id: string | null) => void;
|
||||
setIsPartsEnabled: (enabled: boolean) => void;
|
||||
setIsCompanyEnabled: (enabled: boolean) => void;
|
||||
setIsPersonEnabled: (enabled: boolean) => void;
|
||||
setIsHandleCompanyAndPersonEnable: (enabled: boolean) => void,
|
||||
}
|
||||
) => {
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlUserTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
|
||||
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
|
||||
|
||||
return <>
|
||||
<LivingSpaceUserTypesDataTable
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange}
|
||||
refetchTable={refetch} userTypeID={userTypeID || ""} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsCompanyEnabled={setIsCompanyEnabled}
|
||||
setIsPersonEnabled={setIsPersonEnabled} />
|
||||
refetchTable={refetch} userTypeID={userTypeID || ""} setUserTypeID={setUserTypeID} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable}
|
||||
/>
|
||||
</>;
|
||||
|
||||
}
|
||||
|
||||
export default PageLivingSpaceUserTypesTableSection;
|
||||
export default PageLivingSpaceUserTypesTableSection;
|
||||
|
|
|
|||
Loading…
Reference in New Issue