import { computed, inject, resource } from "@angular/core";
import { isEqual } from "lodash-es";
import { EntityMapperService } from "../../entity/entity-mapper/entity-mapper.service";
import { Entity } from "../../entity/model/entity";
import { WithinParentConfig } from "../../common-components/entity-form/dynamic-form-validators/form-validator-config";
import { asArray } from "app/utils/asArray";
import { DateRangeValue } from "./date-range.datatype";
import { isOutsideRange } from "./is-outside-range";
import { loadLinkedRecords } from "../entity/load-linked-records";
/** the range of a linked parent record (see {@link WithinParentConfig}) */
export interface ParentRange {
name: string;
range: DateRangeValue;
}
/**
* The ids of the parent records to compare a record's range with.
* None for an anonymized record, whose dates are reduced to the year.
*
* @param record the record, with the current values of its form while it is edited
* (see `createCurrentRecordState`), so that a changed link is followed before it is saved
*/
export function getParentIds(
config: WithinParentConfig,
record: Entity | undefined,
): string[] {
if (record?.anonymized) {
return [];
}
return asArray(record?.[config.parentReferenceField] ?? []);
}
/**
* Loads the ranges of the given parent records
* (except anonymized ones, whose dates are reduced to the year, and the ones that cannot be loaded).
*/
export async function loadParentRanges(
entityMapper: EntityMapperService,
parentIds: string[],
valueField: string,
): Promise<ParentRange[]> {
const parents = await loadLinkedRecords(entityMapper, parentIds);
return parents
.filter((parent) => !parent.anonymized)
.map((parent) => ({
name: parent.toString(),
range: parent[valueField],
}));
}
/**
* Loads the ranges of the parent records that a record links to (see {@link getParentIds} and {@link loadParentRanges}).
* Must be called in an injection context (e.g. as a field initializer of a component).
*
* @param params the record (with the current values of its form while it is edited),
* the id and the `withinParent` config of its field (without a config nothing is loaded)
*/
export function parentRangesResource(
params: () => {
record: Entity | undefined;
fieldId: string | undefined;
config: WithinParentConfig | undefined;
},
) {
const entityMapper = inject(EntityMapperService);
return resource({
params: computed(
() => {
const { record, fieldId, config } = params();
const parentIds = config ? getParentIds(config, record) : [];
return parentIds.length
? { parentIds, valueField: config.parentValueField ?? fieldId }
: undefined;
},
// the record is copied on every change of its form: only load again when the parents change
{ equal: isEqual },
),
loader: ({ params: { parentIds, valueField } }) =>
loadParentRanges(entityMapper, parentIds, valueField),
});
}
/** name of the first parent whose range the given range goes beyond */
export function findParentOutside(
range: DateRangeValue | null | undefined,
parents: ParentRange[] | undefined,
): string | undefined {
return parents?.find((parent) => isOutsideRange(range, parent.range))?.name;
}