All files / lastwill lastwill.service.ts

98.24% Statements 56/57
82.05% Branches 32/39
100% Functions 6/6
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1422x                 2x 2x 2x     2x                   2x 2x   2x 2x             3x   1x 1x             6x 6x   6x 6x   5x 5x   5x 1x 1x         4x       5x 4x 3x     2x       5x 4x 3x     2x         1x 1x 1x               1x         1x           1x                 1x 1x 1x 2x   1x               1x 1x 1x 2x   1x         1x 1x      
import {
  ForbiddenException,
  Injectable,
  Logger,
  NotFoundException,
  UnauthorizedException,
} from '@nestjs/common'
import { ObjectId } from 'mongoose'
import { LastWill } from '../db/entities/lastwill.entity'
import { LastWillDBService } from '../db/services/lastwill.service'
import { UserDBService } from '../db/services/user.service'
import { paymentPlans } from '../payments/interfaces/payments'
import { CreateLastWillDto } from './dto/create-lastwill.dto'
import { GeneratedLastWillDTO } from './dto/generated-lastwill.dto'
import {
  generateFinancialInheritancePragraphs,
  generateInitialText,
  generateItemInheritanceParagraph,
  generateLocationHeader,
  generateTestatorHeader,
  getLegalClauses,
} from './utilities/lastwill-templating.util'
 
@Injectable()
export class LastWillService {
  private readonly logger = new Logger(LastWillService.name)
  constructor(
    private readonly userService: UserDBService,
    private readonly lastwillDbService: LastWillDBService,
  ) {}
 
  async getFullTextLastWill(
    id: string,
    userId: ObjectId,
  ): Promise<GeneratedLastWillDTO> {
    const lastWill = await this.lastwillDbService.findFullById(id, userId)
 
    Iif (!lastWill) throw new NotFoundException()
    return this.generateLastWillFullText(lastWill)
  }
 
  async createLastWill(
    createLastWillDto: CreateLastWillDto,
    userId: ObjectId,
  ): Promise<LastWill> {
    this.logger.log(`Creating new Lastwill for user`)
    const lastWillCount = await this.lastwillDbService.countDocuments(userId)
 
    const user = await this.userService.findOneById(userId)
    if (!user) throw new UnauthorizedException('Only Existing users can create')
 
    const plan = user.paymentPlan
    const allowedWills = Math.abs(paymentPlans[plan])
 
    if (lastWillCount >= allowedWills) {
      this.logger.log(`Last will creation exceeding plan limits was attempted`)
      throw new ForbiddenException(
        `Exceeding allowed last wills: ${allowedWills}`,
      )
    }
 
    return await this.lastwillDbService.createOne(createLastWillDto, userId)
  }
 
  includesFinancialInheritance(lastWill: LastWill): boolean {
    if (lastWill.financialAssets.length === 0) return false
    for (const heir of lastWill.heirs) {
      if (heir.percentage) return true
    }
    // False because noone actually inherits anything
    return false
  }
 
  includesItemInheritance(lastWill: LastWill): boolean {
    if (lastWill.items.length === 0) return false
    for (const heir of lastWill.heirs) {
      if (heir.itemIds?.length > 0) return true
    }
    // false bc noone actually inherits anything
    return false
  }
 
  private generateLastWillFullText(lastWill: LastWill): GeneratedLastWillDTO {
    // 1. Set headers
    const testator = lastWill.testator
    const testatorAddress = testator.address
    const testatorHeader = generateTestatorHeader(
      testator.name,
      testatorAddress?.street,
      testatorAddress?.houseNumber,
      testatorAddress?.city,
      testatorAddress?.zipCode,
    )
 
    const locationHeader = generateLocationHeader(
      lastWill.testator.address?.city,
    )
 
    // Generate outer text
    const initialText = generateInitialText(
      testator.name,
      testator.birthDate,
      testator.birthPlace,
    )
 
    const generatedLastWill: GeneratedLastWillDTO = {
      testatorHeader,
      locationHeader,
      title: 'Mein letzter Wille',
      initialText,
      paragraphs: [],
    }
 
    // Generate Erbeinsetzung
    if (this.includesFinancialInheritance(lastWill)) {
      const financialHeirs = []
      for (const heir of lastWill.heirs) {
        if (heir.percentage) financialHeirs.push(heir)
      }
      generatedLastWill.paragraphs.push(
        ...generateFinancialInheritancePragraphs(
          financialHeirs,
          lastWill.financialAssets,
        ),
      )
    }
 
    if (this.includesItemInheritance(lastWill)) {
      const itemHeirs = []
      for (const heir of lastWill.heirs) {
        if (heir.itemIds?.length > 0) itemHeirs.push(heir)
      }
      generatedLastWill.paragraphs.push(
        generateItemInheritanceParagraph(itemHeirs, lastWill.items),
      )
    }
 
    generatedLastWill.paragraphs.push(...getLegalClauses())
    return generatedLastWill
  }
}