Skip to content

Commit

Permalink
chore: replace moment with luxon
Browse files Browse the repository at this point in the history
* Adds keep history guard for patron profile.

Co-Authored-by: Bertrand Zuchuat <[email protected]>
  • Loading branch information
Garfield-fr committed Oct 29, 2024
1 parent 5bdbe24 commit a8a9afd
Show file tree
Hide file tree
Showing 26 changed files with 165 additions and 123 deletions.
9 changes: 0 additions & 9 deletions package-lock.json

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

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@
"lodash-es": "^4.17.21",
"luxon": "^3.5.0",
"marked": "^10.0.0",
"moment": "^2.30.1",
"ngx-bootstrap": "^12.0.0",
"ngx-spinner": "^16.0.0",
"primeflex": "^3.3.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* RERO ILS UI
* Copyright (C) 2021 RERO
* Copyright (C) 2021-2024 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
Expand All @@ -17,9 +17,9 @@

import { inject, Injectable } from '@angular/core';
import { ApiService } from '@rero/ng-core';
import moment from 'moment';
import { IAcqNote } from '../../../classes/common';
import { AcqReceiptAmountAdjustment, IAcqReceipt, IAcqReceiptLine } from '../../../classes/receipt';
import { DateTime } from 'luxon';

/** Interface for Receipt data */
export interface IAcqReceiptModel {
Expand Down Expand Up @@ -82,7 +82,7 @@ export class OrderReceipt {
acqOrderRef: null,
libraryRef: null,
organisationRef: null,
receiptDate: moment().format(moment.HTML5_FMT.DATE),
receiptDate: DateTime.now().toISODate(),
exchangeRate: 1,
reference: null,
amountAdjustments: [],
Expand Down
18 changes: 0 additions & 18 deletions projects/admin/src/app/api/library-api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { RecordService } from '@rero/ng-core';
import moment from 'moment';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

Expand All @@ -27,7 +25,6 @@ import { map } from 'rxjs/operators';
})
export class LibraryApiService {

private http: HttpClient = inject(HttpClient);
private recordService: RecordService = inject(RecordService);

/**
Expand All @@ -39,19 +36,4 @@ export class LibraryApiService {
return this.recordService.getRecord('libraries', pid)
.pipe(map(record => record.metadata));
}

/**
* Allow to get the closed date between two dates for a specific library
* @param libraryPid: the library pid
* @param from: the lower interval (optional)
* @param until: the upper interval (optional)
*/
getClosedDates(libraryPid: string, from?: string, until?: string): Observable<Array<moment>> {
from = from || moment().subtract(1, 'month');
until = until || moment().add(1, 'year');
return this.http.get(`/api/library/${libraryPid}/closed_dates`, {params: {from, until}}).pipe(
map((data: any) => data.closed_dates),
map((dates: [string]) => dates.map(dateStr => moment(dateStr)))
);
}
}
4 changes: 2 additions & 2 deletions projects/admin/src/app/api/operation-logs-api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ import { inject, Injectable } from '@angular/core';
import { Record, RecordService } from '@rero/ng-core';
import { Error } from '@rero/ng-core/lib/error/error';
import { BaseApi } from '@rero/shared';
import moment from 'moment';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { DateTime } from 'luxon';

@Injectable({
providedIn: 'root'
Expand Down Expand Up @@ -89,7 +89,7 @@ export class OperationLogsApiService extends BaseApi {
* @return Observable
*/
getCheckInHistory(patronPid: string, page: number, itemsPerPage: number = 10): Observable<Record | Error> {
const date = moment().subtract(6, 'months').utc().format('YYYY-MM-DDTHH:mm:ss');
const date = DateTime.now().minus({ months: 6 }).toISO();
const query = `_exists_:loan AND record.type:loan AND loan.patron.pid:${patronPid} AND loan.trigger:checkin AND date:[${date} TO *]`;
return this.recordService.getRecords(
'operation_logs', query, page, itemsPerPage, undefined, undefined, BaseApi.reroJsonheaders, 'mostrecent');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { PatronTransactionsComponent } from './patron/patron-transactions/patron
import { PendingComponent } from './patron/pending/pending.component';
import { PickupComponent } from './patron/pickup/pickup.component';
import { ProfileComponent } from './patron/profile/profile.component';
import { keepHistoryGuard } from './guard/keep-history.guard';

const routes: Routes = [
{
Expand Down Expand Up @@ -78,7 +79,7 @@ const routes: Routes = [
{
path: 'history',
component: HistoryComponent,
canActivate: [ PermissionGuard ], data: { permissions: [ PERMISSIONS.CIRC_ADMIN ] }
canActivate: [ keepHistoryGuard, PermissionGuard ], data: { permissions: [ PERMISSIONS.CIRC_ADMIN ] }
}
]
}, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* RERO ILS UI
* Copyright (C) 2024 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { TestBed } from '@angular/core/testing';
import { CanActivateFn } from '@angular/router';

import { keepHistoryGuard } from './keep-history.guard';

describe('keepHistoryGuard', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => keepHistoryGuard(...guardParameters));

beforeEach(() => {
TestBed.configureTestingModule({});
});

it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});
33 changes: 33 additions & 0 deletions projects/admin/src/app/circulation/guard/keep-history.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* RERO ILS UI
* Copyright (C) 2024 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { PatronService } from '@app/admin/service/patron.service';
import { map } from 'rxjs';

export const keepHistoryGuard: CanActivateFn = (route, state) => {
const patronService: PatronService = inject(PatronService);
const router: Router = inject(Router);

const patronPid = state.url.split('/').splice(-2)[0];
return patronService.getPatron(patronPid).pipe(map((patron: any) => {
if (!patron.keep_history) {
router.navigate(['/errors/403'], { skipLocationChange: true });
}
return patron.keep_history
}));
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->

<div class="row mb-4">
<div class="col-12 col-md-6">
<ng-core-search-input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateService } from '@ngx-translate/core';
import { CONFIG } from '@rero/ng-core';
import { UserService } from '@rero/shared';
import moment from 'moment';
import { DateTime } from 'luxon';
import { MessageService } from 'primeng/api';
import { interval, Subscription } from 'rxjs';
import { ItemsService } from '../../service/items.service';
Expand Down Expand Up @@ -116,8 +116,8 @@ export class MainRequestComponent implements OnInit, OnDestroy {
*/
private _sortingRequestedLoans(items: Array<any>) {
this.items = items.sort((a, b) => {
const aTime = moment(a.loan.transaction_date);
const bTime = moment(b.loan.transaction_date);
const aTime = DateTime.fromISO(a.loan.transaction_date);
const bTime = DateTime.fromISO(b.loan.transaction_date);
switch (this.sortCriteria) {
case '-requestdate': return bTime.diff(aTime);
case 'callnumber':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,14 @@ export class FixedDateFormComponent implements OnInit, OnDestroy {
private userService: UserService = inject(UserService);
private recordService: RecordService = inject(RecordService);

/** the date format to used */
static DATE_FORMAT = 'YYYY-MM-DD';

// COMPONENT ATTRIBUTES ====================================
/** form group */
formGroup: FormGroup = new FormGroup({
endDate: new FormControl('', [
Validators.required,
DateValidators.minimumDateValidator(
new Date(),
FixedDateFormComponent.DATE_FORMAT
DateValidators.DATE_FORMAT
)
]),
remember: new FormControl(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,12 @@ export class MainComponent implements OnInit, OnDestroy {
// null and this will cause error for navigation url construction
this._unregisterShortcuts();
this._registerShortcuts();
this.operationLogsApiService.getCheckInHistory(patron.pid, 1, 1).subscribe((result: any) => {
this.historyCount = this.recordService.totalHits(result.hits.total);
});
// Load count history only if the patron has keep history
if (patron.keep_history) {
this.operationLogsApiService.getCheckInHistory(patron.pid, 1, 1).subscribe((result: any) => {
this.historyCount = this.recordService.totalHits(result.hits.total);
});
}
this.patronService.getCirculationInformations(patron.pid).subscribe((data) => {
this.circulationService.clear();
this.feesTotalAmount = data.fees.engaged + data.fees.preview;
Expand Down
8 changes: 4 additions & 4 deletions projects/admin/src/app/classes/items.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* RERO ILS UI
* Copyright (C) 2019 RERO
* Copyright (C) 2019-2024 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
Expand All @@ -18,9 +18,9 @@
/* tslint:disable */
// required as json properties is not lowerCamelCase

import { Moment } from 'moment';
import { ItemStatus, User } from '@rero/shared';
import { Loan } from './loans'
import { DateTime } from 'luxon';
import { Loan } from './loans';

export enum ItemNoteType {
GENERAL = 'general_note',
Expand Down Expand Up @@ -98,7 +98,7 @@ export class Item {
library: any;
library_location_name: any;
notes: ItemNote[];
acquisition_date: Moment;
acquisition_date: DateTime;
enumerationAndChronology: string;
temporary_location?: any;

Expand Down
24 changes: 12 additions & 12 deletions projects/admin/src/app/classes/library.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* RERO ILS UI
* Copyright (C) 2019-2023 RERO
* Copyright (C) 2019-2024 RERO
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
Expand All @@ -19,9 +19,9 @@
// required as json properties is not lowerCamelCase

import { WeekDay } from '@angular/common';
import * as moment from 'moment';
import { NotificationType } from './notification';
import { WeekDays } from './week-days';
import { DateTime } from 'luxon';


export interface OpeningHours {
Expand Down Expand Up @@ -136,7 +136,7 @@ export class Library {
}
return exception;
});
this.exception_dates = this.exception_dates.sort((a, b) => moment(a.start_date) - moment(b.start_date));
this.exception_dates = this.exception_dates.sort((a, b) => DateTime.fromISO(a.start_date) - DateTime.fromISO(b.start_date));
}

/**
Expand Down Expand Up @@ -165,8 +165,8 @@ export class Library {
if (exception.repeat && checkRepeat) {
return false;
}
const checked_date = (exception.end_date) ? moment(exception.end_date) : moment(exception.start_date);
return checked_date < moment();
const checked_date = (exception.end_date) ? DateTime.fromISO(exception.end_date) : DateTime.fromISO(exception.start_date);
return checked_date < DateTime.now();
}

// PRIVATE METHODS ================================================
Expand Down Expand Up @@ -201,7 +201,7 @@ export class Library {
this.opening_hours.forEach(opening => {
if (opening.times.length > 1) {
opening.times.sort((a, b) =>
moment(a.start_time, 'HH:mm').diff(moment(b.start_time, 'HH:mm')));
DateTime.fromFormat(a.start_time, 'HH:mm').diff(DateTime.fromFormat(b.start_time, 'HH:mm')));
}
});
}
Expand All @@ -216,13 +216,13 @@ export class Library {
if (!exception.repeat) {
throw new Error('Unable to increment not repeatable exception date.');
}
const momentJsUnitMapper = {daily: 'd', weekly: 'w', monthly: 'M', yearly: 'y'};
const unity = (momentJsUnitMapper.hasOwnProperty(exception.repeat.period))
? momentJsUnitMapper[exception.repeat.period]
: 'd';
exception.start_date = moment(exception.start_date).add(exception.repeat.interval, unity).format('YYYY-MM-DD');
const jsUnitMapper = {daily: 'days', weekly: 'weeks', monthly: 'months', yearly: 'years'};
const unity = (jsUnitMapper.hasOwnProperty(exception.repeat.period))
? jsUnitMapper[exception.repeat.period]
: 'days';
exception.start_date = DateTime.fromFormat(exception.start_date).plus({ [unity]: exception.repeat.interval }).format('yyyy-LL-dd');
if (exception.end_date) {
exception.end_date = moment(exception.end_date).add(exception.repeat.interval, unity).format('YYYY-MM-DD');
exception.end_date = DateTime.fromFormat(exception.end_date).plus({ [unity]: exception.repeat.interval }).format('yyyy-LL-dd');
}
return exception;
}
Expand Down
Loading

0 comments on commit a8a9afd

Please sign in to comment.