This commit is contained in:
natib21
2026-06-29 15:28:04 +00:00
parent d94b73fe02
commit 04bc9eded6
7 changed files with 237 additions and 11 deletions

View File

@@ -0,0 +1,97 @@
import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { Freight } from '@edr/types';
import {
BillingService,
GenerateInvoiceInput,
InvoiceEventPayload,
} from '../billing/billing.service';
import { Invoice } from '../billing/entities/invoice.entity';
import { LastMileRepository } from './last-mile.repository';
import { LastMile } from './entities/last-mile.entity';
/**
* Owns the last-mile ⇄ invoice mapping — the one place that knows how a last-mile
* record turns into invoices, which type to use, and how it advances when paid.
* Last-mile records are billable business entities for delivery fees, so they
* generate their own invoices directly via {@link BillingService}. All last-mile-specific
* type branching lives here, at the two points it belongs: invoice creation and
* settlement (the paid handler).
*/
@Injectable()
export class LastMileInvoiceService {
private readonly logger = new Logger(LastMileInvoiceService.name);
constructor(
private readonly billing: BillingService,
private readonly lastMileRepo: LastMileRepository,
) {}
/**
* Ensure the last-mile record has its invoice, generating one from the
* remainingPayment if absent. Called when a last-mile record reaches a
* billable state. Idempotent — returns the existing open invoice instead
* of a duplicate. Returns `null` (and logs) when the record is not billable:
* no company to bill (invoices FK requires a companyId).
*/
async ensureInvoiceFor(record: LastMile): Promise<Invoice | null> {
// Check if invoice already exists
const existing = await this.billing.findPayable(
'last_mile' as Freight.InvoiceSource,
record.id,
'DELIVERY_FEE',
);
if (existing) return existing;
// Can't bill without company
const lm = record.booking ? record : (await this.lastMileRepo.findById(record.id, { relations: { booking: true } }));
if (!lm) return null;
if (!lm.booking?.companyId) {
this.logger.warn(
`Skipping invoice for last-mile record ${record.id}: no company to bill.`,
);
return null;
}
// Generate invoice with remainingPayment as totalAmount
const input: GenerateInvoiceInput = {
source: 'last_mile' as Freight.InvoiceSource,
sourceId: record.id,
type: 'DELIVERY_FEE',
companyId: lm.booking!.companyId,
companyProfileId: lm.booking!.companyProfileId || '',
currency: 'ETB',
lines: [
{
chargeType: 'DELIVERY',
description: 'Last-mile delivery',
quantity: 1,
unitRate: record.remainingPayment || 0,
amount: record.remainingPayment || 0,
},
],
totalAmount: record.remainingPayment || 0,
};
return this.billing.generateInvoice(input);
}
/**
* React to a last-mile invoice being paid — the settlement branch point.
* Advances the last-mile record to mark post-payment as completed.
*/
@OnEvent('last_mile.invoice.paid')
async onPaid(payload: InvoiceEventPayload): Promise<void> {
if (payload.type === 'DELIVERY_FEE') {
const record = await this.lastMileRepo.findById(payload.sourceId);
if (record) {
this.logger.log(`Last-mile invoice paid for record ${payload.sourceId}.`);
} else {
this.logger.warn(
`Cannot mark last-mile record ${payload.sourceId} as paid: not found.`,
);
}
}
}
}

View File

@@ -20,13 +20,17 @@ import { UpdateLastMileDto } from './dto/update-last-mile.dto';
import { AllocateLastMileContainersDto } from './dto/allocate-containers.dto';
import { LastMileStatus } from './entities/last-mile.entity';
import { LastMileService } from './last-mile.service';
import { LastMileInvoiceService } from './last-mile-invoice.service';
@ApiTags('last-mile')
@ApiBearerAuth()
@Controller('last-mile')
@TrainSchedulingView()
export class LastMileController {
constructor(private readonly lastMileService: LastMileService) {}
constructor(
private readonly lastMileService: LastMileService,
private readonly lastMileInvoiceService: LastMileInvoiceService,
) {}
@Get()
@ApiOperation({ summary: 'List last-mile legs' })
@@ -73,8 +77,13 @@ export class LastMileController {
@Patch(':id')
@TrainSchedulingManage()
@ApiOperation({ summary: 'Update a last-mile leg' })
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateLastMileDto) {
return this.lastMileService.update(id, dto);
async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateLastMileDto) {
const record = await this.lastMileService.update(id, dto);
// Auto-generate invoice if distance or payment was updated
if (dto.exactKm !== undefined || dto.remainingPayment !== undefined) {
await this.lastMileInvoiceService.ensureInvoiceFor(record);
}
return record;
}
@Delete(':id')

View File

@@ -1,6 +1,7 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { BillingModule } from '../billing/billing.module';
import { BookingsModule } from '../bookings/bookings.module';
import { DriversModule } from '../drivers/drivers.module';
import { NotificationsModule } from '../notifications/notifications.module';
@@ -8,19 +9,21 @@ import { VehiclesModule } from '../vehicles/vehicles.module';
import { LastMile } from './entities/last-mile.entity';
import { LastMileContainerAllocation } from './entities/last-mile-container-allocation.entity';
import { LastMileController } from './last-mile.controller';
import { LastMileInvoiceService } from './last-mile-invoice.service';
import { LastMileRepository } from './last-mile.repository';
import { LastMileService } from './last-mile.service';
@Module({
imports: [
TypeOrmModule.forFeature([LastMile, LastMileContainerAllocation]),
BillingModule,
forwardRef(() => BookingsModule),
VehiclesModule,
DriversModule,
NotificationsModule,
],
controllers: [LastMileController],
providers: [LastMileRepository, LastMileService],
exports: [LastMileRepository, LastMileService],
providers: [LastMileRepository, LastMileService, LastMileInvoiceService],
exports: [LastMileRepository, LastMileService, LastMileInvoiceService],
})
export class LastMileModule {}