date-fns#isAfter TypeScript Examples
The following examples show how to use
date-fns#isAfter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: wallets-assets.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
shouldRequestAssetInformation$ = this.requestAssetInformation$.asObservable()
.pipe(switchMap(params => {
return of(true)
.pipe(map(_ => {
if (params.asset._id === 'native') {
return false;
}
if (params.forceUpdate) {
return true;
}
if (!params.asset.lastTimeUpdated) {
return true;
}
const lastUpdate = new Date(params.asset.lastTimeUpdated);
// TODO: maybe we should make this time dynamic and configurable form the settings
const nextUpdate = add(lastUpdate, { minutes: 15 });
const now = new Date();
return !params.asset.assetFullDataLoaded && isAfter(now, nextUpdate);
}))
.pipe(filter(Boolean))
.pipe(map(_ => ({
asset: params.asset as IWalletAssetModel,
horizonApi: params.horizonApi,
})));
}))
.pipe(map(({ asset, horizonApi}) => {
return {
_id: asset._id,
assetIssuer: asset.assetIssuer,
assetCode: asset.assetCode,
horizonApi,
};
}));
Example #2
Source File: RelativeRangePicker.tsx From gio-design with Apache License 2.0 | 6 votes |
function RelativeRangePicker({ disabledDate, timeRange, onSelect, onCancel, ...rest }: RangePickerProps) {
const defaultDates = parseStartAndEndDate(timeRange ?? 'day:2,1');
const [dates, setDates] = React.useState<[Date, Date]>(defaultDates as [Date, Date]);
const [endDateHidden, setEndDateHidden] = React.useState<boolean>(isYesterday(dates[1]));
const inputDisabled = !isNil(disabledDate);
const handleDisabledDate = (current: Date) =>
disabledDate?.(current) || isAfter(startOfDay(current), endDateHidden ? startOfYesterday() : startOfToday());
const handleOnOK = () => {
onSelect(`day:${differenceInDays(startOfToday(), dates[0]) + 1},${differenceInDays(startOfToday(), dates[1])}`);
};
return (
<InnerRangePanel
data-testid="relative-range-picker"
disableOK={!isValid(dates[0]) || !isValid(dates[1])}
header={<RelativeRangeHeader inputDisabled={inputDisabled} dateRange={dates} onRangeChange={setDates} onModeChange={setEndDateHidden} />}
body={
<RelativeRangeBody
dateRange={dates}
fixedMode={endDateHidden}
disabledDate={handleDisabledDate}
onRangeChange={setDates}
/>
}
onCancel={onCancel}
onOK={handleOnOK}
{...rest}
/>
);
}
Example #3
Source File: Account.ts From remix-hexagonal-architecture with MIT License | 6 votes |
export async function resetPassword(
account: AccountForgotPassword,
token: string,
newPassword: string,
passwordHasher: PasswordHasher,
clock: Clock
): Promise<VerifiedAccount> {
if (token !== account.passwordResetToken)
throw new InvalidPasswordResetTokenError(token);
if (isAfter(clock.now(), account.passwordResetExpiration))
throw new PasswordResetTokenExpiredError(token);
return {
type: "verified",
id: account.id,
email: account.email,
hash: await passwordHasher.hash(newPassword),
};
}
Example #4
Source File: sleep-data-helper.ts From nyxo-app with GNU General Public License v3.0 | 6 votes |
// Find the endit time of the night
export function findEndTime(nights: Night[], value: Value): string {
const nightStartTime = nights
?.filter((n: Night) => n.value === value)
.reduce((previousValue: Night, currentValue: Night) =>
isAfter(new Date(previousValue.endDate), new Date(currentValue.endDate))
? previousValue
: currentValue
)
return new Date(nightStartTime.endDate).toISOString()
}
Example #5
Source File: ListProviderDayAvailabilityService.ts From gobarber-project with MIT License | 6 votes |
public async execute({
provider_id,
day,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInDayFromProvider(
{
provider_id,
day,
month,
year,
},
);
const hourStart = 8;
const eachHourArray = Array.from(
{ length: 10 },
(_, index) => index + hourStart,
);
const currentDate = new Date(Date.now());
const availability = eachHourArray.map(hour => {
const hasAppointmentInHour = appointments.find(
appointment => getHours(appointment.date) === hour,
);
const compareDate = new Date(year, month - 1, day, hour);
return {
hour,
available: !hasAppointmentInHour && isAfter(compareDate, currentDate),
};
});
return availability;
}
Example #6
Source File: ListProviderMonthAvailabilityService.ts From gobarber-project with MIT License | 6 votes |
public async execute({
provider_id,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
{
provider_id,
month,
year,
},
);
const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));
const eachDayArray = Array.from(
{ length: numberOfDaysInMonth },
(_, index) => index + 1,
);
const availability = eachDayArray.map(day => {
const compareDate = new Date(year, month - 1, day, 23, 59, 59);
const appointmentsInDay = appointments.filter(appointment => {
return getDate(appointment.date) === day;
});
return {
day,
available:
isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
};
});
return availability;
}
Example #7
Source File: ResetPasswordService.ts From hotseat-api with MIT License | 6 votes |
async execute({ token, password }: IRequest): Promise<User> {
const checkIfRequestExists = await this.recoverPasswordRequestsMailRepository.findByToken(
token,
);
if (!checkIfRequestExists?.token) {
throw new AppError("Token doesn't exists");
}
const checkIfRequestIsExpired = isAfter(
Date.now(),
checkIfRequestExists.expires_at,
);
if (checkIfRequestIsExpired) {
throw new AppError('The recover password request is expired');
}
const checkIfUserExists = await this.usersRepository.findById(
checkIfRequestExists.user_id,
);
if (!checkIfUserExists) {
throw new AppError("User doesn't exists");
}
checkIfUserExists.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(checkIfUserExists);
this.recoverPasswordRequestsMailRepository.delete(checkIfRequestExists?.id);
return checkIfUserExists;
}
Example #8
Source File: ResetPasswordService.ts From gobarber-project with MIT License | 6 votes |
public async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User Token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User Token does not exists');
}
const tokenCreatedAt = userToken.created_at;
const compareDate = addHours(tokenCreatedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #9
Source File: ListProviderDayAvailabilityService.ts From GoBarber with MIT License | 6 votes |
public async execute({
provider_id,
day,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInDayFromProvider(
{
provider_id,
day,
month,
year,
},
);
const hourStart = 8;
const eachHourArray = Array.from(
{ length: 10 },
(_, index) => index + hourStart,
);
const currentDate = new Date(Date.now());
const availability = eachHourArray.map(hour => {
const hasAppointmentInHour = appointments.find(
appointment => getHours(appointment.date) === hour,
);
const compareDate = new Date(year, month - 1, day, hour);
return {
hour,
available: !hasAppointmentInHour && isAfter(compareDate, currentDate),
};
});
return availability;
}
Example #10
Source File: ListProviderMonthAvailabilityService.ts From GoBarber with MIT License | 6 votes |
public async execute({
provider_id,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
{
provider_id,
month,
year,
},
);
const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));
const eachDayArray = Array.from(
{ length: numberOfDaysInMonth },
(_, index) => index + 1,
);
const availability = eachDayArray.map(day => {
const compareDate = endOfDay(new Date(year, month - 1, day));
const appointmentsInDay = appointments.filter(appointment => {
return getDate(appointment.date) === day;
});
return {
day,
available:
isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
};
});
return availability;
}
Example #11
Source File: ResetPasswordService.ts From GoBarber with MIT License | 6 votes |
public async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User does not exists');
}
const tokenCreatedAt = userToken.created_at;
const compareDate = addHours(tokenCreatedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #12
Source File: dategrid.ts From calendar-hack with MIT License | 6 votes |
setEvent(date: Date, event: T | undefined) {
const k = key(date);
if (event) {
this._events.set(k, event);
// min/max/first/last/weekCount maintenance
if (!this._max || isAfter(date, this._max))
this._max = date;
this._last = startOfDay(endOfWeek(this._max, { weekStartsOn: 1 }))
if (!this._min || isBefore(date, this._min))
this._min = date;
this._first = startOfWeek(this._min, { weekStartsOn: 1 })
this._weekCount = differenceInWeeks(startOfDay(addDays(this._last, 1)), this._first);
} else {
this._events.delete(k);
}
}
Example #13
Source File: timeParser.ts From tempomat with MIT License | 6 votes |
function intervalToSeconds(startTime: string, endTime: string, referenceDate: Date): number | null {
var start = parseTime(startTime, referenceDate)
var end = parseTime(endTime, referenceDate)
if (!start || !end) return null
const diff = differenceInSeconds(end, start)
if (isAfter(end, start)) {
return diff
} else {
const dayInSeconds = 86400
return dayInSeconds + diff
}
}
Example #14
Source File: claimable-balances.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
canBeClaimed(predicate: Horizon.Predicate): boolean {
let canClaim = false;
// TODO: later when there is proper typing from the SDK, update this
if ((predicate as any).unconditional === true) {
canClaim = true;
}
if (typeof predicate.abs_before !== 'undefined') {
canClaim = isBefore(new Date(), new Date(predicate.abs_before));
}
if (typeof predicate.rel_before !== 'undefined') {
canClaim = isAfter(new Date(), new Date(predicate.rel_before));
}
if (typeof predicate.not !== 'undefined') {
canClaim = !this.canBeClaimed(predicate.not);
}
if (typeof predicate.and !== 'undefined') {
canClaim = predicate.and.every(p => this.canBeClaimed(p));
}
if (typeof predicate.or !== 'undefined') {
canClaim = !!predicate.or.find(p => this.canBeClaimed(p));
}
return canClaim;
}
Example #15
Source File: ResetPasswordService.ts From gobarber-api with MIT License | 6 votes |
async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User does not exists');
}
const tokenCraetedAt = userToken.created_at;
const compareDate = addHours(tokenCraetedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #16
Source File: ListProviderMonthAvailabilityService.ts From gobarber-api with MIT License | 6 votes |
public async execute({
provider_id,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
{
provider_id,
month,
year,
},
);
const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));
const eachDayArray = Array.from(
{ length: numberOfDaysInMonth },
(_, index) => index + 1,
);
const availability = eachDayArray.map(day => {
const compareDate = new Date(year, month - 1, day, 23, 59, 59);
const appointmentsInDay = appointments.filter(appointment => {
return getDate(appointment.date) === day;
});
return {
day,
available:
isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
};
});
return availability;
}
Example #17
Source File: ListProviderDayAvailabilityService.ts From gobarber-api with MIT License | 6 votes |
public async execute({
provider_id,
day,
month,
year,
}: IRequest): Promise<IResponse> {
const appointments = await this.appointmentsRepository.findAllInDayFromProvider(
{
provider_id,
day,
month,
year,
},
);
const hourStart = 8;
const eachHourArray = Array.from(
{ length: 10 },
(_, index) => index + hourStart,
);
const currentDate = new Date(Date.now());
const availability = eachHourArray.map(hour => {
const hasAppointmentInHour = appointments.find(
appointment => getHours(appointment.date) === hour,
);
const compareDate = new Date(year, month - 1, day, hour);
return {
hour,
available: !hasAppointmentInHour && isAfter(compareDate, currentDate),
};
});
return availability;
}
Example #18
Source File: deleteBooking.ts From office-booker with MIT License | 5 votes |
deleteBooking = async (
config: Config,
currentUser: User,
bookingToDelete: { id: string; email: string }
): Promise<void> => {
const booking = await getBooking(config, bookingToDelete.id, bookingToDelete.email);
const isEditingSelf = booking !== undefined && booking.user === currentUser.email;
const canManageOfficeBookings = booking !== undefined && canManageBooking(currentUser, booking);
const isAuthorised = isEditingSelf || canManageOfficeBookings;
if (!isAuthorised) {
throw new Forbidden(
`${currentUser.email} tried to delete another user's booking but is not admin, or office admin`
);
}
if (booking === undefined) {
throw new NotFound();
}
const startOfWeek = dateStartOfWeek(booking.date);
const lastCancelTime = canManageOfficeBookings
? getBookingAdminLastCancelTime(booking.date)
: getBookingLastCancelTime(booking.date);
if (isAfter(new Date(), parseISO(lastCancelTime))) {
throw new HttpError({
internalMessage: `Booking can no longer be cancelled. id: ${booking.id} for ${booking.user}`,
status: 403,
httpMessage: 'No longer able to cancel booking',
});
}
audit('1:DeletingBooking', { booking, startOfWeek, currentUser: { email: currentUser.email } });
await deleteBookingDb(config, booking.id, booking.user);
try {
audit('2:DecrementingOfficeBookingCount');
await decrementOfficeBookingCount(config, booking.officeId, booking.date, booking.parking);
audit('3:DecrementingUserBookingCount');
await decrementUserBookingCount(config, booking.user, startOfWeek);
} catch (err) {
throw new CustomError(
`Deleted booking but failed while decremeting counts: ${JSON.stringify(booking)}`,
err
);
}
audit('4:Completed');
}
Example #19
Source File: validator.ts From elements with MIT License | 5 votes |
private validateMinSingle = (value: string): boolean => {
const parsedDate: Date = this.parseDate(value);
return (
isEqual(parsedDate, this._minDate) || isAfter(parsedDate, this._minDate)
);
};
Example #20
Source File: SinceRangePicker.tsx From gio-design with Apache License 2.0 | 5 votes |
function SinceRangePicker({ disabledDate, timeRange, onSelect, onCancel, experimental, ...rest }: RangePickerProps) {
const endDateKeys = ['today', experimental ? 'yesterday' : undefined];
const dates = parseStartAndEndDate(timeRange);
const prefixCls = usePrefixCls('range-panel__header');
const [startDate, setStartDate] = React.useState<Date | undefined>(dates[0]);
const [endKey, setEndKey] = React.useState(
endDateKeys[timeRange && timeRange.split(':')[0] === 'since' ? 0 : 1] || 0
);
const locale = useLocale<typeof defaultLocale>('StaticPastTimePicker') || defaultLocale;
const { startDayText, FromText, toTodayText, toYesterdayText } = {
...defaultLocale,
...locale,
};
const END_DATE_MAPPING: Record<string, string> = {
today: toTodayText,
yesterday: toYesterdayText,
};
const renderHeader = () => {
const startDateString = startDate ? format(startDate, DATE_FORMAT) : startDayText;
return (
<>
<span className={`${prefixCls}__text`}>{`${FromText} ${startDateString}`}</span>
<span className={`${prefixCls}__options`}>
<Switch
size="small"
defaultValue={endKey}
onChange={(e) => {
setEndKey(e.target.value);
}}
>
{endDateKeys.map(
(o: string) =>
o && (
<Switch.Item key={o} value={o}>
{END_DATE_MAPPING[o]}
</Switch.Item>
)
)}
</Switch>
</span>
</>
);
};
const handleDisabledDate = (current: Date) =>
disabledDate?.(current) || isAfter(current, endKey === 'yesterday' ? startOfYesterday() : startOfToday());
const handleOnOK = () => {
onSelect(`${endKey === 'yesterday' ? 'since-lt-today' : 'since'}:${getTime(startOfDay(startDate as Date))}`);
};
return (
<InnerRangePanel
disableOK={!isValid(startDate)}
header={renderHeader()}
body={<DatePicker disabledDate={handleDisabledDate} value={startDate} onSelect={setStartDate} />}
onCancel={onCancel}
onOK={handleOnOK}
{...rest}
/>
);
}
Example #21
Source File: AuctionTimer.tsx From vvs-ui with GNU General Public License v3.0 | 5 votes |
AuctionTimer: React.FC<{ auction: Auction }> = ({ auction }) => {
const { t } = useTranslation()
if (!auction) {
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Skeleton width="256px" height="40px" />
</Flex>
)
}
if (auction.status === AuctionStatus.ToBeAnnounced || auction.status === AuctionStatus.Closed) {
return null
}
if (auction.status === AuctionStatus.Finished) {
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Text bold>{t('Closing')}...</Text>
<PocketWatchIcon height="40px" width="40px" />
</Flex>
)
}
const { startDate, endDate } = auction
const timerUntil = isAfter(startDate, new Date()) ? startDate : endDate
const timerTitle = timerUntil === endDate ? t('Ending in') : t('Next auction')
const secondsRemaining = differenceInSeconds(timerUntil, new Date())
const { days, hours, minutes } = getTimePeriods(secondsRemaining)
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Text bold>{timerTitle}: </Text>
<AuctionCountDown>
{days !== 0 && (
<>
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{days}
</Text>
<Text verticalAlign="baseline" bold mr="4px">
{t('d')}
</Text>
</>
)}
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{hours}
</Text>
<Text verticalAlign="baseline" bold mr="4px">
{t('h')}
</Text>
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{minutes}
</Text>
<Text verticalAlign="baseline" bold>
{t('m')}
</Text>
</AuctionCountDown>
<PocketWatchIcon height="40px" width="40px" />
</Flex>
)
}
Example #22
Source File: AbsoluteRangePicker.tsx From gio-design with Apache License 2.0 | 5 votes |
function AbsoluteRangePicker({ disabledDate, timeRange, onSelect, onRangeSelect, onCancel }: RangePickerProps) {
const [dates, setDates] = React.useState<[Date | undefined, Date | undefined]>(parseStartAndEndDate(timeRange));
const prefixCls = usePrefixCls('range-panel__header');
const locale = useLocale('StaticPastTimePicker');
const { startDayText, endDayText, FromText, ToText } = {
...defaultLocale,
...locale,
};
const renderHeader = () => {
const placeholder = [startDayText, endDayText];
const dateString = formatDates(dates);
const dateTexts = dateString?.split('-')?.map((d) => (d === ' ' ? undefined : d)) || [];
const text = [dateTexts[0] ?? placeholder[0], dateTexts[1] ?? placeholder[1]];
return <span className={`${prefixCls}__text`}>{`${FromText} ${text[0]} ${ToText} ${text[1]}`}</span>;
};
const handleDisabledDate = (current: Date) => disabledDate?.(current) || isAfter(current, startOfToday());
const handleOnOK = () => {
onSelect(`abs:${getTime(startOfDay(dates[0] as Date))},${getTime(endOfDay(dates[1] as Date))}`);
};
const handleOnSelect = (date: [Date, Date], index: number) => {
setDates(date);
onRangeSelect?.(date, index);
}
const endDay = dates[1] !== undefined && isValid(dates[1]) ? dates[1] : new Date();
return (
<InnerRangePanel
disableOK={!isValid(dates[0]) || !isValid(dates[1])}
header={renderHeader()}
body={
<StaticDateRangePicker
defaultViewDates={[subMonths(startOfDay(endDay), 1), startOfDay(endDay)]}
disabledDate={handleDisabledDate}
onSelect={handleOnSelect}
value={dates as [Date, Date]}
/>
}
onCancel={onCancel}
onOK={handleOnOK}
/>
);
}
Example #23
Source File: AuctionTimer.tsx From glide-frontend with GNU General Public License v3.0 | 5 votes |
AuctionTimer: React.FC<{ auction: Auction }> = ({ auction }) => {
const { t } = useTranslation()
if (!auction) {
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Skeleton width="256px" height="40px" />
</Flex>
)
}
if (auction.status === AuctionStatus.ToBeAnnounced || auction.status === AuctionStatus.Closed) {
return null
}
if (auction.status === AuctionStatus.Finished) {
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Text bold>{t('Closing')}...</Text>
<PocketWatchIcon height="40px" width="40px" />
</Flex>
)
}
const { startDate, endDate } = auction
const timerUntil = isAfter(startDate, new Date()) ? startDate : endDate
const timerTitle = timerUntil === endDate ? t('Ending in') : t('Next auction')
const secondsRemaining = differenceInSeconds(timerUntil, new Date())
const { days, hours, minutes } = getTimePeriods(secondsRemaining)
return (
<Flex justifyContent="center" alignItems="center" mb="48px">
<Text bold>{timerTitle}: </Text>
<AuctionCountDown>
{days !== 0 && (
<>
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{days}
</Text>
<Text verticalAlign="baseline" bold mr="4px">
{t('d')}
</Text>
</>
)}
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{hours}
</Text>
<Text verticalAlign="baseline" bold mr="4px">
{t('h')}
</Text>
<Text verticalAlign="baseline" lineHeight="28px" fontSize="24px" bold color="secondary" mr="4px">
{minutes}
</Text>
<Text verticalAlign="baseline" bold>
{t('m')}
</Text>
</AuctionCountDown>
<PocketWatchIcon height="40px" width="40px" />
</Flex>
)
}
Example #24
Source File: matchDayUtils.tsx From symphony-ui-toolkit with Apache License 2.0 | 5 votes |
function isDayAfter(day1: Date, day2: Date): boolean {
return isAfter(day1, day2) && !isSameDay(day1, day2);
}
Example #25
Source File: datetime.ts From panvala with Apache License 2.0 | 5 votes |
dateHasPassed = (uts: number) => isAfter(new Date(), new Date(uts * 1000))
Example #26
Source File: ListProviderMonthAvailabilityService.ts From hotseat-api with MIT License | 5 votes |
async execute({ provider_id, month, year }: IRequest): Promise<IResponse> {
const provider = await this.usersRepository.findById(provider_id);
if (!provider) {
throw new AppError('Provider not found', 404);
}
const appointments = await this.appointmentsRepository.findByMonthFromProvider(
{
year,
month,
provider_id,
},
);
const numberOfDaysInMonth = getDaysInMonth(month - 1);
const daysInMonth = Array.from(
{ length: numberOfDaysInMonth },
(_, index) => index + 1,
);
const availability = daysInMonth.map(day => {
const numberOfAppointmentsInDay = appointments.filter(
appointment => getDate(appointment.date) === day,
).length;
const availabilityDate = new Date(
year,
parseMonthToJSMonth(month),
day,
23,
59,
59,
);
const isPast = isAfter(new Date(Date.now()), availabilityDate);
return {
day,
isPast,
available:
!isPast && numberOfAppointmentsInDay < MAX_APPOINTMENTS_PER_DAY,
};
});
return availability;
}
Example #27
Source File: ListProviderDayAvailabilityService.ts From hotseat-api with MIT License | 5 votes |
async execute({
provider_id,
day,
month,
year,
}: IRequest): Promise<IResponse> {
const provider = await this.usersRepository.findById(provider_id);
if (!provider) {
throw new AppError('Provider not found', 404);
}
const appointments = await this.appointmentsRepository.findByDayFromProvider(
{
provider_id,
day,
month,
year,
},
);
const businessHoursArray = Array.from(
{ length: MAX_APPOINTMENTS_PER_DAY },
(_, index) => index + BUSINESS_START_HOUR,
);
const currentDate = new Date(Date.now());
const availability = businessHoursArray.map(hour => {
const hasAppointmentInThisHour = appointments.find(
appointment => getHours(appointment.date) === hour,
);
const chosenDate = new Date(year, month - 1, day, hour);
return {
hour,
available:
!hasAppointmentInThisHour && isAfter(chosenDate, currentDate),
};
});
return availability;
}
Example #28
Source File: CreateAppointmentService.ts From hotseat-api with MIT License | 5 votes |
public async execute({
provider_id,
customer_id,
date,
type,
}: IRequest): Promise<Appointment> {
const appointmentDate = startOfHour(date);
const appointmentInTheSameDate = await this.appointmentsRepository.findByDate(
appointmentDate,
);
if (
appointmentInTheSameDate &&
appointmentInTheSameDate.provider_id === provider_id
) {
throw new AppError("There's already a appointment booked in that date");
}
const customerIsTheProvider = provider_id === customer_id;
if (customerIsTheProvider) {
throw new AppError("You can't book an appointment with yourself");
}
const hasValidDate = isAfter(appointmentDate, new Date(Date.now()));
if (!hasValidDate) {
throw new AppError("You can't book an appointment in a past date");
}
const appointmentHours = getHours(appointmentDate);
const isInBusinessHoursRange =
appointmentHours >= BUSINESS_START_HOUR &&
appointmentHours <= BUSINESS_LIMIT_HOUR;
if (!isInBusinessHoursRange) {
throw new AppError(
"You can't book an appointment in a hour outside the business hours range",
);
}
const appointment = this.appointmentsRepository.create({
provider_id,
customer_id,
date: appointmentDate,
type,
});
const notificationAppointmentDate = format(
appointmentDate,
'dd-MM-yyyy HH:mm',
);
await this.notificationsRepository.create({
content: `You have an appointment schedule to ${notificationAppointmentDate}`,
recipient_id: provider_id,
});
this.cacheProvider.invalidate(
getProviderAppointmentsListCacheKey(provider_id, appointmentDate),
);
return appointment;
}
Example #29
Source File: index.tsx From gobarber-web with MIT License | 4 votes |
Dashboard: React.FC = () => {
const { signOut, user } = useAuth();
const [selectedDate, setSelectedDate] = useState(new Date());
const [currentMonth, setCurrentMonth] = useState(new Date());
const [monthAvailability, setMonthAvailability] = useState<
MonthAvailabilityItem[]
>([]);
const [appointments, setAppointments] = useState<Appointment[]>([]);
const handleDateChange = useCallback((day: Date, modifiers: DayModifiers) => {
if (modifiers.available && !modifiers.disabled) {
setSelectedDate(day);
}
}, []);
const handleMonthChange = useCallback((month: Date) => {
setCurrentMonth(month);
}, []);
useEffect(() => {
api
.get(`/providers/${user.id}/month-availability`, {
params: {
year: currentMonth.getFullYear(),
month: currentMonth.getMonth() + 1,
},
})
.then(response => setMonthAvailability(response.data));
}, [currentMonth, user.id]);
useEffect(() => {
api
.get<Appointment[]>('/appointments/me', {
params: {
year: selectedDate.getFullYear(),
month: selectedDate.getMonth() + 1,
day: selectedDate.getDate(),
},
})
.then(response => {
const appointmentsFormatted = response.data.map(appointment => ({
...appointment,
hourFormatted: format(parseISO(appointment.date), 'HH:mm'),
}));
setAppointments(appointmentsFormatted);
});
}, [selectedDate]);
const disableDays = useMemo(() => {
return monthAvailability
.filter(monthDay => monthDay.available === false)
.map(monthDay => {
const year = currentMonth.getFullYear();
const month = currentMonth.getMonth();
return new Date(year, month, monthDay.day);
});
}, [currentMonth, monthAvailability]);
const selectedDateAsText = useMemo(() => {
return format(selectedDate, "'Dia' dd 'de' MMMM", { locale: ptBR });
}, [selectedDate]);
const selectedWeekDay = useMemo(() => {
return format(selectedDate, 'cccc', { locale: ptBR });
}, [selectedDate]);
const morningAppointments = useMemo(() => {
return appointments.filter(appointment => {
return parseISO(appointment.date).getHours() < 12;
});
}, [appointments]);
const afternoonAppointments = useMemo(() => {
return appointments.filter(appointment => {
return parseISO(appointment.date).getHours() >= 12;
});
}, [appointments]);
const nextAppointment = useMemo(() => {
return appointments.find(appointment =>
isAfter(parseISO(appointment.date), new Date()),
);
}, [appointments]);
return (
<S.Container>
<S.Header>
<S.HeaderContent>
<img src={logoImg} alt="Logo GoBarber" />
<S.HeaderProfile>
<img
src={
user.avatar_url ||
'https://api.adorable.io/avatars/56/[email protected]'
}
alt={user.name}
/>
<div>
<span>Bem-vindo,</span>
<Link to="/profile">
<strong>{user.name}</strong>
</Link>
</div>
</S.HeaderProfile>
<button type="button" onClick={signOut}>
<FiPower size={20} />
</button>
</S.HeaderContent>
</S.Header>
<S.Content>
<S.Schedule>
<h1>Horários agendados</h1>
<p>
{isToday(selectedDate) && <span>Hoje</span>}
<span>{selectedDateAsText}</span>
<span>{`${selectedWeekDay}-feira`}</span>
</p>
{isToday(selectedDate) && nextAppointment && (
<S.NextAppointment>
<strong>Atendimento a seguir</strong>
<div>
<img
src={
nextAppointment.user.avatar_url ||
'https://api.adorable.io/avatars/80/[email protected]'
}
alt={nextAppointment.user.name}
/>
<strong>{nextAppointment.user.name}</strong>
<span>
<FiClock size={24} />
{nextAppointment.hourFormatted}
</span>
</div>
</S.NextAppointment>
)}
<S.Section>
<strong>Manhã</strong>
{morningAppointments.length === 0 && (
<p>Nenhum agendamento neste período</p>
)}
{morningAppointments.map(appointment => (
<S.Appointment key={appointment.id}>
<span>
<FiClock size={20} />
{appointment.hourFormatted}
</span>
<div>
<img
src={
appointment.user.avatar_url ||
'https://api.adorable.io/avatars/56/[email protected]'
}
alt={appointment.user.name}
/>
<strong>{appointment.user.name}</strong>
</div>
</S.Appointment>
))}
</S.Section>
<S.Section>
<strong>Tarde</strong>
{afternoonAppointments.length === 0 && (
<p>Nenhum agendamento neste período</p>
)}
{afternoonAppointments.map(appointment => (
<S.Appointment key={appointment.id}>
<span>
<FiClock size={20} />
{appointment.hourFormatted}
</span>
<div>
<img
src={
appointment.user.avatar_url ||
'https://api.adorable.io/avatars/56/[email protected]'
}
alt={appointment.user.name}
/>
<strong>{appointment.user.name}</strong>
</div>
</S.Appointment>
))}
</S.Section>
</S.Schedule>
<S.Calendar>
<DayPicker
weekdaysShort={['D', 'S', 'T', 'Q', 'Q', 'S', 'S']}
fromMonth={new Date()}
disabledDays={[{ daysOfWeek: [0, 6] }, ...disableDays]}
modifiers={{
available: { daysOfWeek: [1, 2, 3, 4, 5] },
}}
onMonthChange={handleMonthChange}
selectedDays={selectedDate}
onDayClick={handleDateChange}
months={[
'Janeiro',
'Fevereiro',
'Março',
'Abril',
'Maio',
'Junho',
'Julho',
'Agosto',
'Setembro',
'Outubro',
'Novembro',
'Dezembro',
]}
/>
</S.Calendar>
</S.Content>
</S.Container>
);
}