import { CheckInService, EndUser, ReferenceType, RelationTypeEnum, UserService, WitnessCustomerAssetResponse, } from '@bit-ui-libs/common'; import { format, isValid } from 'date-fns'; import { RelatedEventData } from '../interfaces'; interface GetRelatedEventsOpts { childEvents: WitnessCustomerAssetResponse[]; relationType: RelationTypeEnum; checkInService: CheckInService; userService: UserService; } export async function getRelatedEvents(opts: GetRelatedEventsOpts) { const relatedEvents: RelatedEventData[] = []; const specificRelatedEvents = opts.childEvents.filter((e) => e.relationType === opts.relationType); for (const childEvent of specificRelatedEvents) { try { const event = await opts.checkInService.getEvent(childEvent.eventIdRef); const userId = event.subjectReferences.find((sr) => sr.type === ReferenceType.END_USER_ID)?.value; const eventDate = event.eventDate && isValid(new Date(event.eventDate)) ? format(new Date(event.eventDate), 'MM-dd-yyyy') : ''; let userInfo: EndUser | null = null; if (userId) userInfo = await opts.userService.getUser(userId); relatedEvents.push({ userInfo: userInfo!, attachments: event.attachments, eventDate, properties: event?.properties, type: childEvent.relationType as RelationTypeEnum, approved: childEvent.approved, checkInEventId: childEvent.eventIdRef, }); } catch (err) { continue; } } return relatedEvents; }