File size: 11,218 Bytes
964569f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | const { AppError } = require("../utils/appError");
const { withTransaction } = require("../db/transaction");
function normalizeTripStatus(raw) {
if (!raw) {
return null;
}
const value = String(raw).toUpperCase();
if (!["PLANNED", "IN_PROGRESS", "COMPLETED", "CANCELLED"].includes(value)) {
throw new AppError("status must be PLANNED, IN_PROGRESS, COMPLETED, or CANCELLED", 400);
}
return value;
}
function buildTripCode() {
const now = new Date();
const stamp = now
.toISOString()
.replace(/[-:]/g, "")
.replace(/\..*$/, "")
.replace("T", "");
const suffix = Math.random().toString(36).slice(2, 6).toUpperCase();
return `TRIP-${stamp}-${suffix}`;
}
function toLatLon(value) {
if (value === undefined || value === null || value === "") {
return null;
}
const parsed = Number(value);
if (!Number.isFinite(parsed)) {
throw new AppError("Invalid coordinate value", 400);
}
return parsed;
}
function normalizeCargoType(raw) {
return String(raw || "")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9]+/g, "_")
.replace(/^_+|_+$/g, "");
}
function createTripsService(deps) {
const {
pool,
tripsRepository,
assetRepository,
auditRepository,
alertsRepository,
tripSummaryAiService,
} = deps;
async function listTrips(query, context) {
const tenantCode = context?.tenantCode || null;
const status = normalizeTripStatus(query.status);
return tripsRepository.listTrips(pool, {
tenantCode,
status,
truckCode: query.truckCode || null,
containerCode: query.containerCode || null,
managerUserId: context?.managerUserId || null,
limit: Math.min(Number(query.limit) || 500, 2000),
});
}
async function createTrip(input, context) {
if (!input || typeof input !== "object") {
throw new AppError("Request body must be a JSON object", 400);
}
const tenantCode = (context?.tenantCode || input.tenantCode || "").toString().trim();
if (!tenantCode && !context?.isSuperAdmin) {
throw new AppError("tenantCode is required", 400);
}
const truckCode = String(input.truckCode || "").trim();
const containerCode = String(input.containerCode || "").trim();
const originName = String(input.originName || "").trim();
const destinationName = String(input.destinationName || "").trim();
const cargoTypeInput = String(input.cargoType || "").trim();
const goodsDescription = String(input.goodsDescription || "").trim();
if (!truckCode || !containerCode) {
throw new AppError("truckCode and containerCode are required", 400);
}
if (!originName || !destinationName) {
throw new AppError("originName and destinationName are required", 400);
}
if (!cargoTypeInput) {
throw new AppError("cargoType is required", 400);
}
const cargoProfile = tripSummaryAiService?.resolveCargoProfile
? tripSummaryAiService.resolveCargoProfile(cargoTypeInput)
: {
code: normalizeCargoType(cargoTypeInput) || "GENERAL_CARGO",
label: cargoTypeInput,
prioritySignals: ["temperature", "humidity", "gas", "shock", "gps_fix"],
};
const originLat = toLatLon(input.originLat);
const originLon = toLatLon(input.originLon);
const destinationLat = toLatLon(input.destinationLat);
const destinationLon = toLatLon(input.destinationLon);
const plannedStartAt = input.plannedStartAt ? new Date(input.plannedStartAt).toISOString() : null;
const plannedEndAt = input.plannedEndAt ? new Date(input.plannedEndAt).toISOString() : null;
const tripCode = input.tripCode ? String(input.tripCode).trim() : buildTripCode();
return withTransaction(pool, async (client) => {
const contextRow = await assetRepository.resolveAssetContextByCodes(client, {
tenantCode,
truckCode,
containerCode,
});
if (!contextRow) {
throw new AppError("Truck/container mapping not found", 404);
}
if (context?.managerUserId) {
const assignment = await tripsRepository.getActiveManagerAssignment(client, {
tenantId: contextRow.tenant_id,
containerId: contextRow.container_id,
managerUserId: context.managerUserId,
});
if (!assignment) {
throw new AppError("Container is not assigned to this fleet manager", 403);
}
}
const activeTrip = await tripsRepository.getActiveTripByAsset(client, {
tenantId: contextRow.tenant_id,
truckId: contextRow.truck_id,
containerId: contextRow.container_id,
});
if (activeTrip) {
throw new AppError("An active trip already exists for this truck/container", 409);
}
let created;
try {
created = await tripsRepository.createTrip(client, {
tenantId: contextRow.tenant_id,
tripCode,
fleetId: contextRow.fleet_id,
truckId: contextRow.truck_id,
containerId: contextRow.container_id,
routeId: null,
originName,
destinationName,
plannedStartAt,
plannedEndAt,
status: "PLANNED",
metadata: {
origin: {
name: originName,
lat: originLat,
lon: originLon,
},
destination: {
name: destinationName,
lat: destinationLat,
lon: destinationLon,
},
cargo: {
cargoType: cargoProfile.code,
cargoLabel: cargoProfile.label,
goodsDescription: goodsDescription || null,
prioritySignals: cargoProfile.prioritySignals,
},
},
});
} catch (error) {
if (error && error.code === "23505") {
throw new AppError("Trip code already exists", 409);
}
throw error;
}
if (auditRepository) {
await auditRepository.insertAuditLog(client, {
tenantId: contextRow.tenant_id,
actorUserId: context?.actorUserId || null,
action: "TRIP_CREATE",
targetType: "trip",
targetId: created.id,
metadata: {
tripCode,
truckCode,
containerCode,
originName,
destinationName,
cargoType: cargoProfile.code,
goodsDescription: goodsDescription || null,
},
ipAddress: context?.ipAddress || null,
userAgent: context?.userAgent || null,
});
}
return created;
});
}
async function startTrip(tripId, context) {
if (!tripId) {
throw new AppError("tripId is required", 400);
}
const tenantCode = (context?.tenantCode || context?.tenantCodeOverride || "")
.toString()
.trim();
if (!tenantCode && !context?.isSuperAdmin) {
throw new AppError("tenantCode is required", 400);
}
return withTransaction(pool, async (client) => {
const existing = await tripsRepository.getTripById(client, {
tripId,
tenantCode,
managerUserId: context?.managerUserId || null,
});
if (!existing) {
throw new AppError("Trip not found", 404);
}
if (existing.status !== "PLANNED") {
throw new AppError("Trip cannot be started from current status", 409);
}
const updated = await tripsRepository.startTrip(client, {
tripId,
tenantId: existing.tenant_id,
});
if (!updated) {
throw new AppError("Trip not found", 404);
}
if (auditRepository) {
await auditRepository.insertAuditLog(client, {
tenantId: existing.tenant_id,
actorUserId: context?.actorUserId || null,
action: "TRIP_START",
targetType: "trip",
targetId: existing.id,
metadata: {
tripCode: existing.trip_code,
},
ipAddress: context?.ipAddress || null,
userAgent: context?.userAgent || null,
});
}
return updated;
});
}
async function completeTrip(tripId, context) {
if (!tripId) {
throw new AppError("tripId is required", 400);
}
const tenantCode = (context?.tenantCode || context?.tenantCodeOverride || "")
.toString()
.trim();
if (!tenantCode && !context?.isSuperAdmin) {
throw new AppError("tenantCode is required", 400);
}
return withTransaction(pool, async (client) => {
const existing = await tripsRepository.getTripById(client, {
tripId,
tenantCode,
managerUserId: context?.managerUserId || null,
});
if (!existing) {
throw new AppError("Trip not found", 404);
}
if (existing.status !== "IN_PROGRESS") {
throw new AppError("Trip cannot be completed from current status", 409);
}
const updated = await tripsRepository.completeTrip(client, {
tripId,
tenantId: existing.tenant_id,
});
if (!updated) {
throw new AppError("Trip not found", 404);
}
const metadata =
existing.metadata_json && typeof existing.metadata_json === "object"
? existing.metadata_json
: {};
const cargo = metadata.cargo || {
cargoType: "GENERAL_CARGO",
cargoLabel: "General cargo",
goodsDescription: null,
prioritySignals: ["temperature", "humidity", "gas", "shock", "gps_fix"],
};
const metrics = await tripsRepository.getTripTelemetryAggregate(client, {
tenantId: existing.tenant_id,
tripId: existing.id,
});
const alertSummary = alertsRepository
? await alertsRepository.getAlertSummaryByTrip(client, {
tenantId: existing.tenant_id,
tripId: existing.id,
})
: { count: 0, bySeverity: {} };
let finalTrip = updated;
if (tripSummaryAiService?.generateTripSummary) {
const aiSummary = await tripSummaryAiService.generateTripSummary({
cargoType: cargo.cargoType,
goodsDescription: cargo.goodsDescription || null,
metrics,
alertSummary,
});
const patched = await tripsRepository.updateTripMetadata(client, {
tripId: existing.id,
tenantId: existing.tenant_id,
patch: {
aiSummary,
cargo,
},
});
if (patched) {
finalTrip = patched;
}
}
if (auditRepository) {
await auditRepository.insertAuditLog(client, {
tenantId: existing.tenant_id,
actorUserId: context?.actorUserId || null,
action: "TRIP_COMPLETE",
targetType: "trip",
targetId: existing.id,
metadata: {
tripCode: existing.trip_code,
cargoType: cargo.cargoType,
},
ipAddress: context?.ipAddress || null,
userAgent: context?.userAgent || null,
});
}
return finalTrip;
});
}
return {
listTrips,
createTrip,
startTrip,
completeTrip,
};
}
module.exports = {
createTripsService,
};
|