import { Component, Input, OnInit } from '@angular/core'; import { Validators } from '@angular/forms'; import { SpinnerService } from '@core/services/spinner.service'; import { TimeZoneService } from '@core/services/time-zone.service'; import { APIAdminClient } from '@core/typings/api/admin-client.typing'; import { APIDataImport } from '@core/typings/api/data-import.typing'; import { ApplicantsImportModel, ApplicationFormsImportModel, ApplicationsImportModel, ApplicationsInKindImportModel, AwardsImportModel, AwardsInKindImportModel, EmployeeApplicantInfoModel, FormFieldResponse, HistoricalDataImportModel, HistoricalDataImportModelInstance, OrganizationsImportModel, PaymentsImportModel, PaymentsInKindImportModel } from '@core/typings/data-import.typing'; import { ProcessingTypes } from '@core/typings/payment.typing'; import { PaymentStatus } from '@core/typings/status.typing'; import { AdminClientService } from '@features/platform-admin/clients/admin-client.service'; import { FileService, InflectService, IsString, OrganizedError, TypeaheadSelectOption, TypeSafeFormBuilder, TypeSafeFormGroup, YcFile } from '@yourcause/common'; import { AnalyticsService, EventType } from '@yourcause/common/analytics'; import { I18nService } from '@yourcause/common/i18n'; import { YCModalComponent } from '@yourcause/common/modals'; import { ClassType } from 'class-transformer/ClassTransformer'; import { HistoricalImportService } from '../historical-import.service'; interface AddFileToBatchResponse { fileType: APIDataImport.DataImportFileType; paymentBatchName: string; file: YcFile|string; ancillaryFile: string; timezone: string; } interface BatchFormGroup { fileType: ClassType&{ FileType: APIDataImport.DataImportFileType; }; program: APIAdminClient.GrantProgramSummaryResponse; form: APIAdminClient.GrantProgramForm; jsonFile: any; paymentBatchName: string; timezone: string; } @Component({ selector: 'gc-add-file-to-batch-modal', templateUrl: './add-file-to-batch-modal.component.html', styleUrls: ['./add-file-to-batch-modal.component.scss'] }) export class AddFileToBatchModalComponent extends YCModalComponent< AddFileToBatchResponse > implements OnInit { @Input() initialModel: ClassType&{ FileType: APIDataImport.DataImportFileType; }; DataImportFileType = APIDataImport.DataImportFileType; ValidationClass: ClassType&{ FileType: APIDataImport.DataImportFileType; }; selectedFile: Blob; importValid = false; selectOptions: TypeaheadSelectOption>[] = [{ value: ApplicationsInKindImportModel, label: this.i18n.translate( 'common:hdrInKindAmountRequested', {}, 'In kind amount requested' ) }, { value: AwardsInKindImportModel, label: this.i18n.translate( 'common:hdrInKindItemsAwarded', {}, 'In kind items awarded' ) }, { value: PaymentsInKindImportModel, label: this.i18n.translate( 'common:hdrInKindItemsPaid', {}, 'In kind items paid' ) }, { value: ApplicantsImportModel, label: this.i18n.translate( 'common:lblApplicants', {}, 'Applicants' ) }, { value: ApplicationsImportModel, label: this.i18n.translate( 'common:hdrApplications', {}, 'Applications' ) }, { value: ApplicationFormsImportModel, label: this.i18n.translate( 'GLOBAL:textApplicationForms', {}, 'Application Forms' ) }, { value: AwardsImportModel, label: this.i18n.translate( 'common:hdrAwards', {}, 'Awards' ) }, { value: OrganizationsImportModel, label: this.i18n.translate( 'common:lblOrganizations', {}, 'Organizations' ) }, { value: PaymentsImportModel, label: this.i18n.translate( 'common:hdrPayments', {}, 'Payments' ) }, { value: EmployeeApplicantInfoModel, label: this.i18n.translate( 'common:hdrEmployeeApplicantInfo', {}, 'Employee Applicant Info' ) }, { value: FormFieldResponse, label: this.i18n.translate( 'common:hdrFormResponses', {}, 'Form Responses' ) }]; model: ClassType&{ FileType: APIDataImport.DataImportFileType }; formGroup: TypeSafeFormGroup; selectedProgram: APIAdminClient.GrantProgramSummaryResponse; selectedForm: APIAdminClient.GrantProgramForm; formApplicable = false; columns: string[]; columnKeys: string[]; rows: HistoricalDataImportModelInstance[]; PaymentsImportModel = PaymentsImportModel; PaymentsInKindImportModel = PaymentsInKindImportModel; hasErrors: boolean; errors: OrganizedError[]; filteredErrorMap: { row: number; errors: { [x: string]: string; }; }[]; programOptions: TypeaheadSelectOption[] = []; forms: TypeaheadSelectOption[] = []; timezoneOptions = this.timezoneService.getTimezoneOptions(); constructor ( private adminClientService: AdminClientService, private i18n: I18nService, private inflect: InflectService, private formBuilder: TypeSafeFormBuilder, private historicalImportsService: HistoricalImportService, private fileService: FileService, private spinnerService: SpinnerService, private timezoneService: TimeZoneService, private analyticsService: AnalyticsService ) { super(); } ngOnInit () { const client = this.adminClientService.activeClient; this.programOptions = this.adminClientService.clientPrograms[ client.clientId ].map((program) => { return { label: program.grantProgramName, value: program }; }); this.formGroup = this.formBuilder.group({ fileType: [this.initialModel], program: null, form: null, jsonFile: null, paymentBatchName: null, timezone: client?.defaultTimezone || 'UTC' }); this.handleTypeChange(this.initialModel); } async programChanged (newProgram: APIAdminClient.GrantProgramSummaryResponse) { if (this.selectedProgram !== newProgram) { this.spinnerService.startSpinner(); this.rows = null; this.selectedProgram = newProgram; const forms = await this.adminClientService.fetchClientProgramDetails( newProgram.grantProgramId ); this.forms = forms.map(form => ({ label: form.formName, value: form })); this.setColumns(); this.spinnerService.stopSpinner(); } } formChanged (newForm: APIAdminClient.GrantProgramForm) { if (this.selectedForm !== newForm) { this.rows = null; this.selectedForm = newForm; this.setColumns(); } } handleErrorsChange (errors: OrganizedError[]) { this.errors = errors; } handleTypeChange ( newModel: ClassType&{FileType: APIDataImport.DataImportFileType} ) { if (newModel !== this.model) { this.rows = null; this.model = newModel; this.errors = []; if (newModel === ApplicationFormsImportModel) { this.formApplicable = true; } else { this.formApplicable = false; this.selectedProgram = null; this.selectedForm = null; this.forms = []; } this.setColumns(); this.formGroup.setValue({ fileType: newModel, program: null, form: null, jsonFile: null, paymentBatchName: null, timezone: this.formGroup.value.timezone }); } this.ValidationClass = newModel; } private setColumns () { this.columns = this.historicalImportsService.getAttrs( this.model, this.selectedForm ); // if importing into an application form, we need to create a new dynamic class and add the form columns if (this.isApplicationFormImport(this.rows) && this.selectedForm) { const newClass = class extends ApplicationFormsImportModel { }; const formColumns = this.historicalImportsService.extractColumnsFromForm(this.selectedForm); formColumns.forEach((prop) => { IsString()(newClass.prototype, prop); }); // pass dynamic class to csv import comp so that it shows form columns in the table this.ValidationClass = newClass; } this.columnKeys = this.columns.map(attr => `historical:hdr${this.inflect.pascalize(attr)}`); } downloadErrors () { const csv = this.fileService.convertObjectArrayToCSVString(this.errors); this.fileService.downloadString(csv, 'text/csv', 'errors.csv'); this.analyticsService.emitEvent({ eventName: 'Download errors', eventType: EventType.Click, extras: null }); } downloadSample () { this.historicalImportsService.getSampleCSV(this.model, this.selectedForm); this.analyticsService.emitEvent({ eventName: 'Download sample CSV', eventType: EventType.Click, extras: null }); } isApplicationFormImport ( rows: HistoricalDataImportModelInstance[] ): rows is ApplicationFormsImportModel[] { return this.model === ApplicationFormsImportModel; } submit () { this.spinnerService.startSpinner(); const value = this.formGroup.value; const type: HistoricalDataImportModel = value.fileType as any; let file: string = this.fileService.convertObjectArrayToCSVString(this.rows); let ancillaryFile: string; const rows: HistoricalDataImportModelInstance[] = this.rows; if (this.isApplicationFormImport(rows)) { const result = this.historicalImportsService.mapApplicationForm( rows, this.selectedForm ); ancillaryFile = result.ancillaryFile; file = result.replacementFile; } this.spinnerService.stopSpinner(); this.closeModal.emit({ fileType: type.FileType, paymentBatchName: value.paymentBatchName, file, ancillaryFile, timezone: value.timezone }); this.analyticsService.emitEvent({ eventName: 'Add file to batch submit', eventType: EventType.Click, extras: null }); } handleContentsChange (contents: HistoricalDataImportModelInstance[]) { this.rows = contents; const fileType = this.formGroup.value.fileType; if (fileType === this.PaymentsImportModel) { const budgetsAndSources = this.adminClientService.clientBudgetsMap[ this.adminClientService.activeClientId ]; const clientSources = budgetsAndSources.fundingSources; let requireBatchName = false; this.rows.forEach((row) => { /** * We require payment batch name if there are any rows where: * 1. Funding source is client processed AND * 2. Status is not pending */ const foundSource = clientSources.find((source) => { return +source.id === +(row as PaymentsImportModel).FundingSourceId; }); if ( foundSource?.processingTypeId === ProcessingTypes.Client && +(row as PaymentsImportModel).Status !== PaymentStatus.Pending ) { requireBatchName = true; } }); if (requireBatchName) { const control = this.formGroup.get('paymentBatchName'); control.setValidators([Validators.required]); if (!control.value) { control.markAsDirty(); control.setValue(''); } } else { this.unrequireBatchName(); } } else { this.unrequireBatchName(); } } unrequireBatchName () { const control = this.formGroup.get('paymentBatchName'); control.clearValidators(); control.updateValueAndValidity(); } handleUpdateValidation (valid: boolean) { this.importValid = valid; } }