Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor date handling #1696

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 4 additions & 28 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@
"@entur/tooltip": "5.1.3",
"@entur/typography": "1.8.49",
"@fintraffic/fds-coreui-css": "0.1.3",
"@internationalized/date": "^3.6.0",
"@lit-labs/react": "2.1.3",
"@reduxjs/toolkit": "1.9.7",
"@sentry/react": "7.120.0",
"axios": "1.7.8",
"classnames": "2.5.1",
"date-fns": "2.30.0",
"duration-fns": "3.0.2",
"file-saver": "2.0.5",
"graphql": "16.9.0",
Expand All @@ -51,7 +51,6 @@
"lodash.clonedeep": "4.5.0",
"lodash.isempty": "4.4.0",
"lodash.isequal": "4.5.0",
"moment": "2.30.1",
"oidc-client-ts": "3.1.0",
"react": "18.3.1",
"react-dom": "18.3.1",
Expand Down
26 changes: 13 additions & 13 deletions src/components/BookingArrangementEditor/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { Dropdown } from '@entur/dropdown';
import { Fieldset, Radio, RadioGroup, TextArea, TextField } from '@entur/form';
import { Label, LeadParagraph } from '@entur/typography';
import { TimeValue } from '@react-types/datepicker';
import { CalendarDateTime } from '@internationalized/date';
import DurationPicker from 'components/DurationPicker';
import { TimeUnitPickerPosition } from 'components/TimeUnitPicker';
import { format } from 'date-fns';
import { getCurrentDateTime } from '../../utils/dates';
import { addOrRemove } from 'helpers/arrays';
import { getEnumInit, mapEnumToItems } from 'helpers/dropdown';
import BookingArrangement from 'model/BookingArrangement';
Expand Down Expand Up @@ -58,13 +59,15 @@ export default (props: Props) => {
minimumBookingPeriod,
} = bookingArrangement;

let latestbookingTimeAsDate: Date | undefined = undefined;
let latestbookingTimeAsDate: CalendarDateTime | undefined = undefined;
if (latestBookingTime && latestBookingTime !== '') {
latestbookingTimeAsDate = new Date();
latestbookingTimeAsDate.setHours(parseInt(latestBookingTime.split(':')[0]));
latestbookingTimeAsDate.setMinutes(
parseInt(latestBookingTime.split(':')[1]),
);
const currentDateTime = getCurrentDateTime();
const [hours, minutes] = latestBookingTime.split(':').map(Number);
latestbookingTimeAsDate = currentDateTime.copy();
latestbookingTimeAsDate.set({
hour: hours,
minute: minutes,
});
}

const onContactChange = (contact: Contact) =>
Expand Down Expand Up @@ -249,16 +252,13 @@ export default (props: Props) => {
locale={locale}
disabled={bookingLimitType !== BOOKING_LIMIT_TYPE.TIME}
selectedTime={
latestbookingTimeAsDate
? nativeDateToTimeValue(latestbookingTimeAsDate)
: null
latestbookingTimeAsDate ? latestbookingTimeAsDate : null
}
onChange={(date: TimeValue | null) => {
let formattedDate;
const nativeDate = timeOrDateValueToNativeDate(date);

if (nativeDate != null) {
formattedDate = format(nativeDate, 'HH:mm');
if (date != null) {
formattedDate = `${date.hour}:${date.minute}`;
}

onLatestBookingTimeChange(formattedDate);
Expand Down
18 changes: 9 additions & 9 deletions src/components/DayTypesEditor/DayTypeAssignmentsEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import { getErrorFeedback } from 'helpers/errorHandling';
import useUniqueKeys from 'hooks/useUniqueKeys';
import DayTypeAssignment from 'model/DayTypeAssignment';
import OperatingPeriod from 'model/OperatingPeriod';
import moment from 'moment/moment';
import React from 'react';
import { useIntl } from 'react-intl';
import { getCurrentDate, calendarDateToISO } from '../../utils/dates';
import './styles.scss';
import { parseAbsoluteToLocal } from '@internationalized/date';

type Props = {
dayTypeAssignments: DayTypeAssignment[];
Expand All @@ -26,13 +26,13 @@ const DayTypeAssignmentsEditor = ({ dayTypeAssignments, onChange }: Props) => {
const { formatMessage } = useIntl();

const addNewDayTypeAssignment = () => {
const today: string = moment().format('YYYY-MM-DD');
const tomorrow: string = moment().add(1, 'days').format('YYYY-MM-DD');
const today = getCurrentDate();
const tomorrow = today.add({ days: 1 });
const dayTypeAssignment = {
isAvailable: true,
operatingPeriod: {
fromDate: today,
toDate: tomorrow,
fromDate: today.toString(),
toDate: tomorrow.toString(),
},
};
onChange([...dayTypeAssignments, dayTypeAssignment]);
Expand All @@ -49,7 +49,7 @@ const DayTypeAssignmentsEditor = ({ dayTypeAssignments, onChange }: Props) => {
};

const isNotBefore = (toDate: string, fromDate: string): boolean =>
!moment(toDate).isBefore(moment(fromDate));
parseAbsoluteToLocal(toDate).compare(parseAbsoluteToLocal(fromDate)) > -1;

if (dayTypeAssignments.length === 0) addNewDayTypeAssignment();

Expand All @@ -74,7 +74,7 @@ const DayTypeAssignmentsEditor = ({ dayTypeAssignments, onChange }: Props) => {
<DatePicker
label={formatMessage({ id: 'dayTypeEditorFromDate' })}
selectedDate={nativeDateToDateValue(
moment(dta.operatingPeriod.fromDate).toDate(),
new Date(dta.operatingPeriod.fromDate),
)}
onChange={(date) => {
changeDay(
Expand Down Expand Up @@ -102,7 +102,7 @@ const DayTypeAssignmentsEditor = ({ dayTypeAssignments, onChange }: Props) => {
false,
)}
selectedDate={nativeDateToDateValue(
moment(dta.operatingPeriod.toDate).toDate(),
new Date(dta.operatingPeriod.toDate),
)}
onChange={(date) => {
changeDay(
Expand Down
69 changes: 58 additions & 11 deletions src/components/DurationPicker/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import cx from 'classnames';
import formatDuration from 'date-fns/formatDuration';
import { nb } from 'date-fns/locale';
import * as durationLib from 'duration-fns';
import moment from 'moment';
import { useIntl } from 'react-intl';
import TimeUnitPicker, { TimeUnitPickerPosition } from '../TimeUnitPicker';

Expand All @@ -21,6 +18,59 @@ type Props = {
disabled?: boolean;
};

const formatDuration = (duration: any, intl: any) => {
const parts = [];
if (duration.years) {
parts.push(
intl.formatMessage(
{ id: 'duration.years', defaultMessage: '{years} years' },
{ years: duration.years },
),
);
}
if (duration.months) {
parts.push(
intl.formatMessage(
{ id: 'duration.months', defaultMessage: '{months} months' },
{ months: duration.months },
),
);
}
if (duration.days) {
parts.push(
intl.formatMessage(
{ id: 'duration.days', defaultMessage: '{days} days' },
{ days: duration.days },
),
);
}
if (duration.hours) {
parts.push(
intl.formatMessage(
{ id: 'duration.hours', defaultMessage: '{hours} hours' },
{ hours: duration.hours },
),
);
}
if (duration.minutes) {
parts.push(
intl.formatMessage(
{ id: 'duration.minutes', defaultMessage: '{minutes} minutes' },
{ minutes: duration.minutes },
),
);
}
if (duration.seconds) {
parts.push(
intl.formatMessage(
{ id: 'duration.seconds', defaultMessage: '{seconds} seconds' },
{ seconds: duration.seconds },
),
);
}
return parts.join(', ');
};

export default (props: Props) => {
const {
onChange,
Expand All @@ -44,30 +94,27 @@ export default (props: Props) => {
const durationObj = durationLib.parse(duration);
return {
...durationObj,
textValue: formatDuration(durationObj, {
locale: intl.locale === 'nb' ? nb : undefined,
delimiter: ', ',
}),
textValue: formatDuration(durationObj, intl),
};
} else {
return undefined;
}
})();

const handleOnUnitChange = (unit: string, value: number) => {
const newDuration = moment.duration({
const newDuration = {
seconds: unit === 'seconds' ? value : parsedDuration?.seconds,
minutes: unit === 'minutes' ? value : parsedDuration?.minutes,
hours: unit === 'hours' ? value : parsedDuration?.hours,
days: unit === 'days' ? value : parsedDuration?.days,
months: unit === 'months' ? value : parsedDuration?.months,
years: unit === 'years' ? value : parsedDuration?.years,
});
};

onChange(
resetOnZero && newDuration.asSeconds() === 0
resetOnZero && Object.values(newDuration).every((val) => val === 0)
? undefined
: newDuration.toISOString(),
: JSON.stringify(newDuration),
);
};

Expand Down
16 changes: 9 additions & 7 deletions src/components/LinesForExport/LinesForExport.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MockedProvider } from '@apollo/client/testing';
import { addDays, format, subDays } from 'date-fns';
import { getCurrentDate } from '../../utils/dates';
import { MemoryRouter } from 'react-router-dom';

import { GET_LINES_FOR_EXPORT } from 'api/uttu/queries';
Expand Down Expand Up @@ -30,8 +30,8 @@ const line = {
dayTypeAssignments: [
{
operatingPeriod: {
fromDate: format(addDays(new Date(), 10), 'yyyy-MM-dd'),
toDate: format(addDays(new Date(), 130), 'yyyy-MM-dd'),
fromDate: getCurrentDate().add({ days: 10 }).toString(),
toDate: getCurrentDate().add({ days: 130 }).toString(),
},
},
],
Expand All @@ -55,8 +55,10 @@ const secondLine = {
dayTypeAssignments: [
{
operatingPeriod: {
fromDate: format(subDays(new Date(), 30), 'yyyy-MM-dd'),
toDate: format(subDays(new Date(), 10), 'yyyy-MM-dd'),
fromDate: getCurrentDate()
.subtract({ days: 30 })
.toString(),
toDate: getCurrentDate().subtract({ days: 10 }).toString(),
},
},
],
Expand All @@ -80,8 +82,8 @@ const flexibleLine = {
dayTypeAssignments: [
{
operatingPeriod: {
fromDate: format(new Date(), 'yyyy-MM-dd'),
toDate: format(addDays(new Date(), 10), 'yyyy-MM-dd'),
fromDate: getCurrentDate().toString(),
toDate: getCurrentDate().add({ days: 10 }).toString(),
},
},
],
Expand Down
Loading