| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262 |
- import { Component, inject } from '@angular/core';
- import {
- FormBuilder,
- FormGroup,
- FormControl,
- ReactiveFormsModule,
- Validators,
- } from '@angular/forms';
- import { OnInit } from '@angular/core';
- import { ActivatedRoute, Router, RouterLink } from '@angular/router';
- import { AppHeader } from '../../share/header/app-header';
- import { AppSideMenu } from '../../share/side-menu/app-side-menu';
- import { DankaService } from '../../services/dankaService';
- import { FamilyService } from '../../services/family-service';
- import { MarriageRelationService } from '../../services/marriage-relation-service';
- import { Danka } from '../../models/danka';
- import { Family } from '../../models/family';
- import { MarriageRelation } from '../../models/marriage-relation';
-
- @Component({
- selector: 'app-family-edit',
- imports: [AppHeader, AppSideMenu, ReactiveFormsModule],
- templateUrl: './family-edit.html',
- styleUrl: './family-edit.scss',
- })
- export class FamilyEdit implements OnInit {
- danka: Danka | undefined;
- family: Family | undefined;
- families: Family[] = [];
- dankaId: string = '';
- familyId: string | null = null;
- relationMode: string = '';
- baseFamilyId: string = '';
- marriageErrorMessages: string[] = [];
- private setHouseholderOnSave = false;
-
- constructor(
- private dankaService: DankaService,
- private familyService: FamilyService,
- private marriageRelationService: MarriageRelationService,
- private route: ActivatedRoute,
- private router: Router,
- ) {
- }
-
- ngOnInit(): void {
- this.init();
- }
-
- async init(): Promise<void> {
- this.dankaId = this.route.snapshot.params['dankaId'];
- this.familyId = this.route.snapshot.params['familyId'];
-
- this.relationMode = this.route.snapshot.queryParamMap.get('relationMode') ?? '';
- this.baseFamilyId = this.route.snapshot.queryParamMap.get('baseFamilyId') ?? '';
-
- // ★ここが重要
- this.danka = await this.dankaService.getDankaById(this.dankaId);
- this.families = await this.familyService.getFamiliesByDankaId(this.dankaId);
-
- if (this.familyId) {
- this.family = await this.familyService.getFamilyById(this.familyId);
-
- if (this.family) {
- this.familyForm.patchValue({
- furigana: this.family.furigana,
- name: this.family.name,
- relationship: this.family.relationship,
- birthDate: this.family.birthDate,
- note: this.family.note,
- fatherId: this.family.fatherId,
- motherId: this.family.motherId,
- spouseId: this.family.spouseId,
- gender: this.family.gender,
- });
-
- await this.patchMarriageRelationFields(this.family.id);
- }
- }
-
- if (!this.familyId && this.relationMode === 'spouse') {
- this.familyForm.patchValue({
- spouseId: this.baseFamilyId,
- marriageStatus: 'current',
- });
- }
-
- if (!this.familyId && this.relationMode === 'child') {
- const baseFamily = await this.familyService.getFamilyById(this.baseFamilyId);
-
- if (baseFamily?.gender === 'male') {
- this.familyForm.patchValue({
- fatherId: this.baseFamilyId,
- });
- }
-
- if (baseFamily?.gender === 'female') {
- this.familyForm.patchValue({
- motherId: this.baseFamilyId,
- });
- }
- }
- }
-
- familyForm = new FormGroup({
- furigana: new FormControl('', [Validators.required]),
- name: new FormControl('', [Validators.required]),
- relationship: new FormControl(''),
- birthDate: new FormControl('', Validators.required),
- note: new FormControl(''),
- fatherId: new FormControl(''),
- motherId: new FormControl(''),
- spouseId: new FormControl(''),
- marriageStatus: new FormControl<MarriageRelation['status']>('current'),
- gender: new FormControl('unknown'),
- });
-
- getAgeText() {
- const birthDate = this.familyForm.get('birthDate')?.value;
- if (!birthDate) {
- return '生年月日を入力すると自動計算されます';
- }
- const birth = new Date(birthDate);
- const today = new Date();
- let age = today.getFullYear() - birth.getFullYear();
- const thisYearsBirthday = new Date(today.getFullYear(), birth.getMonth(), birth.getDate());
-
- if (thisYearsBirthday > today) {
- age--;
- }
- return `${age}歳`;
- }
-
- getFamilyOptions(): Family[] {
- return this.families.filter((family) => family.id !== this.familyId);
- }
-
- async patchMarriageRelationFields(familyId: string): Promise<void> {
- const relations = await this.marriageRelationService.getMarriageRelationsByFamilyId(familyId);
-
- const relation =
- relations.find((marriageRelation) => marriageRelation.status === 'current') ?? relations[0];
-
- if (!relation) return;
-
- this.familyForm.patchValue({
- spouseId: relation.person1Id === familyId ? relation.person2Id : relation.person1Id,
- marriageStatus: relation.status,
- });
- }
-
- async findMarriageRelation(
- person1Id: string,
- person2Id: string
- ): Promise<MarriageRelation | undefined> {
-
- const relations = await this.marriageRelationService.getMarriageRelationsByFamilyId(person1Id);
-
- return relations.find(
- (relation) =>
- (relation.person1Id === person1Id && relation.person2Id === person2Id) ||
- (relation.person1Id === person2Id && relation.person2Id === person1Id),
- );
- }
-
- async saveFamily() {
- if (this.familyForm.invalid) {
- return;
- }
-
- this.marriageErrorMessages = [];
- const familyId = this.familyId ?? Date.now().toString();
- const dankaId = this.dankaId;
- const formValue = this.familyForm.value;
- const spouseId = formValue.spouseId ?? '';
- const marriageStatus = formValue.marriageStatus ?? 'current';
- const currentSpouseId = marriageStatus === 'current' ? spouseId : '';
- const updatedFamily = {
- id: familyId,
- dankaId: dankaId,
- furigana: formValue.furigana?.trim() ?? '',
- name: formValue.name?.trim() ?? '',
- relationship: formValue.relationship?.trim() ?? '',
- birthDate: formValue.birthDate?.trim() ?? '',
- note: formValue.note?.trim() ?? '',
- fatherId: this.familyForm.value.fatherId ?? '',
- motherId: this.familyForm.value.motherId ?? '',
- spouseId: currentSpouseId,
- gender: this.familyForm.value.gender ?? 'unknown',
- };
-
- if (spouseId) {
- const existingRelation = await this.findMarriageRelation(familyId, spouseId);
-
- const errors = await this.marriageRelationService.saveMarriageRelation({
- id: existingRelation?.id ?? crypto.randomUUID(),
- dankaId,
- person1Id: familyId,
- person2Id: spouseId,
- status: marriageStatus,
- startDate: existingRelation?.startDate ?? '',
- endDate: existingRelation?.endDate ?? '',
- note: existingRelation?.note ?? '',
- });
-
- if (errors.length > 0) {
- this.marriageErrorMessages = errors;
- return;
- }
- } else {
- const currentMarriage = await this.marriageRelationService.getCurrentMarriageByFamilyId(familyId);
- if (currentMarriage) {
- this.marriageRelationService.deleteMarriageRelation(currentMarriage.id);
- }
- }
-
- this.familyService.saveFamily(updatedFamily);
- this.saveHouseholderIfSelected(updatedFamily);
- this.router.navigate(['/danka-detail', dankaId], { queryParams: { tab: 'family' } });
- }
-
- cancelFamilyEdit(): void {
- const dankaId = this.dankaId;
- this.router.navigate(['/danka-detail', dankaId], { queryParams: { tab: 'family' } });
- }
-
- deleteFamily() {
- const dankaId = this.dankaId;
- if (!this.familyId) {
- return;
- }
- this.familyService.deleteFamily(this.familyId);
- this.router.navigate(['/danka-detail', dankaId], { queryParams: { tab: 'family' } });
- }
-
- setAsHouseholder(): void {
- this.setHouseholderOnSave = true;
- this.familyForm.patchValue({
- relationship: '施主',
- });
- }
-
- private saveHouseholderIfSelected(family: Family): void {
- if (!this.setHouseholderOnSave || !this.danka) {
- return;
- }
-
- this.dankaService.saveDanka({
- ...this.danka,
- householder: family.name,
- householderFurigana: family.furigana,
- updatedAt: this.formatDateForSave(new Date()),
- });
- }
-
- private formatDateForSave(date: Date): string {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
- }
- }
|