forked from Yara724/api
99 lines
2.6 KiB
TypeScript
99 lines
2.6 KiB
TypeScript
import { Injectable } from "@nestjs/common";
|
|
import { InjectModel } from "@nestjs/mongoose";
|
|
import { FilterQuery, Model, Types } from "mongoose";
|
|
import { BranchModel, BranchDocument } from "../schema/branch.schema";
|
|
|
|
@Injectable()
|
|
export class BranchDbService {
|
|
constructor(
|
|
@InjectModel(BranchModel.name)
|
|
private readonly branchModel: Model<BranchModel>,
|
|
) {}
|
|
|
|
async create(branch: BranchModel): Promise<BranchModel> {
|
|
return await this.branchModel.create(branch);
|
|
}
|
|
|
|
async find(branch: FilterQuery<BranchModel>): Promise<BranchDocument> {
|
|
return await this.branchModel.findOne(branch);
|
|
}
|
|
|
|
async findOne(branch: FilterQuery<BranchModel>) {
|
|
return this.branchModel.findOne(branch);
|
|
}
|
|
|
|
async findAll(insuranceId: string): Promise<BranchModel[]> {
|
|
return await this.branchModel.find({
|
|
clientKey: new Types.ObjectId(insuranceId),
|
|
});
|
|
}
|
|
|
|
async findAllWithFilters(
|
|
insuranceId: string,
|
|
opts?: {
|
|
search?: string;
|
|
from?: Date;
|
|
to?: Date;
|
|
isActive?: boolean;
|
|
},
|
|
): Promise<BranchModel[]> {
|
|
const filter: any = { clientKey: new Types.ObjectId(insuranceId) };
|
|
|
|
if (typeof opts?.isActive === "boolean") {
|
|
filter.isActive = opts.isActive;
|
|
}
|
|
|
|
if (opts?.from || opts?.to) {
|
|
filter.$or = [
|
|
{
|
|
createdAt: {
|
|
...(opts.from ? { $gte: opts.from } : {}),
|
|
...(opts.to ? { $lte: opts.to } : {}),
|
|
},
|
|
},
|
|
{
|
|
activityStartDate: {
|
|
...(opts.from ? { $gte: opts.from } : {}),
|
|
...(opts.to ? { $lte: opts.to } : {}),
|
|
},
|
|
},
|
|
];
|
|
}
|
|
|
|
if (opts?.search?.trim()) {
|
|
const q = opts.search.trim();
|
|
const rx = new RegExp(q, "i");
|
|
filter.$and = [
|
|
...(filter.$and || []),
|
|
{
|
|
$or: [
|
|
{ name: rx },
|
|
{ code: rx },
|
|
{ city: rx },
|
|
{ state: rx },
|
|
{ address: rx },
|
|
{ phoneNumber: rx },
|
|
],
|
|
},
|
|
];
|
|
}
|
|
|
|
return this.branchModel.find(filter).lean();
|
|
}
|
|
|
|
async findByIds(ids: Types.ObjectId[]) {
|
|
return this.branchModel
|
|
.find({ _id: { $in: ids } })
|
|
.select({ _id: 1, name: 1, code: 1, city: 1, state: 1, address: 1, phoneNumber: 1, isActive: 1, activityStartDate: 1, createdAt: 1, updatedAt: 1 })
|
|
.lean();
|
|
}
|
|
|
|
async findByIdAndUpdate(id: string, update: any): Promise<BranchModel | null> {
|
|
return this.branchModel.findByIdAndUpdate(id, update, { new: true }).lean();
|
|
}
|
|
|
|
async findById(id: string): Promise<BranchModel | null> {
|
|
return this.branchModel.findById(id).lean();
|
|
}
|
|
}
|