Skip to content

Commit

Permalink
feat: able to transfer vehicle to business
Browse files Browse the repository at this point in the history
  • Loading branch information
casperiv0 committed Oct 6, 2023
1 parent 13e8271 commit 8462a8f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 16 deletions.
57 changes: 42 additions & 15 deletions apps/api/src/controllers/citizen/vehicles-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { getLastOfArray, manyToManyHelper } from "lib/data/many-to-many";
import { AllowedFileExtension, allowedFileExtensions } from "@snailycad/config";
import { getImageWebPPath } from "~/lib/images/get-image-webp-path";
import fs from "node:fs/promises";
import { ExtendedNotFound } from "~/exceptions/extended-not-found";

@Controller("/vehicles")
@UseBeforeEach(IsAuth)
Expand Down Expand Up @@ -484,25 +485,51 @@ export class VehiclesController {
throw new NotFound("vehicleNotFound");
}

const newOwner = await prisma.citizen.findFirst({
where: {
AND: [{ id: data.ownerId }, { NOT: { id: String(vehicle.citizenId) } }],
},
});
if (data.businessId) {
const business = await prisma.business.findUnique({
where: { id: data.businessId },
});

if (!newOwner) {
throw new NotFound("newOwnerNotFound");
if (!business) {
throw new ExtendedNotFound({ business: "businessNotFound" });
}

const updatedVehicle = await prisma.registeredVehicle.update({
where: { id: vehicle.id },
data: {
Business: { connect: { id: data.businessId } },
},
});

return updatedVehicle;
}

const updatedVehicle = await prisma.registeredVehicle.update({
where: { id: vehicle.id },
data: {
citizenId: newOwner.id,
userId: newOwner.userId,
},
});
if (data.ownerId) {
const newOwner = await prisma.citizen.findFirst({
where: {
AND: [{ id: data.ownerId }, { NOT: { id: String(vehicle.citizenId) } }],
},
});

return updatedVehicle;
if (!newOwner) {
throw new NotFound("newOwnerNotFound");
}

const updatedVehicle = await prisma.registeredVehicle.update({
where: { id: vehicle.id },
data: {
citizenId: newOwner.id,
userId: newOwner.userId,
},
});

return updatedVehicle;
}

throw new ExtendedBadRequest({
ownerId: "ownerIdOrBusinessIdRequired",
businessId: "ownerIdOrBusinessIdRequired",
});
}

@Delete("/:id")
Expand Down
3 changes: 2 additions & 1 deletion packages/schemas/src/citizen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ export const VEHICLE_SCHEMA = z.object({
});

export const TRANSFER_VEHICLE_SCHEMA = z.object({
ownerId: z.string().min(2).max(255),
ownerId: z.string().max(255).nullish(),
businessId: z.string().max(255).nullish(),
});

export const DELETE_VEHICLE_SCHEMA = z.object({
Expand Down

0 comments on commit 8462a8f

Please sign in to comment.