UNPKG

@tmlmobilidade/interfaces

Version:

This package provides SDK-style connectors for interacting with databases (e.g., stops, plans, rides, alerts) and external providers (e.g., authentication, storage). It simplifies data access and integration across projects.

86 lines (85 loc) 3.35 kB
/* * */ import { MongoCollectionClass } from '../../common/mongo-collection.js'; import { HTTP_STATUS, HttpException } from '@tmlmobilidade/consts'; import { Dates } from '@tmlmobilidade/dates'; import { CreateRideAcceptanceSchema, UpdateRideAcceptanceSchema } from '@tmlmobilidade/types'; import { asyncSingletonProxy, compareObjects, flattenObject } from '@tmlmobilidade/utils'; /* * */ class RideAcceptanceClass extends MongoCollectionClass { static _instance; createSchema = CreateRideAcceptanceSchema; updateSchema = UpdateRideAcceptanceSchema; constructor() { super(); } static async getInstance() { if (!RideAcceptanceClass._instance) { const instance = new RideAcceptanceClass(); await instance.connect(); RideAcceptanceClass._instance = instance; } return RideAcceptanceClass._instance; } async createByRideId(ride_id, data, options = {}) { const currentTimestamp = Dates.now('utc').unix_timestamp; const createdBy = data.created_by || 'system'; data.comments.push({ created_at: currentTimestamp, created_by: createdBy, message: 'Ride acceptance created', type: 'note', updated_at: currentTimestamp, }); data.comments.push({ created_at: currentTimestamp, created_by: createdBy, curr_value: data.analysis_summary, field: 'analysis_summary', prev_value: null, type: 'field_changed', updated_at: currentTimestamp, }); return super.insertOne({ ...data, ride_id }, { options }); } async findByRideId(ride_id) { return super.findOne({ ride_id }); } async updateByRideId(ride_id, data, options = {}) { const prevAcceptance = await this.findByRideId(ride_id); if (!prevAcceptance) { throw new HttpException(HTTP_STATUS.NOT_FOUND, 'Ride acceptance not found'); } const diff = compareObjects(prevAcceptance, data); const flattenedDiff = flattenObject(diff); data.comments = data.comments || prevAcceptance.comments || []; for (const key of Object.keys(flattenedDiff)) { if (key === 'is_locked' || key === 'acceptance_status' || key === 'justification' || key === 'analysis_summary') { data.comments.push({ created_at: Dates.now('utc').unix_timestamp, created_by: data.updated_by || 'system', curr_value: data[key], field: key, prev_value: prevAcceptance[key], type: 'field_changed', updated_at: Dates.now('utc').unix_timestamp, updated_by: data.updated_by || 'system', }); } } return super.updateOne({ ride_id }, data, options); } getCollectionIndexes() { return [ { background: true, key: { ride_id: 1 } }, { background: true, key: { acceptance_status: 1 } }, ]; } getCollectionName() { return 'ride_acceptances'; } getEnvName() { return 'DATABASE_URI'; } } /* * */ export const rideAcceptances = asyncSingletonProxy(RideAcceptanceClass);