Skip to content

Commit

Permalink
[ACS-5857] reverted moment migration for DateWidget and DateCloudWidget
Browse files Browse the repository at this point in the history
  • Loading branch information
SheenaMalhotra182 committed Oct 9, 2023
1 parent 2cc6f6c commit 27dbd03
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 145 deletions.
2 changes: 1 addition & 1 deletion lib/core/src/lib/common/utils/date-fns-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export class DateFnsUtils {
/**
* Parses a date string using the specified date format.
*
* @param value - The date string to parse.
* @param date - The date string to parse.
* @param dateFormat - The date format string to use for parsing.
* @returns The parsed Date object.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

/* eslint-disable @angular-eslint/component-selector */

import moment from 'moment';
import { FormFieldTypes } from './form-field-types';
import { isNumberValue } from './form-field-utils';
import { FormFieldModel } from './form-field.model';
Expand Down Expand Up @@ -148,8 +149,8 @@ export class DateFieldValidator implements FormFieldValidator {
// Validates that the input string is a valid date formatted as <dateFormat> (default D-M-YYYY)
static isValidDate(inputDate: string, dateFormat: string = 'D-M-YYYY'): boolean {
if (inputDate) {
const date = DateFnsUtils.parseDate(inputDate, dateFormat);
return isValid(date);
const d = moment(inputDate, dateFormat, true);
return d.isValid();
}

return false;
Expand All @@ -164,7 +165,7 @@ export class DateFieldValidator implements FormFieldValidator {
if (DateFieldValidator.isValidDate(field.value, field.dateDisplayFormat)) {
return true;
}
field.validationSummary.message = DateFnsUtils.convertDateFnsToMomentFormat(field.dateDisplayFormat);
field.validationSummary.message = field.dateDisplayFormat;
return false;
}
return true;
Expand Down Expand Up @@ -211,8 +212,8 @@ export class DateTimeFieldValidator implements FormFieldValidator {

export abstract class BoundaryDateFieldValidator implements FormFieldValidator {

DATE_FORMAT_CLOUD = 'yyyy-MM-dd';
DATE_FORMAT = 'dd-MM-yyyy';
DATE_FORMAT_CLOUD = 'YYYY-MM-DD';
DATE_FORMAT = 'DD-MM-YYYY';

supportedTypes = [
FormFieldTypes.DATE
Expand Down Expand Up @@ -251,17 +252,17 @@ export class MinDateFieldValidator extends BoundaryDateFieldValidator {
// remove time and timezone info
let fieldValueData;
if (typeof field.value === 'string') {
fieldValueData = DateFnsUtils.parseDate(field.value.split('T')[0], dateFormat);
fieldValueData = moment(field.value.split('T')[0], dateFormat);
} else {
fieldValueData = field.value;
}

const minValueDateFormat = this.extractDateFormat(field.minValue);
const min = DateFnsUtils.parseDate(field.minValue, minValueDateFormat);
const min = moment(field.minValue, minValueDateFormat);

if (isBefore(fieldValueData, min)) {
if (fieldValueData.isBefore(min)) {
field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_LESS_THAN`;
field.validationSummary.attributes.set('minValue', DateFnsUtils.formatDate(min, field.dateDisplayFormat).toLocaleUpperCase());
field.validationSummary.attributes.set('minValue', min.format(field.dateDisplayFormat).toLocaleUpperCase());
isFieldValid = false;
}
return isFieldValid;
Expand All @@ -281,17 +282,17 @@ export class MaxDateFieldValidator extends BoundaryDateFieldValidator {
// remove time and timezone info
let fieldValueData;
if (typeof field.value === 'string') {
fieldValueData = DateFnsUtils.parseDate(field.value.split('T')[0], dateFormat);
fieldValueData = moment(field.value.split('T')[0], dateFormat);
} else {
fieldValueData = field.value;
}

const maxValueDateFormat = this.extractDateFormat(field.maxValue);
const max = DateFnsUtils.parseDate(field.maxValue, maxValueDateFormat);
const max = moment(field.maxValue, maxValueDateFormat);

if (isAfter(fieldValueData, max)) {
if (fieldValueData.isAfter(max)) {
field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_GREATER_THAN`;
field.validationSummary.attributes.set('maxValue', DateFnsUtils.formatDate(max, field.dateDisplayFormat).toLocaleUpperCase());
field.validationSummary.attributes.set('maxValue', max.format(field.dateDisplayFormat).toLocaleUpperCase());
isFieldValid = false;
}
return isFieldValid;
Expand Down Expand Up @@ -320,7 +321,7 @@ export class MinDateTimeFieldValidator implements FormFieldValidator {
if (this.isSupported(field) && field.value && field.isVisible) {
const dateFormat = field.dateDisplayFormat;

if (!DateFieldValidator.isValidDate(field.value, dateFormat)) {
if (!DateTimeFieldValidator.isValidDate(field.value, dateFormat)) {
field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE';
isFieldValid = false;
} else {
Expand Down Expand Up @@ -366,7 +367,7 @@ export class MaxDateTimeFieldValidator implements FormFieldValidator {
if (this.isSupported(field) && field.value && field.isVisible) {
const dateFormat = field.dateDisplayFormat;

if (!DateFieldValidator.isValidDate(field.value, dateFormat)) {
if (!DateTimeFieldValidator.isValidDate(field.value, dateFormat)) {
field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE';
isFieldValid = false;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import moment from 'moment';
import { FormFieldTypes } from './form-field-types';
import { FormFieldModel } from './form-field.model';
import { FormModel } from './form.model';
Expand Down Expand Up @@ -273,9 +274,9 @@ describe('FormFieldModel', () => {
dateDisplayFormat: 'DD-MM-YYYY'
});

const currentDate = new Date();
const expectedDate = DateFnsUtils.formatDate(currentDate, 'DD-MM-YYYY');
const expectedDateFormat = `${DateFnsUtils.formatDate(currentDate, 'YYYY-MM-DD')}T00:00:00.000Z`;
const currentDate = moment(new Date());
const expectedDate = moment(currentDate).format('DD-MM-YYYY');
const expectedDateFormat = `${currentDate.format('YYYY-MM-DD')}T00:00:00.000Z`;

expect(field.value).toBe(expectedDate);
expect(form.values['ddmmyyy']).toEqual(expectedDateFormat);
Expand Down
26 changes: 8 additions & 18 deletions lib/core/src/lib/form/components/widgets/core/form-field.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

/* eslint-disable @angular-eslint/component-selector */
import moment from 'moment';
import { WidgetVisibilityModel } from '../../../models/widget-visibility.model';
import { ContainerColumnModel } from './container-column.model';
import { ErrorMessageModel } from './error-message.model';
Expand All @@ -39,7 +40,7 @@ export class FormFieldModel extends FormWidgetModel {
private _isValid: boolean = true;
private _required: boolean = false;

readonly defaultDateFormat: string = 'd-M-yyyy';
readonly defaultDateFormat: string = 'D-M-YYYY';
readonly defaultDateTimeFormat: string = 'd-M-yyyy hh:mm a';

// model members
Expand Down Expand Up @@ -190,7 +191,7 @@ export class FormFieldModel extends FormWidgetModel {
this.visibilityCondition = json.visibilityCondition ? new WidgetVisibilityModel(json.visibilityCondition) : undefined;
this.enableFractions = json.enableFractions;
this.currency = json.currency;
this.dateDisplayFormat = DateFnsUtils.convertMomentToDateFnsFormat(json.dateDisplayFormat) || this.getDefaultDateFormat(json);
this.dateDisplayFormat = json.dateDisplayFormat || this.getDefaultDateFormat(json);
this._value = this.parseValue(json);
this.validationSummary = new ErrorMessageModel();
this.tooltip = json.tooltip;
Expand Down Expand Up @@ -241,22 +242,11 @@ export class FormFieldModel extends FormWidgetModel {
}

private getDefaultDateFormat(jsonField: any): string {
if (jsonField.fields) {
Object.keys(jsonField.fields).forEach((el) => {
if (jsonField.fields[el]) {
jsonField.fields[el].forEach((element) => {
element.dateDisplayFormat = element.dateDisplayFormat
? DateFnsUtils.convertMomentToDateFnsFormat(element.dateDisplayFormat)
: element.dateDisplayFormat;
});
}
});
}
let originalType = jsonField.type;
if (FormFieldTypes.isReadOnlyType(jsonField.type) && jsonField.params && jsonField.params.field) {
originalType = jsonField.params.field.type;
}
return originalType === FormFieldTypes.DATETIME ? this.defaultDateTimeFormat : this.defaultDateFormat;
return originalType === FormFieldTypes.DATETIME ? DateFnsUtils.convertMomentToDateFnsFormat(this.defaultDateTimeFormat) : this.defaultDateFormat;
}

private isTypeaheadFieldType(type: string): boolean {
Expand Down Expand Up @@ -366,12 +356,12 @@ export class FormFieldModel extends FormWidgetModel {
if (value) {
let dateValue;
if (isNumberValue(value)) {
dateValue = new Date(value);
dateValue = moment(value);
} else {
dateValue = DateFnsUtils.parseDate(value.split('T')[0], 'YYYY-M-D');
dateValue = moment.utc(value.split('T')[0], 'YYYY-M-D');
}
if (isValid(dateValue)) {
value = DateFnsUtils.formatDate(dateValue, this.dateDisplayFormat);
if (dateValue?.isValid()) {
value = dateValue.utc().format(this.dateDisplayFormat);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class DateTimeWidgetComponent extends WidgetComponent implements OnInit,
private onDestroy$ = new Subject<boolean>();

constructor(public formService: FormService,
private dateAdapter: DateAdapter<DateFnsAdapter>,
private dateAdapter: DateAdapter<Date>,
private userPreferencesService: UserPreferencesService,
@Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats,
private translationService: TranslationService) {
Expand Down
27 changes: 5 additions & 22 deletions lib/core/src/lib/form/components/widgets/date/date.widget.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
*/

import { ComponentFixture, TestBed } from '@angular/core/testing';
import moment from 'moment';
import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model';
import { DateWidgetComponent } from './date.widget';
import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { FormFieldTypes } from '../core/form-field-types';
import { isSameDay } from 'date-fns';
import { DateFnsUtils } from '../../../../common';

describe('DateWidgetComponent', () => {
let widget: DateWidgetComponent;
Expand Down Expand Up @@ -63,8 +62,8 @@ describe('DateWidgetComponent', () => {

widget.ngOnInit();

const expectedMinDate = DateFnsUtils.parseDate(minValue, widget.field.dateDisplayFormat);
expect(isSameDay(widget.minDate, expectedMinDate)).toBeTruthy();
const expected = moment(minValue, widget.field.dateDisplayFormat);
expect(widget.minDate.isSame(expected)).toBeTruthy();
});

it('should date field be present', () => {
Expand All @@ -86,8 +85,8 @@ describe('DateWidgetComponent', () => {
});
widget.ngOnInit();

const expectedMaxDate = DateFnsUtils.parseDate(maxValue, widget.field.dateDisplayFormat);
expect(isSameDay(widget.maxDate, expectedMaxDate)).toBeTruthy();
const expected = moment(maxValue, widget.field.dateDisplayFormat);
expect(widget.maxDate.isSame(expected)).toBeTruthy();
});

it('should eval visibility on date changed', () => {
Expand Down Expand Up @@ -250,20 +249,4 @@ describe('DateWidgetComponent', () => {

expect(dateElement?.value).toContain('03-02-2020');
});

describe('format label', () => {
beforeEach(() => {
widget.field = new FormFieldModel(new FormModel({ taskId: '<id>' }), {
name: 'Date',
dateDisplayFormat: 'd-M-yyyy'
});
fixture.detectChanges();
});

it('should format label correctly', () => {
const result = widget.formatDateLabel(widget.field);

expect(result).toBe('Date (D-M-YYYY)');
});
});
});
16 changes: 7 additions & 9 deletions lib/core/src/lib/form/components/widgets/date/date.widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ import { MatDatepickerInputEvent } from '@angular/material/datepicker';
@Component({
selector: 'date-widget',
providers: [
{ provide: DateAdapter, useClass: DateFnsAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_DATE_FNS_FORMATS }
],
{ provide: DateAdapter, useClass: MomentDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MOMENT_DATE_FORMATS }],
templateUrl: './date.widget.html',
host: {
'(click)': 'event($event)',
Expand Down Expand Up @@ -63,20 +62,19 @@ export class DateWidgetComponent extends WidgetComponent implements OnInit, OnDe
private onDestroy$ = new Subject<boolean>();

constructor(public formService: FormService,
private dateAdapter: DateAdapter<DateFnsAdapter>,
private userPreferencesService: UserPreferencesService,
@Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats,
private translationService: TranslationService) {
private dateAdapter: DateAdapter<Moment>,
private userPreferencesService: UserPreferencesService) {
super(formService);
}

ngOnInit() {
this.userPreferencesService
.select(UserPreferenceValues.Locale)
.pipe(takeUntil(this.onDestroy$))
.subscribe(locale => this.dateAdapter.setLocale(DateFnsUtils.getLocaleFromString(locale)));
.subscribe(locale => this.dateAdapter.setLocale(locale));

this.dateFormatConfig.display.dateInput = this.field.dateDisplayFormat;
const momentDateAdapter = this.dateAdapter as MomentDateAdapter;
momentDateAdapter.overrideDisplayFormat = this.field.dateDisplayFormat;

if (this.field) {
if (this.field.minValue) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<div class="{{field.className}}" id="data-widget" [class.adf-invalid]="!field.isValid && isTouched()" [class.adf-left-label-input-container]="field.leftLabels">
<div *ngIf="field.leftLabels">
<label class="adf-label adf-left-label" [attr.for]="field.id">{{formatLabel(field)}}<span class="adf-asterisk"
<label class="adf-label adf-left-label" [attr.for]="field.id">{{field.name | translate }} ({{field.dateDisplayFormat}})<span class="adf-asterisk"
*ngIf="isRequired()">*</span></label>
</div>
<div>
<mat-form-field class="adf-date-widget" [class.adf-left-label-input-datepicker]="field.leftLabels" [hideRequiredMarker]="true">
<label class="adf-label" *ngIf="!field.leftLabels" [attr.for]="field.id">{{formatLabel(field)}}<span class="adf-asterisk"
<label class="adf-label" *ngIf="!field.leftLabels" [attr.for]="field.id">{{field.name | translate }} ({{field.dateDisplayFormat}})<span class="adf-asterisk"
*ngIf="isRequired()">*</span></label>
<input matInput
[id]="field.id"
Expand All @@ -22,11 +22,11 @@
</mat-form-field>
<error-widget [error]="field.validationSummary"></error-widget>
<error-widget *ngIf="isInvalidFieldRequired() && isTouched()" required="{{ 'FORM.FIELD.REQUIRED' | translate }}"></error-widget>
<mat-datepicker #datePicker [touchUi]="true" [startAt]="field.value | adfDate: field.dateDisplayFormat" [disabled]="field.readOnly"></mat-datepicker>
<mat-datepicker #datePicker [touchUi]="true" [startAt]="field.value | adfMomentDate: field.dateDisplayFormat" [disabled]="field.readOnly"></mat-datepicker>
<input
type="hidden"
[matDatepicker]="datePicker"
[value]="field.value | adfDate: field.dateDisplayFormat"
[value]="field.value | adfMomentDate: field.dateDisplayFormat"
[min]="minDate"
[max]="maxDate"
[disabled]="field.readOnly"
Expand Down
Loading

0 comments on commit 27dbd03

Please sign in to comment.