jws-backend/src/controllers/branch/contact-controller.ts

108 lines
2.8 KiB
TypeScript
Raw Normal View History

2024-04-02 13:54:49 +07:00
import {
Body,
Controller,
Delete,
Get,
Patch,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import prisma from "../../db";
import minio from "../../services/minio";
import HttpError from "../../interfaces/http-error";
import HttpStatus from "../../interfaces/http-status";
import { RequestWithUser } from "../../interfaces/user";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
2024-04-02 14:08:07 +07:00
type BranchContactCreate = {
lineId: string;
telephoneNo: string;
};
type BranchContactUpdate = {
lineId?: string;
telephoneNo?: string;
};
function imageLocation(id: string) {
return `branch/contact-${id}`;
}
2024-04-02 13:54:49 +07:00
@Route("api/branch/{branchId}/contact")
@Tags("Branch Contact")
@Security("keycloak")
export class BranchContactController extends Controller {
2024-04-02 13:55:54 +07:00
@Post()
async createBranchContact(
@Request() req: RequestWithUser,
@Path() branchId: string,
@Body() body: BranchContactCreate,
) {
if (!(await prisma.branch.findFirst({ where: { id: branchId } }))) {
throw new HttpError(HttpStatus.BAD_REQUEST, "Branch not found.");
}
const record = await prisma.branchContact.create({
include: { branch: true },
data: { ...body, branchId, createdBy: req.user.name, updateBy: req.user.name },
});
return Object.assign(record, {
qrCodeImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,
imageLocation(record.id),
2024-04-02 13:55:54 +07:00
12 * 60 * 60,
),
qrCodeImageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
imageLocation(record.id),
2024-04-02 13:55:54 +07:00
12 * 60 * 60,
),
});
}
2024-04-02 13:56:40 +07:00
2024-04-02 15:21:19 +07:00
@Patch("{contactId}")
async editBranchContact(
@Request() req: RequestWithUser,
@Body() body: BranchContactUpdate,
@Path() branchId: string,
@Path() contactId: string,
) {
const record = await prisma.branchContact.update({
include: { branch: true },
data: { ...body, updateBy: req.user.name },
where: { id: contactId, branchId },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.");
}
return Object.assign(record, {
qrCodeImageUrl: await minio.presignedGetObject(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
qrCodeImageUploadUrl: await minio.presignedPutObject(
MINIO_BUCKET,
imageLocation(record.id),
12 * 60 * 60,
),
});
}
2024-04-02 13:56:40 +07:00
@Delete("{contactId}")
async deleteBranchContact(@Path() branchId: string, @Path() contactId: string) {
const result = await prisma.branchContact.deleteMany({ where: { id: contactId, branchId } });
if (result.count <= 0) throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.");
}
2024-04-02 13:54:49 +07:00
}