build-address added tested
This commit is contained in:
parent
6a5acd28db
commit
688576a1de
|
|
@ -11,6 +11,7 @@ import { BuildPartsModule } from './build-parts/build-parts.module';
|
|||
import { BuildAreaModule } from './build-area/build-area.module';
|
||||
import { UserTypesModule } from './user-types/user-types.module';
|
||||
import { BuildTypesModule } from './build-types/build-types.module';
|
||||
import { BuildAddressModule } from './build-address/build-address.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
|
@ -27,6 +28,7 @@ import { BuildTypesModule } from './build-types/build-types.module';
|
|||
BuildAreaModule,
|
||||
UserTypesModule,
|
||||
BuildTypesModule,
|
||||
BuildAddressModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
|
|
|||
|
|
@ -0,0 +1,11 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { BuildAddressService } from './build-address.service';
|
||||
import { BuildAddressResolver } from './build-address.resolver';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { BuildAddress, BuildAddressSchema } from '@/models/build-address.model';
|
||||
|
||||
@Module({
|
||||
imports: [MongooseModule.forFeature([{ name: BuildAddress.name, schema: BuildAddressSchema }])],
|
||||
providers: [BuildAddressService, BuildAddressResolver]
|
||||
})
|
||||
export class BuildAddressModule { }
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { BuildAddressResolver } from './build-address.resolver';
|
||||
|
||||
describe('BuildAddressResolver', () => {
|
||||
let resolver: BuildAddressResolver;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [BuildAddressResolver],
|
||||
}).compile();
|
||||
|
||||
resolver = module.get<BuildAddressResolver>(BuildAddressResolver);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(resolver).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { Resolver, Query, Args, ID, Info, Mutation } from '@nestjs/graphql';
|
||||
import { Types } from 'mongoose';
|
||||
import { BuildAddress } from '@/models/build-address.model';
|
||||
import { ListArguments } from '@/dto/list.input';
|
||||
import { UpdateBuildAddressInput } from './dto/update-build-address.input';
|
||||
import { ListBuildAddressInput } from './dto/list-build-address.response';
|
||||
import { CreateBuildAddressInput } from './dto/create-build-address.input';
|
||||
import graphqlFields from 'graphql-fields';
|
||||
import { BuildAddressService } from './build-address.service';
|
||||
import type { GraphQLResolveInfo } from 'graphql';
|
||||
|
||||
@Resolver()
|
||||
export class BuildAddressResolver {
|
||||
|
||||
constructor(private readonly buildAddressService: BuildAddressService) { }
|
||||
|
||||
@Query(() => ListBuildAddressInput, { name: "buildAddresses" })
|
||||
async getBuildAddresses(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListBuildAddressInput> {
|
||||
const fields = graphqlFields(info); const projection = this.buildAddressService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
|
||||
return await this.buildAddressService.findAll(projection, skip, limit, sort, filters);
|
||||
}
|
||||
|
||||
@Query(() => BuildAddress, { name: 'buildAddress', nullable: true })
|
||||
async getBuildAddress(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<BuildAddress | null> {
|
||||
const fields = graphqlFields(info); const projection = this.buildAddressService.buildProjection(fields); return this.buildAddressService.findById(new Types.ObjectId(id), projection);
|
||||
}
|
||||
|
||||
@Mutation(() => BuildAddress, { name: 'createBuildAddress' })
|
||||
async createBuildAddress(@Args('input') input: CreateBuildAddressInput): Promise<BuildAddress> { return this.buildAddressService.create(input) }
|
||||
|
||||
@Mutation(() => BuildAddress, { name: 'updateBuildAddress' })
|
||||
async updateBuildAddress(@Args('uuid') uuid: string, @Args('input') input: UpdateBuildAddressInput): Promise<BuildAddress> { return this.buildAddressService.update(uuid, input) }
|
||||
|
||||
@Mutation(() => Boolean, { name: 'deleteBuildAddress' })
|
||||
async deleteBuildAddress(@Args('uuid') uuid: string): Promise<boolean> { return this.buildAddressService.delete(uuid) }
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { BuildAddressService } from './build-address.service';
|
||||
|
||||
describe('BuildAddressService', () => {
|
||||
let service: BuildAddressService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [BuildAddressService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<BuildAddressService>(BuildAddressService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { UpdateBuildAddressInput } from './dto/update-build-address.input';
|
||||
import { ListBuildAddressInput } from './dto/list-build-address.response';
|
||||
import { CreateBuildAddressInput } from './dto/create-build-address.input';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Types, Model } from 'mongoose';
|
||||
import { BuildAddress, BuildAddressDocument } from '@/models/build-address.model';
|
||||
|
||||
@Injectable()
|
||||
export class BuildAddressService {
|
||||
|
||||
constructor(@InjectModel(BuildAddress.name) private readonly buildAddressModel: Model<BuildAddressDocument>) { }
|
||||
|
||||
async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildAddressInput> {
|
||||
const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
|
||||
const totalCount = await this.buildAddressModel.countDocuments(query).exec();
|
||||
const data = await this.buildAddressModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
|
||||
return { data, totalCount };
|
||||
}
|
||||
|
||||
async findById(id: Types.ObjectId, projection?: any): Promise<BuildAddressDocument | null> { return this.buildAddressModel.findById(id, projection, { lean: false }).populate({ path: 'person', select: projection?.person }).exec() }
|
||||
|
||||
async create(input: CreateBuildAddressInput): Promise<BuildAddressDocument> { const user = new this.buildAddressModel(input); return user.save() }
|
||||
|
||||
async update(uuid: string, input: UpdateBuildAddressInput): Promise<BuildAddressDocument> { const user = await this.buildAddressModel.findOne({ uuid }); if (!user) { throw new Error('User not found') }; user.set(input); console.dir({ uuid, input }, { depth: null }); return user.save() }
|
||||
|
||||
async delete(uuid: string): Promise<boolean> { const user = await this.buildAddressModel.deleteMany({ uuid }); return user.deletedCount > 0 }
|
||||
|
||||
buildProjection(fields: Record<string, any>): Record<string, 1> { const projection: Record<string, 1> = {}; for (const key in fields) { projection[key] = 1 }; return projection }
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { InputType, Field, Float, ID } from "@nestjs/graphql";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
@InputType()
|
||||
export class CreateBuildAddressInput {
|
||||
@Field()
|
||||
buildNumber: string;
|
||||
|
||||
@Field()
|
||||
doorNumber: string;
|
||||
|
||||
@Field()
|
||||
floorNumber: string;
|
||||
|
||||
@Field()
|
||||
commentAddress: string;
|
||||
|
||||
@Field()
|
||||
letterAddress: string;
|
||||
|
||||
@Field()
|
||||
shortLetterAddress: string;
|
||||
|
||||
@Field(() => Float)
|
||||
latitude: number;
|
||||
|
||||
@Field(() => Float)
|
||||
longitude: number;
|
||||
|
||||
@Field(() => ID, { nullable: true })
|
||||
street?: Types.ObjectId;
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { ObjectType, Field, Int } from "@nestjs/graphql";
|
||||
import { BuildAddress } from "@/models/build-address.model";
|
||||
|
||||
@ObjectType()
|
||||
export class ListBuildAddressInput {
|
||||
|
||||
@Field(() => [BuildAddress], { nullable: true })
|
||||
data?: BuildAddress[];
|
||||
|
||||
@Field(() => Int, { nullable: true })
|
||||
totalCount?: number;
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
import { InputType, Field, Float, ID } from "@nestjs/graphql";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
@InputType()
|
||||
export class UpdateBuildAddressInput {
|
||||
|
||||
@Field({ nullable: true })
|
||||
buildNumber?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
doorNumber?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
floorNumber?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
commentAddress?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
letterAddress?: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
shortLetterAddress?: string;
|
||||
|
||||
@Field(() => Float, { nullable: true })
|
||||
latitude?: number;
|
||||
|
||||
@Field(() => Float, { nullable: true })
|
||||
longitude?: number;
|
||||
|
||||
@Field(() => ID, { nullable: true })
|
||||
street?: Types.ObjectId;
|
||||
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { Field, Int, InputType, ObjectType } from '@nestjs/graphql';
|
|||
|
||||
@InputType()
|
||||
export class ListArguments {
|
||||
|
||||
@Field(() => GraphQLJSONObject, { nullable: true })
|
||||
filters?: any;
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ import { Base } from '@/models/base.model';
|
|||
@ObjectType()
|
||||
@Schema({ timestamps: true })
|
||||
export class BuildAddress extends Base {
|
||||
|
||||
@Field(() => ID)
|
||||
readonly _id: string;
|
||||
|
||||
@Field()
|
||||
@Prop({ required: true })
|
||||
buildNumber: string;
|
||||
|
|
@ -38,9 +42,10 @@ export class BuildAddress extends Base {
|
|||
@Prop({ required: true })
|
||||
longitude: number;
|
||||
|
||||
@Field(() => ID)
|
||||
@Prop({ type: Types.ObjectId, ref: 'Street', required: true })
|
||||
street: Types.ObjectId;
|
||||
@Field(() => ID, { nullable: true })
|
||||
@Prop({ type: Types.ObjectId, ref: 'Street', required: false })
|
||||
street?: Types.ObjectId;
|
||||
|
||||
}
|
||||
|
||||
export type BuildAddressDocument = BuildAddress & Document;
|
||||
|
|
|
|||
|
|
@ -3,9 +3,11 @@ import { Person } from "@/models/person.model";
|
|||
|
||||
@ObjectType()
|
||||
export class ListPeopleResponse {
|
||||
|
||||
@Field(() => [Person], { nullable: true })
|
||||
data?: Person[];
|
||||
|
||||
@Field(() => Int, { nullable: true })
|
||||
totalCount?: number;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,7 @@ import { UsersService } from './users.service';
|
|||
import { UserSchema, User } from '@/models/user.model';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])
|
||||
],
|
||||
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
|
||||
providers: [UsersService, UsersResolver],
|
||||
})
|
||||
export class UsersModule { }
|
||||
|
|
|
|||
|
|
@ -1,38 +1,9 @@
|
|||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
# ToDo's
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
||||
new Date('2025-11-14T18:21:35.212Z').toLocaleString("en-US", { timeZone: "Europe/Istanbul", hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
Build:
|
||||
BuildPart:
|
||||
Build Living Space:
|
||||
People:
|
||||
User:
|
||||
Company:
|
||||
ADD UPDATE yapan page:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { buildTypesAddSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validatedBody = buildTypesAddSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation CreateBuildAddress($input: CreateBuildAddressInput!) {
|
||||
createBuildAddress(input: $input) {
|
||||
_id
|
||||
buildNumber
|
||||
doorNumber
|
||||
floorNumber
|
||||
commentAddress
|
||||
letterAddress
|
||||
shortLetterAddress
|
||||
latitude
|
||||
longitude
|
||||
street
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.createBuildAddress, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildTypesAddSchema = z.object({
|
||||
buildNumber: z.string(),
|
||||
doorNumber: z.string(),
|
||||
floorNumber: z.string(),
|
||||
commentAddress: z.string(),
|
||||
letterAddress: z.string(),
|
||||
shortLetterAddress: z.string(),
|
||||
latitude: z.number(),
|
||||
longitude: z.number(),
|
||||
street: z.string().optional(),
|
||||
});
|
||||
|
||||
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const uuid = searchParams.get('uuid');
|
||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation DeleteBuildAddress($uuid: String!) { deleteBuildAddress(uuid: $uuid) }`;
|
||||
const variables = { uuid: uuid };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.deleteBuildAddress, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const { limit, skip, sort, filters } = body;
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
query GetBuildAddresses($input: ListArguments!) {
|
||||
buildAddresses(input: $input) {
|
||||
totalCount
|
||||
data {
|
||||
_id
|
||||
uuid
|
||||
buildNumber
|
||||
doorNumber
|
||||
floorNumber
|
||||
commentAddress
|
||||
letterAddress
|
||||
shortLetterAddress
|
||||
latitude
|
||||
longitude
|
||||
street
|
||||
createdAt
|
||||
updatedAt
|
||||
expiryStarts
|
||||
expiryEnds
|
||||
}
|
||||
}
|
||||
}`;
|
||||
const variables = { input: { limit, skip, sort, filters } };
|
||||
console.dir({ variables })
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.buildAddresses.data, totalCount: data.buildAddresses.totalCount });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { UpdateBuildAddressSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const searchUrl = new URL(request.url);
|
||||
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||
const body = await request.json();
|
||||
const validatedBody = UpdateBuildAddressSchema.parse(body);
|
||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation UpdateBuildAddress($uuid: String!, $input: UpdateBuildAddressInput!) {
|
||||
updateBuildAddress(uuid: $uuid, input: $input) {
|
||||
_id
|
||||
buildNumber
|
||||
doorNumber
|
||||
floorNumber
|
||||
commentAddress
|
||||
letterAddress
|
||||
shortLetterAddress
|
||||
latitude
|
||||
longitude
|
||||
street
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { uuid: uuid, input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.updateBuildAddress, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const UpdateBuildAddressSchema = z.object({
|
||||
buildNumber: z.string().optional(),
|
||||
doorNumber: z.string().optional(),
|
||||
floorNumber: z.string().optional(),
|
||||
commentAddress: z.string().optional(),
|
||||
letterAddress: z.string().optional(),
|
||||
shortLetterAddress: z.string().optional(),
|
||||
latitude: z.number().optional(),
|
||||
longitude: z.number().optional(),
|
||||
street: z.string().optional(),
|
||||
});
|
||||
|
||||
export type UpdateBuildAddress = z.infer<typeof UpdateBuildAddressSchema>;
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { buildTypesAddSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validatedBody = buildTypesAddSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation CreateBuildType($input: CreateBuildTypesInput!) {
|
||||
createBuildType(input: $input) {
|
||||
type
|
||||
token
|
||||
typeToken
|
||||
description
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.createBuildType, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildTypesAddSchema = z.object({
|
||||
type: z.string(),
|
||||
token: z.string(),
|
||||
typeToken: z.string(),
|
||||
description: z.string().optional().default(''),
|
||||
});
|
||||
|
||||
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const uuid = searchParams.get('uuid');
|
||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation DeletePerson($uuid: String!) { deletePerson(uuid: $uuid)}`;
|
||||
const variables = { uuid: uuid };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.deletePerson, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const { limit, skip, sort, filters } = body;
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
query GetBuildTypes($input: ListArguments!) {
|
||||
buildTypes(input: $input) {
|
||||
totalCount
|
||||
data {
|
||||
_id
|
||||
uuid
|
||||
type
|
||||
token
|
||||
typeToken
|
||||
description
|
||||
createdAt
|
||||
updatedAt
|
||||
expiryStarts
|
||||
expiryEnds
|
||||
}
|
||||
}
|
||||
}`;
|
||||
const variables = { input: { limit, skip, sort, filters } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.buildTypes.data, totalCount: data.buildTypes.totalCount });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { personUpdateSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const searchUrl = new URL(request.url);
|
||||
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||
const body = await request.json();
|
||||
const validatedBody = personUpdateSchema.parse(body);
|
||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation UpdateBuildType($uuid: String!, $input: UpdateBuildTypesInput!) {
|
||||
updateBuildType(uuid: $uuid, input: $input) {
|
||||
type
|
||||
token
|
||||
typeToken
|
||||
description
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { uuid: uuid, input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.updateBuildType, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const personUpdateSchema = z.object({
|
||||
firstName: z.string().optional(),
|
||||
surname: z.string().optional(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string().optional(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string().optional(),
|
||||
nationalIdentityId: z.string().optional(),
|
||||
birthPlace: z.string().optional(),
|
||||
birthDate: z.string().optional(),
|
||||
taxNo: z.string().optional().optional(),
|
||||
birthname: z.string().optional().optional(),
|
||||
expiryStarts: z.string().optional().optional(),
|
||||
expiryEnds: z.string().optional().optional(),
|
||||
});
|
||||
|
||||
export type PeopleUpdate = z.infer<typeof personUpdateSchema>;
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { personAddSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validatedBody = personAddSchema.parse(body);
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation CreatePerson($input: CreatePersonInput!) {
|
||||
createPerson(input: $input) {
|
||||
uuid
|
||||
firstName
|
||||
surname
|
||||
birthDate
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.createPerson, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// export async function POST(request: Request) {
|
||||
|
||||
// const body = await request.json();
|
||||
// const validatedBody = userAddSchema.parse(body);
|
||||
// console.log("VALIDATED")
|
||||
// console.dir({ validatedBody })
|
||||
// return NextResponse.json({ data: validatedBody })
|
||||
// }
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const personAddSchema = z.object({
|
||||
firstName: z.string(),
|
||||
surname: z.string(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string(),
|
||||
nationalIdentityId: z.string(),
|
||||
birthPlace: z.string(),
|
||||
birthDate: z.string(),
|
||||
taxNo: z.string().optional(),
|
||||
birthname: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type PeopleAdd = z.infer<typeof personAddSchema>;
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const uuid = searchParams.get('uuid');
|
||||
if (!uuid) { return NextResponse.json({ error: 'UUID not found in search params' }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`mutation DeletePerson($uuid: String!) { deletePerson(uuid: $uuid)}`;
|
||||
const variables = { uuid: uuid };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.deletePerson, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
'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 GetPeople($input: ListArguments!) {
|
||||
people(input: $input) {
|
||||
totalCount
|
||||
data {
|
||||
_id
|
||||
uuid
|
||||
firstName
|
||||
surname
|
||||
middleName
|
||||
sexCode
|
||||
personRef
|
||||
personTag
|
||||
fatherName
|
||||
motherName
|
||||
countryCode
|
||||
nationalIdentityId
|
||||
birthPlace
|
||||
birthDate
|
||||
taxNo
|
||||
birthname
|
||||
expiryStarts
|
||||
expiryEnds
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { input: { limit, skip, sort, filters } };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.people.data, totalCount: data.people.totalCount });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
'use server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { GraphQLClient, gql } from 'graphql-request';
|
||||
import { personUpdateSchema } from './schema';
|
||||
|
||||
const endpoint = "http://localhost:3001/graphql";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const searchUrl = new URL(request.url);
|
||||
const uuid = searchUrl.searchParams.get("uuid") || "";
|
||||
const body = await request.json();
|
||||
const validatedBody = personUpdateSchema.parse(body);
|
||||
console.dir({ validatedBody });
|
||||
if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
|
||||
try {
|
||||
const client = new GraphQLClient(endpoint);
|
||||
const query = gql`
|
||||
mutation updatePerson($uuid: String! $input: UpdatePersonInput!) {
|
||||
updatePerson(uuid: $uuid, input: $input) {
|
||||
uuid
|
||||
firstName
|
||||
surname
|
||||
sexCode
|
||||
}
|
||||
}
|
||||
`;
|
||||
const variables = { uuid: uuid, input: validatedBody };
|
||||
const data = await client.request(query, variables);
|
||||
return NextResponse.json({ data: data.updatePerson, status: 200 });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const personUpdateSchema = z.object({
|
||||
firstName: z.string().optional(),
|
||||
surname: z.string().optional(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string().optional(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string().optional(),
|
||||
nationalIdentityId: z.string().optional(),
|
||||
birthPlace: z.string().optional(),
|
||||
birthDate: z.string().optional(),
|
||||
taxNo: z.string().optional().optional(),
|
||||
birthname: z.string().optional().optional(),
|
||||
expiryStarts: z.string().optional().optional(),
|
||||
expiryEnds: z.string().optional().optional(),
|
||||
});
|
||||
|
||||
export type PeopleUpdate = z.infer<typeof personUpdateSchema>;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { PageAddBuildAddress } from "@/pages/build-address/add/page";
|
||||
|
||||
const BuildAddress = () => {
|
||||
return <PageAddBuildAddress />
|
||||
}
|
||||
|
||||
export default BuildAddress;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { PageBuildAddress } from "@/pages/build-address/page";
|
||||
|
||||
const BuildAddress = () => {
|
||||
return <PageBuildAddress />
|
||||
}
|
||||
|
||||
export default BuildAddress;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { PageUpdateBuildAddress } from "@/pages/build-address/update/page";
|
||||
|
||||
const BuildAddress = () => {
|
||||
return <PageUpdateBuildAddress />
|
||||
}
|
||||
|
||||
export default BuildAddress;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageAddBuildTypes } from "@/pages/build-types/add/page";
|
||||
|
||||
const AddBuildTypesPage = () => { return <><PageAddBuildTypes /></> }
|
||||
|
||||
export default AddBuildTypesPage;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageBuildTypes } from "@/pages/build-types/page";
|
||||
|
||||
const BuildTypesPage = () => { return <><PageBuildTypes /></> }
|
||||
|
||||
export default BuildTypesPage;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageUpdateBuildTypes } from '@/pages/build-types/update/page';
|
||||
|
||||
const UpdateBuildTypesPage = async () => { return <PageUpdateBuildTypes /> }
|
||||
|
||||
export default UpdateBuildTypesPage;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageAddPerson } from "@/pages/people/add/page";
|
||||
|
||||
const AddPersonPage = () => { return <><PageAddPerson /></> }
|
||||
|
||||
export default AddPersonPage;
|
||||
|
|
@ -1,10 +1,5 @@
|
|||
import { PagePeople } from "@/pages/people/page";
|
||||
|
||||
const PeoplePage = () => {
|
||||
return (
|
||||
<div>
|
||||
<h1>People</h1>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const PeoplePage = () => { return <><PagePeople /></> }
|
||||
|
||||
export default PeoplePage;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
import { PageUpdatePeople } from '@/pages/people/update/page';
|
||||
|
||||
const UpdatePeoplePage = async () => { return <PageUpdatePeople /> }
|
||||
|
||||
export default UpdatePeoplePage;
|
||||
|
|
@ -1,51 +1,30 @@
|
|||
"use client"
|
||||
|
||||
import { IconCirclePlusFilled, IconMail, type Icon } from "@tabler/icons-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
} from "@/components/ui/sidebar"
|
||||
import Link from "next/link"
|
||||
import { type Icon } from "@tabler/icons-react"
|
||||
import { SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar"
|
||||
import { usePathname } from 'next/navigation'
|
||||
|
||||
export function NavMain({
|
||||
items,
|
||||
}: {
|
||||
items: {
|
||||
title: string
|
||||
url: string
|
||||
icon?: Icon
|
||||
}[]
|
||||
}) {
|
||||
const pathname = usePathname()
|
||||
const linkRenderActive = (item: { title: string; url: string; icon?: Icon }) =>
|
||||
<Link key={`${item.title}-${item.url}`} href={item.url}>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton tooltip={item.title}>
|
||||
{item.icon && <item.icon />}
|
||||
<span>{item.title}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</Link>
|
||||
interface NavMainProps {
|
||||
title: string
|
||||
url: string
|
||||
icon?: Icon
|
||||
}
|
||||
|
||||
const linkRenderDisabled = (item: { title: string; url: string; icon?: Icon }) =>
|
||||
export function NavMain({ items }: { items: NavMainProps[] }) {
|
||||
const pathname = usePathname()?.split("/")[1]
|
||||
const linkRenderActive = (item: NavMainProps) =>
|
||||
<Link key={`${item.title}-${item.url}`} href={item.url}><SidebarMenuItem>
|
||||
<SidebarMenuButton tooltip={item.title}>{item.icon && <item.icon />}<span>{item.title}</span></SidebarMenuButton>
|
||||
</SidebarMenuItem></Link>
|
||||
const linkRenderDisabled = (item: NavMainProps) =>
|
||||
<SidebarMenuItem key={`${item.title}-${item.url}`} className="opacity-50 bg-gray-300 border-gray-300 border-2 rounded-2xl">
|
||||
<SidebarMenuButton disabled tooltip={item.title}>
|
||||
{item.icon && <item.icon />}
|
||||
<span>{item.title}</span>
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuButton disabled tooltip={item.title}>{item.icon && <item.icon />}<span>{item.title}</span></SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
return (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupContent className="flex flex-col gap-2">
|
||||
<SidebarMenu>
|
||||
{items.map((item) => pathname?.includes(item.url) ? linkRenderDisabled(item) : linkRenderActive(item))}
|
||||
{items.map((item) => pathname?.toLocaleLowerCase() === item.url?.split("/")[1].toLocaleLowerCase() ? linkRenderDisabled(item) : linkRenderActive(item))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
|
|
|||
|
|
@ -14,10 +14,11 @@ import {
|
|||
IconInnerShadowTop,
|
||||
IconListDetails,
|
||||
IconReport,
|
||||
IconSearch,
|
||||
IconAddressBook,
|
||||
IconSettings,
|
||||
IconUsers,
|
||||
IconBuilding
|
||||
IconBuilding,
|
||||
IconTypeface
|
||||
} from "@tabler/icons-react"
|
||||
|
||||
import { NavMain } from "@/components/dashboard/nav-main"
|
||||
|
|
@ -57,98 +58,98 @@ const data = {
|
|||
url: "/build",
|
||||
icon: IconBuilding,
|
||||
},
|
||||
// {
|
||||
// title: "Projects",
|
||||
// url: "#",
|
||||
// icon: IconFolder,
|
||||
// },
|
||||
// {
|
||||
// title: "Team",
|
||||
// url: "#",
|
||||
// icon: IconUsers,
|
||||
// },
|
||||
{
|
||||
title: "Build Types",
|
||||
url: "/build-types",
|
||||
icon: IconTypeface,
|
||||
},
|
||||
{
|
||||
title: "Build Addresses",
|
||||
url: "/build-address",
|
||||
icon: IconAddressBook,
|
||||
}
|
||||
],
|
||||
navClouds: [
|
||||
{
|
||||
title: "Capture",
|
||||
icon: IconCamera,
|
||||
isActive: true,
|
||||
url: "#",
|
||||
items: [
|
||||
{
|
||||
title: "Active Proposals",
|
||||
url: "#",
|
||||
},
|
||||
{
|
||||
title: "Archived",
|
||||
url: "#",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Proposal",
|
||||
icon: IconFileDescription,
|
||||
url: "#",
|
||||
items: [
|
||||
{
|
||||
title: "Active Proposals",
|
||||
url: "#",
|
||||
},
|
||||
{
|
||||
title: "Archived",
|
||||
url: "#",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Prompts",
|
||||
icon: IconFileAi,
|
||||
url: "#",
|
||||
items: [
|
||||
{
|
||||
title: "Active Proposals",
|
||||
url: "#",
|
||||
},
|
||||
{
|
||||
title: "Archived",
|
||||
url: "#",
|
||||
},
|
||||
],
|
||||
},
|
||||
// {
|
||||
// title: "Capture",
|
||||
// icon: IconCamera,
|
||||
// isActive: true,
|
||||
// url: "#",
|
||||
// items: [
|
||||
// {
|
||||
// title: "Active Proposals",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Archived",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Proposal",
|
||||
// icon: IconFileDescription,
|
||||
// url: "#",
|
||||
// items: [
|
||||
// {
|
||||
// title: "Active Proposals",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Archived",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Prompts",
|
||||
// icon: IconFileAi,
|
||||
// url: "#",
|
||||
// items: [
|
||||
// {
|
||||
// title: "Active Proposals",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Archived",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
],
|
||||
navSecondary: [
|
||||
{
|
||||
title: "Settings",
|
||||
url: "#",
|
||||
icon: IconSettings,
|
||||
},
|
||||
{
|
||||
title: "Get Help",
|
||||
url: "#",
|
||||
icon: IconHelp,
|
||||
},
|
||||
{
|
||||
title: "Search",
|
||||
url: "#",
|
||||
icon: IconSearch,
|
||||
},
|
||||
// {
|
||||
// title: "Settings",
|
||||
// url: "#",
|
||||
// icon: IconSettings,
|
||||
// },
|
||||
// {
|
||||
// title: "Get Help",
|
||||
// url: "#",
|
||||
// icon: IconHelp,
|
||||
// },
|
||||
// {
|
||||
// title: "Search",
|
||||
// url: "#",
|
||||
// icon: IconSearch,
|
||||
// },
|
||||
],
|
||||
documents: [
|
||||
{
|
||||
name: "Data Library",
|
||||
url: "#",
|
||||
icon: IconDatabase,
|
||||
},
|
||||
{
|
||||
name: "Reports",
|
||||
url: "#",
|
||||
icon: IconReport,
|
||||
},
|
||||
{
|
||||
name: "Word Assistant",
|
||||
url: "#",
|
||||
icon: IconFileWord,
|
||||
},
|
||||
// {
|
||||
// name: "Data Library",
|
||||
// url: "#",
|
||||
// icon: IconDatabase,
|
||||
// },
|
||||
// {
|
||||
// name: "Reports",
|
||||
// url: "#",
|
||||
// icon: IconReport,
|
||||
// },
|
||||
// {
|
||||
// name: "Word Assistant",
|
||||
// url: "#",
|
||||
// icon: IconFileWord,
|
||||
// },
|
||||
],
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -213,7 +213,5 @@ export const dateGetter = (str: string | undefined): Date | null => {
|
|||
export const dateSetter = (date: Date | null): string => {
|
||||
if (!date) return "";
|
||||
const fmt = (n: number) => String(n).padStart(2, "0");
|
||||
return `${fmt(date.getDate())}/${fmt(date.getMonth() + 1)}/${date.getFullYear()} ${fmt(
|
||||
date.getHours()
|
||||
)}:${fmt(date.getMinutes())}:${fmt(date.getSeconds())}`;
|
||||
return `${fmt(date.getDate())}/${fmt(date.getMonth() + 1)}/${date.getFullYear()} ${fmt(date.getHours())}:${fmt(date.getMinutes())}:${fmt(date.getSeconds())}`;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,4 +9,20 @@ export function dateToLocaleString(date: string) {
|
|||
return new Date(date).toLocaleString("en-US",
|
||||
{ timeZone: "Europe/Istanbul", hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function toISOIfNotZ(val: string): string {
|
||||
if (val.endsWith("Z")) return val;
|
||||
const [d, m, yAndTime] = val.split("/");
|
||||
if (!yAndTime) return val;
|
||||
const [y, time] = yAndTime.split(" ");
|
||||
if (!time) return val;
|
||||
const [h, min, s] = time.split(":").map(Number);
|
||||
try {
|
||||
const date = new Date(Number(y), Number(m) - 1, Number(d), h, min, s);
|
||||
return date ? date.toISOString() : "";
|
||||
} catch (error) {
|
||||
console.error("Error converting date:", error);
|
||||
return val;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,250 @@
|
|||
"use client"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
import { buildAddressAddSchema, BuildAddressAdd } from "./schema"
|
||||
import { useAddBuildAddressMutation } from "./queries"
|
||||
|
||||
const BuildAddressForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
|
||||
const form = useForm<BuildAddressAdd>({
|
||||
resolver: zodResolver(buildAddressAddSchema),
|
||||
defaultValues: {
|
||||
buildNumber: "",
|
||||
doorNumber: "",
|
||||
floorNumber: "",
|
||||
commentAddress: "",
|
||||
letterAddress: "",
|
||||
shortLetterAddress: "",
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
street: "",
|
||||
expiryStarts: "",
|
||||
expiryEnds: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit } = form;
|
||||
|
||||
const mutation = useAddBuildAddressMutation();
|
||||
|
||||
function onSubmit(values: BuildAddressAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
{/* ROW 1 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="buildNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Build Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="12A" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="doorNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Door Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="3" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 2 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="floorNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Floor Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="street"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Street ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="671f0d..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 3 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="commentAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Comment Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Near the market..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="letterAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Letter Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="123 Lemon St" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 4 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="shortLetterAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Short Letter Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Lmn St 123" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="latitude"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Latitude</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="41.0082"
|
||||
value={field.value ?? ""}
|
||||
onChange={(e) =>
|
||||
field.onChange(e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 5 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="longitude"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Longitude</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="28.9784"
|
||||
value={field.value ?? ""}
|
||||
onChange={(e) =>
|
||||
field.onChange(e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* EXPIRY DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full">
|
||||
Add Build Address
|
||||
</Button>
|
||||
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export { BuildAddressForm }
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { BuildAddressForm } from '@/pages/build-address/add/form';
|
||||
import { PeopleDataTableUpdate } from './table/data-table';
|
||||
import { useGraphQlBuildAddressesList } from '@/pages/build-address/queries';
|
||||
|
||||
const PageAddBuildAddress = () => {
|
||||
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 } = useGraphQlBuildAddressesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
return (
|
||||
<>
|
||||
<PeopleDataTableUpdate
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildAddressForm refetchTable={refetch} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageAddBuildAddress };
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { toISOIfNotZ } from '@/lib/utils';
|
||||
import { BuildAddressAdd } from './schema';
|
||||
|
||||
const fetchGraphQlBuildAddressAdd = async (record: BuildAddressAdd): Promise<{ data: BuildAddressAdd | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch('/api/build-address/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 }
|
||||
};
|
||||
|
||||
export function useAddBuildAddressMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data }: { data: BuildAddressAdd }) => fetchGraphQlBuildAddressAdd(data),
|
||||
onSuccess: () => { console.log("Build address created successfully") },
|
||||
onError: (error) => { console.error("Create build address failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildAddressAddSchema = z.object({
|
||||
buildNumber: z.string(),
|
||||
doorNumber: z.string(),
|
||||
floorNumber: z.string(),
|
||||
commentAddress: z.string(),
|
||||
letterAddress: z.string(),
|
||||
shortLetterAddress: z.string(),
|
||||
latitude: z.number(),
|
||||
longitude: z.number(),
|
||||
street: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type BuildAddressAdd = z.infer<typeof buildAddressAddSchema>;
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "buildNumber",
|
||||
header: "Build Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "doorNumber",
|
||||
header: "Door Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "floorNumber",
|
||||
header: "Floor Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "commentAddress",
|
||||
header: "Comment Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "letterAddress",
|
||||
header: "Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "shortLetterAddress",
|
||||
header: "Short Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "latitude",
|
||||
header: "Latitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "longitude",
|
||||
header: "Longitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "street",
|
||||
header: "StreetId",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/build-address/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,282 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeleteBuildAddressMutation } from "@/pages/build-address/queries"
|
||||
|
||||
export function PeopleDataTableUpdate({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteBuildAddressMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-address") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Build Address</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
firstName: z.string().optional(),
|
||||
surname: z.string().optional(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string().optional(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string().optional(),
|
||||
nationalIdentityId: z.string().optional(),
|
||||
birthPlace: z.string().optional(),
|
||||
birthDate: z.string().optional(),
|
||||
taxNo: z.string().optional(),
|
||||
birthname: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
|
||||
interface PeopleAdd {
|
||||
|
||||
firstName: string;
|
||||
surname: string;
|
||||
middleName?: string;
|
||||
sexCode: string;
|
||||
personRef?: string;
|
||||
personTag?: string;
|
||||
fatherName?: string;
|
||||
motherName?: string;
|
||||
countryCode: string;
|
||||
nationalIdentityId: string;
|
||||
birthPlace: string;
|
||||
birthDate: string;
|
||||
taxNo?: string;
|
||||
birthname?: string;
|
||||
expiryStarts?: string;
|
||||
expiryEnds?: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
export type { PeopleAdd };
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): 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: "buildNumber",
|
||||
header: "Build Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "doorNumber",
|
||||
header: "Door Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "floorNumber",
|
||||
header: "Floor Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "commentAddress",
|
||||
header: "Comment Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "letterAddress",
|
||||
header: "Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "shortLetterAddress",
|
||||
header: "Short Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "latitude",
|
||||
header: "Latitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "longitude",
|
||||
header: "Longitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "street",
|
||||
header: "StreetId",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/build-address/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,270 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
IconPlus,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDeleteBuildAddressMutation } from "../queries"
|
||||
|
||||
export function BuildAddressDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteBuildAddressMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-address/add") }}>
|
||||
<IconPlus />
|
||||
<span className="hidden lg:inline">Add Build Address</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
buildNumber: z.string().optional(),
|
||||
doorNumber: z.string().optional(),
|
||||
floorNumber: z.string().optional(),
|
||||
commentAddress: z.string().optional(),
|
||||
letterAddress: z.string().optional(),
|
||||
shortLetterAddress: z.string().optional(),
|
||||
latitude: z.number().optional(),
|
||||
longitude: z.number().optional(),
|
||||
street: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client';
|
||||
import { BuildAddressDataTable } from './list/data-table';
|
||||
import { useGraphQlBuildAddressesList } from './queries';
|
||||
import { useState } from 'react';
|
||||
|
||||
const PageBuildAddress = () => {
|
||||
|
||||
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 } = useGraphQlBuildAddressesList({ 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 <BuildAddressDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
|
||||
|
||||
};
|
||||
|
||||
export { PageBuildAddress };
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
'use client'
|
||||
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
|
||||
const fetchGraphQlBuildAddressesList = 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/build-address/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ limit, skip, sort, filters }) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, totalCount: data.totalCount }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlDeleteBuildAddress = async (uuid: string): Promise<boolean> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/build-address/delete?uuid=${uuid}`, { method: 'GET', cache: 'no-store', credentials: "include" });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return data
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useGraphQlBuildAddressesList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-build-addresses-list', params], queryFn: () => fetchGraphQlBuildAddressesList(params) })
|
||||
}
|
||||
|
||||
export function useDeleteBuildAddressMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteBuildAddress(uuid),
|
||||
onSuccess: () => { console.log("Build address deleted successfully") },
|
||||
onError: (error) => { console.error("Delete build address failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
|
||||
interface BuildAddress {
|
||||
|
||||
_id: string;
|
||||
uuid: string;
|
||||
buildNumber: string;
|
||||
doorNumber: string;
|
||||
floorNumber: string;
|
||||
commentAddress: string;
|
||||
letterAddress: string;
|
||||
shortLetterAddress: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
street: string;
|
||||
expiryStarts: string | null;
|
||||
expiryEnds: string | null;
|
||||
|
||||
}
|
||||
|
||||
export type { BuildAddress };
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
"use client"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
import { useUpdateBuildAddressMutation } from "@/pages/build-address/update/queries"
|
||||
import { buildAddressUpdateSchema, type BuildAddressUpdate } from "@/pages/build-address/update/schema"
|
||||
|
||||
const BuildAddressForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: BuildAddressUpdate, selectedUuid: string }) => {
|
||||
|
||||
const form = useForm<BuildAddressUpdate>({ resolver: zodResolver(buildAddressUpdateSchema), defaultValues: { ...initData, street: "" } })
|
||||
|
||||
const { handleSubmit } = form
|
||||
|
||||
const mutation = useUpdateBuildAddressMutation();
|
||||
|
||||
function onSubmit(values: BuildAddressUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 400) }
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
{/* ROW 1 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="buildNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Build Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="12A" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="doorNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Door Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="3" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 2 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="floorNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Floor Number</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="street"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Street ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="671f0d..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 3 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="commentAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Comment Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Near the market..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="letterAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Letter Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="123 Lemon St" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 4 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="shortLetterAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Short Letter Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Lmn St 123" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="latitude"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Latitude</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="41.0082"
|
||||
value={field.value ?? ""}
|
||||
onChange={(e) =>
|
||||
field.onChange(e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{/* ROW 5 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="longitude"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Longitude</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="28.9784"
|
||||
value={field.value ?? ""}
|
||||
onChange={(e) =>
|
||||
field.onChange(e.target.value ? Number(e.target.value) : undefined)
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* EXPIRY DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Update Build Address
|
||||
</Button>
|
||||
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
export { BuildAddressForm }
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlBuildAddressesList } from '@/pages/build-address/queries';
|
||||
import { BuildAddressDataTableUpdate } from '@/pages/build-address/update/table/data-table';
|
||||
import { BuildAddressForm } from '@/pages/build-address/update/form';
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
const PageUpdateBuildAddress = () => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const uuid = searchParams?.get('uuid') || null
|
||||
const backToBuildAddress = <>
|
||||
<div>UUID not found in search params</div>
|
||||
<Button onClick={() => router.push('/build-address')}>Back to Build Address</Button>
|
||||
</>
|
||||
if (!uuid) { return backToBuildAddress }
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildAddressesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||
const initData = data?.data?.[0] || null;
|
||||
if (!initData) { return backToBuildAddress }
|
||||
return (
|
||||
<>
|
||||
<BuildAddressDataTableUpdate
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildAddressForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageUpdateBuildAddress };
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { BuildAddressUpdate } from './types';
|
||||
|
||||
const fetchGraphQlBuildAddressUpdate = async (record: BuildAddressUpdate, uuid: string): Promise<{ data: BuildAddressUpdate | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/build-address/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 useUpdateBuildAddressMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data, uuid }: { data: BuildAddressUpdate, uuid: string }) => fetchGraphQlBuildAddressUpdate(data, uuid),
|
||||
onSuccess: () => { console.log("Build Address updated successfully") },
|
||||
onError: (error) => { console.error("Update Build Address failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildAddressUpdateSchema = z.object({
|
||||
buildNumber: z.string().optional(),
|
||||
doorNumber: z.string().optional(),
|
||||
floorNumber: z.string().optional(),
|
||||
commentAddress: z.string().optional(),
|
||||
letterAddress: z.string().optional(),
|
||||
shortLetterAddress: z.string().optional(),
|
||||
latitude: z.number().optional(),
|
||||
longitude: z.number().optional(),
|
||||
street: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type BuildAddressUpdate = z.infer<typeof buildAddressUpdateSchema>;
|
||||
|
|
@ -0,0 +1,225 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function TableCellViewer({ item }: { item: schemaType }) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return (
|
||||
<Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
{item.email ?? "Unknown Email"}
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="gap-1">
|
||||
<h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
User details
|
||||
</p>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<Input value={item.email ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Phone</Label>
|
||||
<Input value={item.phone ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Tag</Label>
|
||||
<Input value={item.tag ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Active</Label>
|
||||
<Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Created At</Label>
|
||||
<Input
|
||||
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Updated At</Label>
|
||||
<Input
|
||||
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* TOKENS */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full">
|
||||
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 w-full">
|
||||
<Input value={t.prefix} readOnly />
|
||||
<Input value={t.token} readOnly />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "buildNumber",
|
||||
header: "Build Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "doorNumber",
|
||||
header: "Door Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "floorNumber",
|
||||
header: "Floor Number",
|
||||
},
|
||||
{
|
||||
accessorKey: "commentAddress",
|
||||
header: "Comment Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "letterAddress",
|
||||
header: "Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "shortLetterAddress",
|
||||
header: "Short Letter Address",
|
||||
},
|
||||
{
|
||||
accessorKey: "latitude",
|
||||
header: "Latitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "longitude",
|
||||
header: "Longitude",
|
||||
},
|
||||
{
|
||||
accessorKey: "street",
|
||||
header: "StreetId",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,279 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeletePersonMutation } from "@/pages/people/queries"
|
||||
|
||||
export function BuildAddressDataTableUpdate({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeletePersonMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-address") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Build Address</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
isConfirmed: z.boolean().nullable().optional(),
|
||||
deleted: z.boolean().nullable().optional(),
|
||||
active: z.boolean().nullable().optional(),
|
||||
crypUuId: z.string().nullable().optional(),
|
||||
createdCredentialsToken: z.string().nullable().optional(),
|
||||
updatedCredentialsToken: z.string().nullable().optional(),
|
||||
confirmedCredentialsToken: z.string().nullable().optional(),
|
||||
isNotificationSend: z.boolean().nullable().optional(),
|
||||
isEmailSend: z.boolean().nullable().optional(),
|
||||
refInt: z.number().nullable().optional(),
|
||||
refId: z.string().nullable().optional(),
|
||||
replicationId: z.number().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
resetToken: z.string().nullable().optional(),
|
||||
password: z.string().nullable().optional(),
|
||||
history: z.array(z.string()).optional(),
|
||||
tag: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
|
||||
collectionTokens: z
|
||||
.object({
|
||||
default: z.string().nullable().optional(),
|
||||
tokens: z
|
||||
.array(
|
||||
z.object({
|
||||
prefix: z.string(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
|
||||
interface BuildAddressUpdate {
|
||||
buildNumber: string;
|
||||
doorNumber: string;
|
||||
floorNumber: string;
|
||||
commentAddress: string;
|
||||
letterAddress: string;
|
||||
shortLetterAddress: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
street: string;
|
||||
expiryStarts: string | null;
|
||||
expiryEnds: string | null;
|
||||
}
|
||||
|
||||
|
||||
export type { BuildAddressUpdate };
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
"use client"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { BuildTypesAdd, buildTypesAddSchema } from "./schema"
|
||||
import { useAddBuildTypesMutation } from "./queries"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
|
||||
const BuildTypesForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
|
||||
const form = useForm<BuildTypesAdd>({
|
||||
resolver: zodResolver(buildTypesAddSchema),
|
||||
defaultValues: {
|
||||
type: "",
|
||||
token: "",
|
||||
typeToken: "",
|
||||
description: "",
|
||||
expiryStarts: "",
|
||||
expiryEnds: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit } = form;
|
||||
|
||||
const mutation = useAddBuildTypesMutation();
|
||||
|
||||
function onSubmit(values: BuildTypesAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
{/* TYPE + TOKEN */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Type..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Token..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* TYPE TOKEN + DESCRIPTION */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="typeToken"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Type Token..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Description..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* EXPIRY DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Update Build Type
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export { BuildTypesForm }
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlBuildTypesList } from '@/pages/build-types/queries';
|
||||
import { BuildTypesForm } from './form';
|
||||
import { BuildTypesDataTableAdd } from './table/data-table';
|
||||
|
||||
const PageAddBuildTypes = () => {
|
||||
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 } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
return (
|
||||
<>
|
||||
<BuildTypesDataTableAdd
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildTypesForm refetchTable={refetch} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageAddBuildTypes };
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { BuildTypesAdd } from './types'
|
||||
import { toISOIfNotZ } from '@/lib/utils';
|
||||
|
||||
const fetchGraphQlBuildTypesAdd = async (record: BuildTypesAdd): Promise<{ data: BuildTypesAdd | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
// record.birthDate = toISOIfNotZ(record.birthDate || "");
|
||||
// record.expiryStarts = toISOIfNotZ(record.expiryStarts || "");
|
||||
// record.expiryEnds = toISOIfNotZ(record.expiryEnds || "");
|
||||
try {
|
||||
const res = await fetch('/api/build-types/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 }
|
||||
};
|
||||
|
||||
export function useAddBuildTypesMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data }: { data: BuildTypesAdd }) => fetchGraphQlBuildTypesAdd(data),
|
||||
onSuccess: () => { console.log("Build Types created successfully") },
|
||||
onError: (error) => { console.error("Create build types failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildTypesAddSchema = z.object({
|
||||
type: z.string(),
|
||||
token: z.string(),
|
||||
typeToken: z.string(),
|
||||
description: z.string(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type BuildTypesAdd = z.infer<typeof buildTypesAddSchema>;
|
||||
|
|
@ -0,0 +1,250 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
// function TableCellViewer({ item }: { item: schemaType }) {
|
||||
// const isMobile = useIsMobile();
|
||||
|
||||
// return (
|
||||
// <Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
// <DrawerTrigger asChild>
|
||||
// <Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
// {item.email ?? "Unknown Email"}
|
||||
// </Button>
|
||||
// </DrawerTrigger>
|
||||
|
||||
// <DrawerContent>
|
||||
// <DrawerHeader className="gap-1">
|
||||
// <h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
// <p className="text-sm text-muted-foreground">
|
||||
// User details
|
||||
// </p>
|
||||
// </DrawerHeader>
|
||||
|
||||
// <div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
// {/* BASIC INFO */}
|
||||
// <div className="grid grid-cols-2 gap-4">
|
||||
// <div>
|
||||
// <Label>Email</Label>
|
||||
// <Input value={item.email ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Phone</Label>
|
||||
// <Input value={item.phone ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Tag</Label>
|
||||
// <Input value={item.tag ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Active</Label>
|
||||
// <Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
// </div>
|
||||
// </div>
|
||||
|
||||
// <Separator />
|
||||
|
||||
// {/* DATES */}
|
||||
// <div className="grid grid-cols-2 gap-4">
|
||||
// <div>
|
||||
// <Label>Created At</Label>
|
||||
// <Input
|
||||
// value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
// readOnly
|
||||
// />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Updated At</Label>
|
||||
// <Input
|
||||
// value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
// readOnly
|
||||
// />
|
||||
// </div>
|
||||
// </div>
|
||||
|
||||
// <Separator />
|
||||
|
||||
// {/* TOKENS */}
|
||||
// <DropdownMenu>
|
||||
// <DropdownMenuTrigger asChild>
|
||||
// <Button variant="outline" className="w-full">
|
||||
// Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
// </Button>
|
||||
// </DropdownMenuTrigger>
|
||||
|
||||
// <DropdownMenuContent className="w-72">
|
||||
// <DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
// <DropdownMenuSeparator />
|
||||
// {(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
// {(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
// <DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
// <div className="grid grid-cols-2 gap-2 w-full">
|
||||
// <Input value={t.prefix} readOnly />
|
||||
// <Input value={t.token} readOnly />
|
||||
// </div>
|
||||
// </DropdownMenuItem>
|
||||
// ))}
|
||||
// </DropdownMenuContent>
|
||||
// </DropdownMenu>
|
||||
|
||||
// </div>
|
||||
|
||||
// <DrawerFooter>
|
||||
// <DrawerClose asChild>
|
||||
// <Button variant="outline">Close</Button>
|
||||
// </DrawerClose>
|
||||
// </DrawerFooter>
|
||||
// </DrawerContent>
|
||||
// </Drawer>
|
||||
// );
|
||||
// }
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "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-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/people/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,287 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
|
||||
export function BuildTypesDataTableAdd({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1);
|
||||
onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => {
|
||||
const newSize = Number(value);
|
||||
onPageSizeChange(newSize);
|
||||
onPageChange(1);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-types") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Build Types</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
firstName: z.string().optional(),
|
||||
surname: z.string().optional(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string().optional(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string().optional(),
|
||||
nationalIdentityId: z.string().optional(),
|
||||
birthPlace: z.string().optional(),
|
||||
birthDate: z.string().optional(),
|
||||
taxNo: z.string().optional(),
|
||||
birthname: z.string().optional(),
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
|
||||
interface BuildTypesAdd {
|
||||
|
||||
type: string;
|
||||
token: string;
|
||||
typeToken: string;
|
||||
description: string;
|
||||
expiryStarts?: string;
|
||||
expiryEnds?: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
export type { BuildTypesAdd };
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): 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: "type",
|
||||
header: "Type",
|
||||
},
|
||||
{
|
||||
accessorKey: "token",
|
||||
header: "Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "typeToken",
|
||||
header: "Type Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: "Description",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/build-types/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,270 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
IconPlus,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDeleteBuildTypeMutation } from "../queries"
|
||||
|
||||
export function BuildTypesDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteBuildTypeMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-types/add") }}>
|
||||
<IconPlus />
|
||||
<span className="hidden lg:inline">Add Build Type</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline" className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6">
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string(),
|
||||
type: z.string(),
|
||||
token: z.string(),
|
||||
typeToken: z.string(),
|
||||
description: z.string(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client';
|
||||
import { BuildTypesDataTable } from './list/data-table';
|
||||
import { useGraphQlBuildTypesList } from './queries';
|
||||
import { useState } from 'react';
|
||||
|
||||
const PageBuildTypes = () => {
|
||||
|
||||
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 } = useGraphQlBuildTypesList({ 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 <BuildTypesDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
|
||||
|
||||
};
|
||||
|
||||
export { PageBuildTypes };
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
'use client'
|
||||
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
|
||||
const fetchGraphQlBuildTypesList = 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/build-types/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ limit, skip, sort, filters }) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, totalCount: data.totalCount }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlDeleteBuildType = async (uuid: string): Promise<boolean> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/build-types/delete?uuid=${uuid}`, { method: 'GET', cache: 'no-store', credentials: "include" });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return data
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useGraphQlBuildTypesList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-build-types-list', params], queryFn: () => fetchGraphQlBuildTypesList(params) })
|
||||
}
|
||||
|
||||
export function useDeleteBuildTypeMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteBuildType(uuid),
|
||||
onSuccess: () => { console.log("Build type deleted successfully") },
|
||||
onError: (error) => { console.error("Delete build type failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
|
||||
interface BuildType {
|
||||
type: string;
|
||||
token: string;
|
||||
typeToken: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export type { BuildType }
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
"use client"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
import { useUpdateBuildTypesMutation } from "@/pages/build-types/update/queries"
|
||||
import { buildTypesUpdateSchema, type BuildTypesUpdate } from "@/pages/build-types/update/schema"
|
||||
|
||||
const BuildTypesForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: BuildTypesUpdate, selectedUuid: string }) => {
|
||||
|
||||
const form = useForm<BuildTypesUpdate>({ resolver: zodResolver(buildTypesUpdateSchema), defaultValues: { ...initData } })
|
||||
|
||||
const { handleSubmit } = form
|
||||
|
||||
const mutation = useUpdateBuildTypesMutation();
|
||||
|
||||
function onSubmit(values: BuildTypesUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 400) }
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
{/* TYPE + TOKEN */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Type..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Token..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* TYPE TOKEN + DESCRIPTION */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="typeToken"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Type Token..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Description..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* EXPIRY STARTS + ENDS */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Update Build Type
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
export { BuildTypesForm }
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlBuildTypesList } from '@/pages/build-types/queries';
|
||||
import { BuildTypesDataTableUpdate } from '@/pages/build-types/update/table/data-table';
|
||||
import { BuildTypesForm } from '@/pages/build-types/update/form';
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
const PageUpdateBuildTypes = () => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const uuid = searchParams?.get('uuid') || null
|
||||
const backToBuildTypes = <>
|
||||
<div>UUID not found in search params</div>
|
||||
<Button onClick={() => router.push('/build-types')}>Back to Build Types</Button>
|
||||
</>
|
||||
if (!uuid) { return backToBuildTypes }
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||
const initData = data?.data?.[0] || null;
|
||||
if (!initData) { return backToBuildTypes }
|
||||
return (
|
||||
<>
|
||||
<BuildTypesDataTableUpdate
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildTypesForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageUpdateBuildTypes };
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { BuildTypesUpdate } from './types';
|
||||
|
||||
const fetchGraphQlBuildTypesUpdate = async (record: BuildTypesUpdate, uuid: string): Promise<{ data: BuildTypesUpdate | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/build-types/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 useUpdateBuildTypesMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data, uuid }: { data: BuildTypesUpdate, uuid: string }) => fetchGraphQlBuildTypesUpdate(data, uuid),
|
||||
onSuccess: () => { console.log("Build Types updated successfully") },
|
||||
onError: (error) => { console.error("Update build types failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const buildTypesUpdateSchema = z.object({
|
||||
type: z.string(),
|
||||
token: z.string(),
|
||||
typeToken: z.string(),
|
||||
description: z.string(),
|
||||
expiryStarts: z.string(),
|
||||
expiryEnds: z.string(),
|
||||
});
|
||||
|
||||
export type BuildTypesUpdate = z.infer<typeof buildTypesUpdateSchema>;
|
||||
|
|
@ -0,0 +1,206 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function TableCellViewer({ item }: { item: schemaType }) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return (
|
||||
<Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
{item.email ?? "Unknown Email"}
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="gap-1">
|
||||
<h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
User details
|
||||
</p>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<Input value={item.email ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Phone</Label>
|
||||
<Input value={item.phone ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Tag</Label>
|
||||
<Input value={item.tag ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Active</Label>
|
||||
<Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Created At</Label>
|
||||
<Input
|
||||
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Updated At</Label>
|
||||
<Input
|
||||
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* TOKENS */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full">
|
||||
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 w-full">
|
||||
<Input value={t.prefix} readOnly />
|
||||
<Input value={t.token} readOnly />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: "Type",
|
||||
},
|
||||
{
|
||||
accessorKey: "token",
|
||||
header: "Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "typeToken",
|
||||
header: "Type Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: "Description",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/build-types/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,280 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeletePersonMutation } from "@/pages/people/queries"
|
||||
|
||||
export function BuildTypesDataTableUpdate({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeletePersonMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1);
|
||||
onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="outline" className="w-full flex-col justify-start gap-6">
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/build-types") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Build Types</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
isConfirmed: z.boolean().nullable().optional(),
|
||||
deleted: z.boolean().nullable().optional(),
|
||||
active: z.boolean().nullable().optional(),
|
||||
crypUuId: z.string().nullable().optional(),
|
||||
createdCredentialsToken: z.string().nullable().optional(),
|
||||
updatedCredentialsToken: z.string().nullable().optional(),
|
||||
confirmedCredentialsToken: z.string().nullable().optional(),
|
||||
isNotificationSend: z.boolean().nullable().optional(),
|
||||
isEmailSend: z.boolean().nullable().optional(),
|
||||
refInt: z.number().nullable().optional(),
|
||||
refId: z.string().nullable().optional(),
|
||||
replicationId: z.number().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
resetToken: z.string().nullable().optional(),
|
||||
password: z.string().nullable().optional(),
|
||||
history: z.array(z.string()).optional(),
|
||||
tag: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
|
||||
collectionTokens: z
|
||||
.object({
|
||||
default: z.string().nullable().optional(),
|
||||
tokens: z
|
||||
.array(
|
||||
z.object({
|
||||
prefix: z.string(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
|
||||
interface BuildTypesUpdate {
|
||||
type: string;
|
||||
token: string;
|
||||
typeToken: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
|
||||
export type { BuildTypesUpdate };
|
||||
|
|
@ -0,0 +1,250 @@
|
|||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
// function TableCellViewer({ item }: { item: schemaType }) {
|
||||
// const isMobile = useIsMobile();
|
||||
|
||||
// return (
|
||||
// <Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
// <DrawerTrigger asChild>
|
||||
// <Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
// {item.email ?? "Unknown Email"}
|
||||
// </Button>
|
||||
// </DrawerTrigger>
|
||||
|
||||
// <DrawerContent>
|
||||
// <DrawerHeader className="gap-1">
|
||||
// <h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
// <p className="text-sm text-muted-foreground">
|
||||
// User details
|
||||
// </p>
|
||||
// </DrawerHeader>
|
||||
|
||||
// <div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
// {/* BASIC INFO */}
|
||||
// <div className="grid grid-cols-2 gap-4">
|
||||
// <div>
|
||||
// <Label>Email</Label>
|
||||
// <Input value={item.email ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Phone</Label>
|
||||
// <Input value={item.phone ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Tag</Label>
|
||||
// <Input value={item.tag ?? ""} readOnly />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Active</Label>
|
||||
// <Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
// </div>
|
||||
// </div>
|
||||
|
||||
// <Separator />
|
||||
|
||||
// {/* DATES */}
|
||||
// <div className="grid grid-cols-2 gap-4">
|
||||
// <div>
|
||||
// <Label>Created At</Label>
|
||||
// <Input
|
||||
// value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
// readOnly
|
||||
// />
|
||||
// </div>
|
||||
|
||||
// <div>
|
||||
// <Label>Updated At</Label>
|
||||
// <Input
|
||||
// value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
// readOnly
|
||||
// />
|
||||
// </div>
|
||||
// </div>
|
||||
|
||||
// <Separator />
|
||||
|
||||
// {/* TOKENS */}
|
||||
// <DropdownMenu>
|
||||
// <DropdownMenuTrigger asChild>
|
||||
// <Button variant="outline" className="w-full">
|
||||
// Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
// </Button>
|
||||
// </DropdownMenuTrigger>
|
||||
|
||||
// <DropdownMenuContent className="w-72">
|
||||
// <DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
// <DropdownMenuSeparator />
|
||||
// {(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
// {(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
// <DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
// <div className="grid grid-cols-2 gap-2 w-full">
|
||||
// <Input value={t.prefix} readOnly />
|
||||
// <Input value={t.token} readOnly />
|
||||
// </div>
|
||||
// </DropdownMenuItem>
|
||||
// ))}
|
||||
// </DropdownMenuContent>
|
||||
// </DropdownMenu>
|
||||
|
||||
// </div>
|
||||
|
||||
// <DrawerFooter>
|
||||
// <DrawerClose asChild>
|
||||
// <Button variant="outline">Close</Button>
|
||||
// </DrawerClose>
|
||||
// </DrawerFooter>
|
||||
// </DrawerContent>
|
||||
// </Drawer>
|
||||
// );
|
||||
// }
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "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-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/people/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
|
|
@ -0,0 +1,280 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
IconPlus,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
|
||||
export function BuildDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/people/add") }}>
|
||||
<IconPlus />
|
||||
<span className="hidden lg:inline">Add Person</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,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>;
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
'use client';
|
||||
import { useGraphQlBuildsList } from './queries';
|
||||
import { useState } from 'react';
|
||||
import { BuildDataTable } from '@/pages/builds/list/data-table';
|
||||
|
||||
const PageBuilds = () => {
|
||||
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 } = useGraphQlBuildsList({ 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 <BuildDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
|
||||
|
||||
};
|
||||
|
||||
export { PageBuilds };
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
'use client'
|
||||
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
|
||||
const fetchGraphQlBuildsList = 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/list', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ limit, skip, sort, filters }) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, totalCount: data.totalCount }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlDeleteBuild = async (uuid: string): Promise<boolean> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/builds/delete?uuid=${uuid}`, { method: 'GET', cache: 'no-store', credentials: "include" });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return data
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useGraphQlBuildsList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-builds-list', params], queryFn: () => fetchGraphQlBuildsList(params) })
|
||||
}
|
||||
|
||||
export function useDeleteBuildMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteBuild(uuid),
|
||||
onSuccess: () => { console.log("Person deleted successfully") },
|
||||
onError: (error) => { console.error("Delete person failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
interface Build {
|
||||
buildType: string;
|
||||
collectionToken: string;
|
||||
info: BuildInfo;
|
||||
site?: string;
|
||||
address?: string;
|
||||
areas?: string[];
|
||||
ibans?: BuildIban[];
|
||||
responsibles?: BuildResponsible[];
|
||||
}
|
||||
|
||||
interface BuildInfo {
|
||||
govAddressCode: string;
|
||||
buildName: string;
|
||||
buildNo: string;
|
||||
maxFloor: number;
|
||||
undergroundFloor: number;
|
||||
buildDate: Date;
|
||||
decisionPeriodDate: Date;
|
||||
taxNo: string;
|
||||
liftCount: number;
|
||||
heatingSystem: boolean;
|
||||
coolingSystem: boolean;
|
||||
hotWaterSystem: boolean;
|
||||
blockServiceManCount: number;
|
||||
securityServiceManCount: number;
|
||||
garageCount: number;
|
||||
managementRoomId: number;
|
||||
}
|
||||
|
||||
interface BuildIban {
|
||||
iban: string;
|
||||
startDate: Date;
|
||||
stopDate: Date;
|
||||
bankCode: string;
|
||||
xcomment: string;
|
||||
}
|
||||
|
||||
interface BuildResponsible {
|
||||
company: string;
|
||||
person: string;
|
||||
}
|
||||
|
||||
export type { Build, BuildInfo, BuildIban, BuildResponsible }
|
||||
|
|
@ -0,0 +1,309 @@
|
|||
"use client"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { PeopleAdd, personAddSchema } from "./schema"
|
||||
import { useAddPeopleMutation } from "./queries"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
|
||||
const PeopleForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
|
||||
const form = useForm<PeopleAdd>({
|
||||
resolver: zodResolver(personAddSchema),
|
||||
defaultValues: {
|
||||
firstName: "",
|
||||
surname: "",
|
||||
middleName: "",
|
||||
sexCode: "",
|
||||
personRef: "",
|
||||
personTag: "",
|
||||
fatherName: "",
|
||||
motherName: "",
|
||||
countryCode: "",
|
||||
nationalIdentityId: "",
|
||||
birthPlace: "",
|
||||
birthDate: "",
|
||||
taxNo: "",
|
||||
birthname: "",
|
||||
expiryStarts: "",
|
||||
expiryEnds: "",
|
||||
},
|
||||
});
|
||||
|
||||
const { handleSubmit } = form;
|
||||
|
||||
const mutation = useAddPeopleMutation();
|
||||
|
||||
function onSubmit(values: PeopleAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="firstName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>First Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="John" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="surname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Surname</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Doe" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* SECOND ROW */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="middleName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Middle Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Alexander" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="sexCode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Sex Code</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="M / F" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* THIRD ROW */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="personRef"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Person Ref</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="REF123" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="personTag"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Person Tag</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="TAG001" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* FAMILY INFO */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="fatherName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Father Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Father..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="motherName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Mother Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Mother..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* COUNTRY + NATIONAL ID */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="countryCode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Country Code</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="TR" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="nationalIdentityId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>National Identity ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="12345678901" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* BIRTH INFO */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="birthPlace"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Birth Place</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Istanbul" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="birthDate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Birth Date</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* TAX/BIRTHNAME */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="taxNo"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Tax No</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Tax number..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="birthname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Birth Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Birth name..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* EXPIRY DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">Create Person</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export { PeopleForm }
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlPeopleList } from '@/pages/people/queries';
|
||||
import { PeopleDataTableAdd } from '@/pages/people/add/table/data-table';
|
||||
import { PeopleForm } from '@/pages/people/add/form';
|
||||
|
||||
const PageAddPerson = () => {
|
||||
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 });
|
||||
|
||||
return (
|
||||
<>
|
||||
<PeopleDataTableAdd
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<PeopleForm refetchTable={refetch} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageAddPerson };
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { PeopleAdd } from './types'
|
||||
import { toISOIfNotZ } from '@/lib/utils';
|
||||
|
||||
const fetchGraphQlPeopleAdd = async (record: PeopleAdd): Promise<{ data: PeopleAdd | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
record.birthDate = toISOIfNotZ(record.birthDate || "");
|
||||
record.expiryStarts = toISOIfNotZ(record.expiryStarts || "");
|
||||
record.expiryEnds = toISOIfNotZ(record.expiryEnds || "");
|
||||
try {
|
||||
const res = await fetch('/api/people/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 }
|
||||
};
|
||||
|
||||
export function useAddPeopleMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data }: { data: PeopleAdd }) => fetchGraphQlPeopleAdd(data),
|
||||
onSuccess: () => { console.log("People created successfully") },
|
||||
onError: (error) => { console.error("Create people failed:", error) },
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { z } from "zod"
|
||||
|
||||
export const personAddSchema = z.object({
|
||||
firstName: z.string(),
|
||||
surname: z.string(),
|
||||
middleName: z.string().optional(),
|
||||
sexCode: z.string(),
|
||||
personRef: z.string().optional(),
|
||||
personTag: z.string().optional(),
|
||||
fatherName: z.string().optional(),
|
||||
motherName: z.string().optional(),
|
||||
countryCode: z.string(),
|
||||
nationalIdentityId: z.string(),
|
||||
birthPlace: z.string(),
|
||||
birthDate: z.string(),
|
||||
taxNo: z.string().optional(),
|
||||
birthname: z.string().optional(),
|
||||
expiryStarts: z.string(),
|
||||
expiryEnds: z.string(),
|
||||
});
|
||||
|
||||
export type PeopleAdd = z.infer<typeof personAddSchema>;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue