block.service.ts 4.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * * **Current State:** `BlockService` imports and initializes `PhaseRepository` to perform cross-entity validation checking if a `Phase` exists before creating or updating a `Block`.
  3. * * **Intended Mutation:** Remove `PhaseRepository` from imports, properties, `getRepos()`, `create()`, and `update()` methods to unbind Phase and Block entities.
  4. * * **Risk Mitigation:** Cross-entity validation is entirely shifted to the `FFB Production` ledger level, making the master block seeder 100% independent.
  5. */
  6. import { Injectable, NotFoundException, Inject, forwardRef } from '@nestjs/common';
  7. import { FFBLangChainService } from '../../FFB/services/ffb-langchain.service';
  8. import { MongoCoreService } from '../../mongo/mongo-core.service';
  9. import { BlockRepository } from '../repositories/block.repository';
  10. import { Block } from '../schemas/site.schema';
  11. import { FFBProductionService } from '../../FFB/services/ffb-production.service';
  12. @Injectable()
  13. export class BlockService {
  14. private repo: BlockRepository;
  15. constructor(
  16. private readonly mongoCore: MongoCoreService,
  17. @Inject(forwardRef(() => FFBProductionService))
  18. private readonly ffbService: FFBProductionService,
  19. @Inject(forwardRef(() => FFBLangChainService))
  20. private readonly ffbLangChainService: FFBLangChainService,
  21. ) { }
  22. private async getRepos() {
  23. if (!this.repo) {
  24. const db = await this.mongoCore.getDb();
  25. this.repo = new BlockRepository(db);
  26. await this.repo.init();
  27. }
  28. return { repo: this.repo };
  29. }
  30. async create(block: Block): Promise<Block> {
  31. const { repo } = await this.getRepos();
  32. return repo.create(block);
  33. }
  34. async findAll(filter: Record<string, any> = {}): Promise<Block[]> {
  35. const { repo } = await this.getRepos();
  36. return repo.findAll(filter);
  37. }
  38. async findById(id: string): Promise<Block | null> {
  39. const { repo } = await this.getRepos();
  40. return repo.findById(id);
  41. }
  42. async update(id: string, update: Partial<Block>): Promise<void> {
  43. const { repo } = await this.getRepos();
  44. const block = await repo.findById(id);
  45. if (!block) throw new NotFoundException('Block not found');
  46. await repo.update(id, update);
  47. }
  48. async delete(id: string): Promise<void> {
  49. const { repo } = await this.getRepos();
  50. const block = await repo.findById(id);
  51. if (!block) throw new NotFoundException('Block not found');
  52. // Cascading Delete:
  53. // 1. Delete all FFB Production records referencing this block
  54. await this.ffbService.deleteMany({ blockCode: block.blockCode });
  55. // 2. Delete the block itself
  56. await repo.delete(id);
  57. }
  58. async generateDescription(data: { name: string, phaseName?: string, size?: number, numOfTrees?: number }): Promise<{ description: string }> {
  59. const prompt = `Write a realistic, professional description (2–4 sentences) for an oil palm plantation block named "${data.name}"${data.phaseName ? ` within phase "${data.phaseName}"` : ''}.${data.size ? ` It has a size of ${data.size} units` : ''}${data.numOfTrees ? ` and contains ${data.numOfTrees} trees` : ''}.
  60. Choose 1-2 aspects from the following to incorporate naturally:
  61. - Block health and maturity (e.g., trees at peak production age, healthy canopy development, consistent fruit set)
  62. - Field accessibility (e.g., easily accessible by tractor paths, slightly sloped area requiring specialized harvesting tools)
  63. - Environmental features (e.g., bordering primary forest, presence of natural irrigation channels, rich nutrient-holding soil)
  64. - Monitoring and care (e.g., subject to intensive pest monitoring, recently fertilized, under strict irrigation schedule)
  65. Guidelines:
  66. - Maintain a grounded, operational tone.
  67. - Do not mention the bullet points explicitly; weave them into the narrative.
  68. - Ensure the length is exactly 2-4 sentences.
  69. Description:`;
  70. const description = await this.ffbLangChainService.chatStateless(prompt);
  71. return { description: description.replace(/^Description:\s*/i, '').trim() };
  72. }
  73. }