From ad5dd208f24138b84a22bd5c7d28c48e06bf6d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chlo=C3=A9=20Zermatten?= Date: Tue, 13 Aug 2024 14:15:44 +0000 Subject: [PATCH] Bug 10190: Complete Vue.js rewrite of Circulation Triggers administration interface This patch introduces a modern Vue.js-based interface for managing circulation triggers (overdue notice/status triggers), replacing the legacy Tools-based interface with a more intuitive, feature-rich administration page. New Features Enhanced Visibility & Navigation - Exhaustive effective rule lists showing all rules that apply to each context - Toggle between "all exhaustive rules" and "explicitly set rules" views - Advanced filtering by patron category and/or item type - Clear display of fallback/default rules for each context Rule Management Actions - Delete triggers (last trigger in a sequence for any given library) - Reset entire rule sets for a given context (with safeguards) - Edit existing triggers with improved context awareness - Add new triggers with intelligent delay constraints Improved User Experience - Multi-step form wizard with clear workflow progression - Context-aware letter template filtering (only shows applicable templates) - Placeholder values showing fallback rules when clearing inputs - Dynamic min/max constraints for delay values based on neighboring triggers - Real-time form validation and feedback - Partial page reloads (only reload affected sections, not entire page) - Specific loading messages for different operations Technical Improvements - Centralized Vuex store for state management - Reusable CirculationTriggersForm component - API clients for libraries, circulation rules, item types, and patron categories - Consistent async/await pattern throughout - Separation of repositories, utilities, and services - Improved naming consistency and code maintainability - "Dumb" TriggersTable component for better separation of concerns Test Plan Prerequisites 1. Log in to staff interface with appropriate permissions (tools_edit_notice_status_triggers) 2. Ensure you have test data: multiple libraries, patron categories, item types, and notice templates 3. Navigate to Administration > Circulation triggers (new interface) Part 1: Basic Navigation & Interface 1. Verify the new "Circulation triggers" link appears in Administration home under the Circulation section 2. Access the new interface and confirm it loads successfully 3. Verify the default view shows either "All libraries" or your logged-in library based on DefaultToLoggedInLibraryOverdueTriggers system preference 4. Confirm the interface displays a list of triggers organized by context (library/patron category/item type combinations) Part 2: Viewing and Filtering Rules 1. Toggle between "All exhaustive rules" and "Explicitly set rules" views - Verify "All exhaustive rules" shows inherited/fallback rules - Verify "Explicitly set rules" shows only rules you've specifically configured 2. Test the patron category filter: - Select a specific patron category - Confirm only rules for that category are displayed 3. Test the item type filter: - Select a specific item type - Confirm only rules for that item type are displayed 4. Test combined filters (patron category + item type simultaneously) 5. Clear filters and verify all rules display again Part 3: Adding New Triggers 1. Click "Add trigger" button 2. Step 1 - Confirm Context: - Select Library (required) - Select Patron category (required) - Select Item type (required) - Click "Confirm context" 3. Step 2 - Review Existing Triggers: - Verify existing triggers for this context are displayed - Note the trigger numbers and delays 4. Step 3 - Configure New Trigger: - Enter a delay value (should be constrained by neighboring triggers) - Try entering an invalid delay (too low or too high) - verify validation - Set "Restricts checkouts" (Yes/No/Fallback to default) - Note the placeholder showing the fallback value - Select a letter template - Verify only templates for the selected library context appear - Set "Debarring" options if desired - Select "Charged notice fees" if applicable 5. Submit the form 6. Verify the new trigger appears in the list without a full page reload 7. Verify success message is displayed Part 4: Editing Existing Triggers 1. Locate an existing trigger in the list 2. Click the edit icon/button 3. Verify the form pre-populates with existing values 4. Test delay modification: - Try changing the delay within valid bounds - should succeed - Try changing delay beyond neighboring triggers - should show validation error - Use the increment/decrement buttons to adjust delay 5. Test clearing values: - Clear a field (e.g., delay or restrict checkouts) - Verify placeholder shows the fallback/default value - Submit with cleared value - should save as null and inherit fallback 6. Change the letter template to a different valid template 7. Submit changes 8. Verify the trigger updates in the list without full page reload 9. Verify the changes persist after refreshing the page Part 5: Deleting Triggers 1. Identify a trigger that is the last in its sequence 2. Click the delete button/icon 3. Verify a confirmation dialog appears 4. Confirm deletion 5. Verify the trigger is removed from the list without page reload 6. Verify the deletion persists after page refresh 7. Test delete constraints: - Try to delete a trigger that's not the last in sequence - Verify appropriate error/warning message Part 6: Resetting Rule Sets 1. Locate a context with explicitly set rules (not just inherited) 2. Ensure this is not the only rule set for this trigger sequence 3. Click the "Reset" button for that context 4. Verify confirmation dialog explains what will be reset 5. Confirm the reset 6. Verify the explicit rules are removed and context now shows inherited rules 7. Verify changes persist after page refresh 8. Test reset constraints: - Try to reset when it would leave no rules for that trigger - Verify appropriate warning/prevention Part 7: Context-Specific Behavior 1. Test library-specific letter filtering: - Create/edit a trigger for a specific library - Verify only letter templates with matching branchcode or default templates appear - Switch to a different library context - Verify the letter list updates accordingly 2. Test default rules: - View rules for "All libraries" / "All patron categories" / "All item types" - Verify these are labeled as "Default rule for [context]" - Confirm these serve as fallback for more specific rules 3. Test DefaultToLoggedInLibraryOverdueTriggers preference: - Set preference to "Yes" - Reload circulation triggers page - Verify it defaults to your logged-in library - Set preference to "No" - Verify it defaults to "All libraries" Part 8: Form Workflow & Validation 1. Test required fields: - Try submitting add/edit form without selecting library - should fail - Try submitting without patron category - should fail - Try submitting without item type - should fail 2. Test stepper navigation: - Start adding a trigger - Verify you must confirm context before proceeding - Verify you see existing triggers before editing/adding - Verify trigger form only appears after context confirmation 3. Test cancellation: - Start adding/editing a trigger - Click Cancel - Verify you return to the list without changes - Verify no partial data was saved Part 9: Loading States & Messages 1. On slow connections or with many rules: - Verify "Loading context..." appears while fetching context data - Verify "Loading rule set information..." appears while fetching rules - Verify section-specific loading messages appear during updates 2. After form submission: - Verify appropriate success/error messages display - Verify loading indicators during async operations Part 10: Permissions 1. Log in as a user without tools_edit_notice_status_triggers permission 2. Verify the "Circulation triggers" link does not appear in Administration 3. Try accessing /cgi-bin/koha/admin/circulation_triggers directly 4. Verify access is denied Part 11: Data Integrity & Persistence 1. Create a complex set of rules with multiple triggers across different contexts 2. Refresh the page and verify all rules persist 3. Restart the Koha services 4. Verify all rules still display correctly 5. Check the database circulation_rules table: - Verify rules are stored with correct rule_name pattern (overdue_1_delay, etc.) - Verify null values are properly stored for inheritance - Verify the overdue_X_has_rules rule kind is present Part 12: Edge Cases 1. Test with no existing triggers - verify empty state message 2. Test with maximum trigger sequences (e.g., trigger 1, 2, 3) 3. Test rapid successive edits 4. Test with special characters in letter template names 5. Test browser back/forward buttons during form workflow Part 13: Comparison with Legacy Interface 1. Access the old interface if still available (via Tools menu) 2. Create a trigger using the new interface 3. Verify it appears correctly in the old interface (if applicable) 4. Create a trigger using the old interface (if still available) 5. Verify it appears correctly in the new interface --- Notes for QA - This is a complete UI rewrite; the underlying API remains unchanged - The interface is mobile-responsive and should be tested on various screen sizes - Vue.js components are compiled via Rspack; run yarn build after pulling - All existing circulation trigger functionality should continue to work - The URL rewrite rule ensures /admin/circulation_triggers routes correctly Sponsored-by: Glasgow Colleges Library Group Co-authored-by: Matt Blenkinsop Co-authored-by: Martin Renvoize Signed-off-by: George Harkins --- Koha/CirculationRules.pm | 4 + admin/circulation_triggers.pl | 43 + debian/templates/apache-shared-intranet.conf | 1 + .../prog/en/modules/admin/admin-home.tt | 4 + .../en/modules/admin/circulation_triggers.tt | 43 + .../js/fetch/circulation-rules-api-client.js | 36 + .../prog/js/fetch/item-api-client.js | 11 + .../prog/js/fetch/library-api-client.js | 25 + .../prog/js/fetch/patron-api-client.js | 16 +- .../CirculationTriggersForm.vue | 44 + .../CirculationTriggersFormAdd.vue | 1008 +++++++++++++++++ .../CirculationTriggersFormConfirmReset.vue | 487 ++++++++ ...lationTriggersFormConfirmTriggerDelete.vue | 257 +++++ .../CirculationTriggersList.vue | 503 ++++++++ .../Admin/CirculationTriggers/Main.vue | 69 ++ .../CirculationTriggers/TriggerContext.vue | 50 + .../CirculationTriggers/TriggersTable.vue | 357 ++++++ .../prog/js/vue/fetch/api-client.js | 4 + .../vue/modules/admin/circulation_triggers.ts | 57 + .../vue/routes/admin/circulation_triggers.js | 91 ++ .../prog/js/vue/stores/circulation-rules.js | 486 ++++++++ rspack.config.js | 4 +- 22 files changed, 3597 insertions(+), 3 deletions(-) create mode 100644 admin/circulation_triggers.pl create mode 100644 koha-tmpl/intranet-tmpl/prog/en/modules/admin/circulation_triggers.tt create mode 100644 koha-tmpl/intranet-tmpl/prog/js/fetch/circulation-rules-api-client.js create mode 100644 koha-tmpl/intranet-tmpl/prog/js/fetch/library-api-client.js create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersForm.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormAdd.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmReset.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmTriggerDelete.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersList.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/Main.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggerContext.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggersTable.vue create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/circulation_triggers.ts create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/routes/admin/circulation_triggers.js create mode 100644 koha-tmpl/intranet-tmpl/prog/js/vue/stores/circulation-rules.js diff --git a/Koha/CirculationRules.pm b/Koha/CirculationRules.pm index 86863a0f019..6fdd1501339 100644 --- a/Koha/CirculationRules.pm +++ b/Koha/CirculationRules.pm @@ -190,6 +190,10 @@ our $RULE_KINDS = { scope => [ 'branchcode', 'categorycode', 'itemtype' ], can_be_blank => 0, }, + overdue_X_has_rules => { + scope => [ 'branchcode', 'categorycode', 'itemtype' ], + can_be_blank => 0, + }, renewalperiod => { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, diff --git a/admin/circulation_triggers.pl b/admin/circulation_triggers.pl new file mode 100644 index 00000000000..6a09f5b86c2 --- /dev/null +++ b/admin/circulation_triggers.pl @@ -0,0 +1,43 @@ +#!/usr/bin/perl + +# Copyright 2024 PTFS Europe Ltd +# +# This file is part of Koha. +# +# Koha is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# Koha 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Koha; if not, see . + +use Modern::Perl; + +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); + +my $query = CGI->new; + +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/circulation_triggers.tt", + query => $query, + type => "intranet", + } +); + +my $letters = Koha::Notice::Templates->search( + { module => "circulation", lang => 'default' }, + { columns => [ 'module', 'code', 'branchcode', 'name' ] } +)->unblessed; + +$template->param( letters => $letters ); + +output_html_with_http_headers $query, $cookie, $template->output; diff --git a/debian/templates/apache-shared-intranet.conf b/debian/templates/apache-shared-intranet.conf index ad001458325..86fc33bc983 100644 --- a/debian/templates/apache-shared-intranet.conf +++ b/debian/templates/apache-shared-intranet.conf @@ -27,6 +27,7 @@ RewriteRule ^/cgi-bin/koha/admin/record_sources(.*)?$ /cgi-bin/koha/admin/record RewriteCond %{QUERY_STRING} booksellerid=(.*) RewriteRule ^/cgi-bin/koha/acqui/supplier.pl$ /cgi-bin/koha/acquisition/vendors/%1? [R] RewriteRule ^/cgi-bin/koha/acquisition/vendors(.*)?$ /cgi-bin/koha/acqui/vendors.pl$1 [PT] +RewriteRule ^/cgi-bin/koha/admin/circulation_triggers(.*)?$ /cgi-bin/koha/admin/circulation_triggers.pl$1 [PT] Alias "/api" "/usr/share/koha/api" diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/admin-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/admin-home.tt index bf92a4c1f8c..08a70eb5262 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/admin-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/admin-home.tt @@ -96,6 +96,10 @@
Circulation and fine rules
Define circulation and fine rules for combinations of libraries, patron categories, and item types
[% END %] + [% IF ( CAN_user_tools_edit_notice_status_triggers ) %] +
Circulation triggers
+
Define triggers for circulation notices
+ [% END %] [% IF ( CAN_user_parameters_manage_patron_attributes ) %]
Patron attribute types
Define extended attributes (identifiers and statistical categories) for patron records
diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/circulation_triggers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/circulation_triggers.tt new file mode 100644 index 00000000000..d2f11c99cc4 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/circulation_triggers.tt @@ -0,0 +1,43 @@ +[% USE raw %] +[% USE To %] +[% USE Asset %] +[% USE Branches %] +[% USE KohaDates %] +[% USE TablesSettings %] +[% USE AuthorisedValues %] +[% SET footerjs = 1 %] +[% PROCESS 'i18n.inc' %] +[% INCLUDE 'doc-head-open.inc' %] +[% FILTER collapse %] + [% t("Circulation triggers") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] +[% INCLUDE 'doc-head-close.inc' %] + + + +[% WRAPPER 'header.inc' %] + [% INCLUDE 'prefs-admin-search.inc' %] +[% END %] + +
+ + + [% MACRO jsinclude BLOCK %] + [% INCLUDE 'calendar.inc' %] + + [% INCLUDE 'datatables.inc' %] + [% INCLUDE 'js-patron-format.inc' %] + [% INCLUDE 'js-date-format.inc' %] + + [% Asset.js("js/vue/dist/admin/circulation_triggers.js") | $raw %] + [% END %] + + [% INCLUDE 'intranet-bottom.inc' %]
diff --git a/koha-tmpl/intranet-tmpl/prog/js/fetch/circulation-rules-api-client.js b/koha-tmpl/intranet-tmpl/prog/js/fetch/circulation-rules-api-client.js new file mode 100644 index 00000000000..ccb1c2c1623 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/fetch/circulation-rules-api-client.js @@ -0,0 +1,36 @@ +export class CircRuleAPIClient { + constructor(HttpClient) { + this.httpClient = new HttpClient({ + baseURL: "/api/v1/circulation_rules", + }); + } + + get circRules() { + return { + getAll: (query, params, headers) => + this.httpClient.getAll({ + endpoint: "", + query, + params, + headers, + }), + update: rule => + this.httpClient.put({ + endpoint: "", + body: rule, + }), + count: (query = {}) => + this.httpClient.count({ + endpoint: + "?" + + new URLSearchParams({ + _page: 1, + _per_page: 1, + ...(query && { q: JSON.stringify(query) }), + }), + }), + }; + } +} + +export default CircRuleAPIClient; diff --git a/koha-tmpl/intranet-tmpl/prog/js/fetch/item-api-client.js b/koha-tmpl/intranet-tmpl/prog/js/fetch/item-api-client.js index 84b9b8c3704..cd9af06923f 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/fetch/item-api-client.js +++ b/koha-tmpl/intranet-tmpl/prog/js/fetch/item-api-client.js @@ -16,6 +16,17 @@ export class ItemAPIClient { }), }; } + get itemTypes() { + return { + getAll: (query, params, headers) => + this.httpClient.getAll({ + endpoint: "item_types", + query, + params, + headers, + }), + }; + } } export default ItemAPIClient; diff --git a/koha-tmpl/intranet-tmpl/prog/js/fetch/library-api-client.js b/koha-tmpl/intranet-tmpl/prog/js/fetch/library-api-client.js new file mode 100644 index 00000000000..01d34db3343 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/fetch/library-api-client.js @@ -0,0 +1,25 @@ +export class LibraryAPIClient { + constructor(HttpClient) { + this.httpClient = new HttpClient({ + baseURL: "/api/v1/libraries", + }); + } + + get libraries() { + return { + getAll: (query, params, headers) => + this.httpClient.getAll({ + endpoint: "", + query, + params, + headers, + }), + get: id => + this.httpClient.get({ + endpoint: `/${id}`, + }), + }; + } +} + +export default LibraryAPIClient; diff --git a/koha-tmpl/intranet-tmpl/prog/js/fetch/patron-api-client.js b/koha-tmpl/intranet-tmpl/prog/js/fetch/patron-api-client.js index 2ec8b8c2600..77b0a38e356 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/fetch/patron-api-client.js +++ b/koha-tmpl/intranet-tmpl/prog/js/fetch/patron-api-client.js @@ -1,7 +1,7 @@ export class PatronAPIClient { constructor(HttpClient) { this.httpClient = new HttpClient({ - baseURL: "/api/v1/patrons/", + baseURL: "/api/v1/", }); } @@ -9,7 +9,19 @@ export class PatronAPIClient { return { get: id => this.httpClient.get({ - endpoint: id, + endpoint: "patrons/" + id, + }), + }; + } + + get patronCategories() { + return { + getAll: (query, params, headers) => + this.httpClient.getAll({ + endpoint: "patron_categories", + query, + params, + headers, }), }; } diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersForm.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersForm.vue new file mode 100644 index 00000000000..25c0ba02986 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersForm.vue @@ -0,0 +1,44 @@ + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormAdd.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormAdd.vue new file mode 100644 index 00000000000..136fd55a0ee --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormAdd.vue @@ -0,0 +1,1008 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmReset.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmReset.vue new file mode 100644 index 00000000000..0c1e96286ae --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmReset.vue @@ -0,0 +1,487 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmTriggerDelete.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmTriggerDelete.vue new file mode 100644 index 00000000000..ccc989f754a --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersFormConfirmTriggerDelete.vue @@ -0,0 +1,257 @@ + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersList.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersList.vue new file mode 100644 index 00000000000..3060373d563 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/CirculationTriggersList.vue @@ -0,0 +1,503 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/Main.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/Main.vue new file mode 100644 index 00000000000..9a05c2d347c --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/Main.vue @@ -0,0 +1,69 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggerContext.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggerContext.vue new file mode 100644 index 00000000000..6be8bc94eda --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggerContext.vue @@ -0,0 +1,50 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggersTable.vue b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggersTable.vue new file mode 100644 index 00000000000..b79d5da7d51 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/components/Admin/CirculationTriggers/TriggersTable.vue @@ -0,0 +1,357 @@ + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/fetch/api-client.js b/koha-tmpl/intranet-tmpl/prog/js/vue/fetch/api-client.js index c12f54beebf..59863485f5f 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/vue/fetch/api-client.js +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/fetch/api-client.js @@ -2,6 +2,7 @@ import HttpClient from "./http-client"; import ERMAPIClient from "@fetch/erm-api-client"; import PatronAPIClient from "@fetch/patron-api-client"; +import LibraryAPIClient from "@fetch/library-api-client"; import AcquisitionAPIClient from "@fetch/acquisition-api-client"; import AdditionalFieldsAPIClient from "@fetch/additional-fields-api-client"; import AVAPIClient from "@fetch/authorised-values-api-client"; @@ -9,10 +10,12 @@ import ItemAPIClient from "@fetch/item-api-client"; import RecordSourcesAPIClient from "@fetch/record-sources-api-client"; import SysprefAPIClient from "@fetch/system-preferences-api-client"; import PreservationAPIClient from "@fetch/preservation-api-client"; +import CircRuleAPIClient from "@fetch/circulation-rules-api-client"; export const APIClient = { erm: new ERMAPIClient(HttpClient), patron: new PatronAPIClient(HttpClient), + library: new LibraryAPIClient(HttpClient), acquisition: new AcquisitionAPIClient(HttpClient), additional_fields: new AdditionalFieldsAPIClient(HttpClient), authorised_values: new AVAPIClient(HttpClient), @@ -20,4 +23,5 @@ export const APIClient = { sysprefs: new SysprefAPIClient(HttpClient), preservation: new PreservationAPIClient(HttpClient), record_sources: new RecordSourcesAPIClient(HttpClient), + circRule: new CircRuleAPIClient(HttpClient), }; diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/circulation_triggers.ts b/koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/circulation_triggers.ts new file mode 100644 index 00000000000..f5e6a50c50b --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/circulation_triggers.ts @@ -0,0 +1,57 @@ +import { createApp } from "vue"; +import { createPinia } from "pinia"; +import { createWebHistory, createRouter } from "vue-router"; + +import { library } from "@fortawesome/fontawesome-svg-core"; +import { + faPlus, + faMinus, + faPencil, + faTrash, + faSpinner, +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; +import vSelect from "vue-select"; +import { useNavigationStore } from "../../stores/navigation"; +import { useMainStore } from "../../stores/main"; +import { useCircRulesStore } from "../../stores/circulation-rules"; +import routesDef from "../../routes/admin/circulation_triggers"; + +library.add(faPlus, faMinus, faPencil, faTrash, faSpinner); + +const pinia = createPinia(); +const navigationStore = useNavigationStore(pinia); +const mainStore = useMainStore(pinia); +const circRulesStore = useCircRulesStore(pinia); +const { removeMessages } = mainStore; +const { setRoutes } = navigationStore; +const routes = setRoutes(routesDef); + +const router = createRouter({ + history: createWebHistory(), + linkExactActiveClass: "current", + routes, +}); + +import App from "../../components/Admin/CirculationTriggers/Main.vue"; +import i18n from "../../i18n"; + +const app = createApp(App); + +const rootComponent = app + .use(i18n) + .use(pinia) + .use(router) + .component("font-awesome-icon", FontAwesomeIcon) + .component("v-select", vSelect); + +app.config.unwrapInjectedRef = true; +app.provide("mainStore", mainStore); +app.provide("navigationStore", navigationStore); +app.provide("circRulesStore", circRulesStore); +app.mount("#__app"); + +router.beforeEach(to => { + navigationStore.$patch({ current: to.matched, params: to.params || {} }); + removeMessages(); // This will actually flag the messages as displayed already +}); diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/routes/admin/circulation_triggers.js b/koha-tmpl/intranet-tmpl/prog/js/vue/routes/admin/circulation_triggers.js new file mode 100644 index 00000000000..e3d5a9cc587 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/routes/admin/circulation_triggers.js @@ -0,0 +1,91 @@ +import { markRaw } from "vue"; +import { $__ } from "../../i18n"; + +import CirculationTriggersList from "../../components/Admin/CirculationTriggers/CirculationTriggersList.vue"; +import CirculationTriggersFormAdd from "../../components/Admin/CirculationTriggers/CirculationTriggersFormAdd.vue"; +import CirculationTriggersFormConfirmReset from "../../components/Admin/CirculationTriggers/CirculationTriggersFormConfirmReset.vue"; +import CirculationTriggersFormConfirmTriggerDelete from "../../components/Admin/CirculationTriggers/CirculationTriggersFormConfirmTriggerDelete.vue"; + +export default { + title: $__("Administration"), + path: "", + href: "/cgi-bin/koha/admin/admin-home.pl", + is_base: true, + is_default: true, + children: [ + { + title: $__("Circulation triggers"), + path: "/cgi-bin/koha/admin/circulation_triggers", + children: [ + { + path: "", + name: "CirculationTriggersList", + component: markRaw(CirculationTriggersList), + title: $__("Home"), + children: [ + { + path: "confirmContext", + name: "CirculationTriggersFormConfirmContext", + component: markRaw(CirculationTriggersFormAdd), + title: $__("Confirm trigger context"), + meta: { + showModal: true, + }, + }, + { + path: "selectOrAdd", + name: "CirculationTriggersSelectOrAdd", + component: markRaw(CirculationTriggersFormAdd), + title: $__( + "Select a trigger to edit or select add" + ), + meta: { + showModal: true, + }, + }, + { + path: "add", + name: "CirculationTriggersFormAdd", + component: markRaw(CirculationTriggersFormAdd), + title: $__("Add new rule set"), + meta: { + showModal: true, + }, + }, + { + path: "edit", + name: "CirculationTriggersFormEdit", + component: markRaw(CirculationTriggersFormAdd), + title: $__("Edit rule set"), + meta: { + showModal: true, + }, + }, + { + path: "reset", + name: "CirculationTriggersFormConfirmReset", + component: markRaw( + CirculationTriggersFormConfirmReset + ), + title: $__("Confirm rule set reset"), + meta: { + showModal: true, + }, + }, + { + path: "delete", + name: "CirculationTriggersFormConfirmTriggerDelete", + component: markRaw( + CirculationTriggersFormConfirmTriggerDelete + ), + title: $__("Confirm trigger deletion"), + meta: { + showModal: true, + }, + }, + ], + }, + ], + }, + ], +}; diff --git a/koha-tmpl/intranet-tmpl/prog/js/vue/stores/circulation-rules.js b/koha-tmpl/intranet-tmpl/prog/js/vue/stores/circulation-rules.js new file mode 100644 index 00000000000..53d21f1f562 --- /dev/null +++ b/koha-tmpl/intranet-tmpl/prog/js/vue/stores/circulation-rules.js @@ -0,0 +1,486 @@ +import { defineStore } from "pinia"; +import { $__ } from "../i18n"; +import { APIClient } from "../fetch/api-client.js"; +import { isEqual } from "lodash"; + +export const useCircRulesStore = defineStore("circRules", { + // NOTES ON RULE SETS TYPES + // exhaustive: includes 'pure fallback' rules sets for contexts that no rules match. + // Format: [{overdue_X_: {value: mixed: isFallback: bool}}] + // effective: includes sets only for contexts for which one or more rule exists in the db. These sets will include fallbacks. + // Format: [{overdue_X_: }} + // raw: includes only the exact sets as they are found in the db + // Format: [{overdue_X_: }}] + state: () => ({ + // context + currentLibraryId: "*", + currentPatronCategoryId: null, + currentItemTypeId: null, + triggerCounts: { "*": 0 }, + // references + itemTypes: [], + libraries: [], + patronCategories: [], + letters: [], + ruleSuffixes: ["delay", "notice", "mtt", "restrict", "has_rules"], + transportTypes: [ + { code: "email", name: "Email" }, + { code: "sms", name: "SMS" }, + { code: "print", name: "Print" }, + ], + regex: /overdue_(\d+)_has_rules/, + // rule sets + allDefaultLibraryRawRuleSets: [], // source of truth for default library + allCurrentLibraryRawRuleSets: [], // source of truth for current library + allEffectiveRuleSets: [], // main data set for display explicitly set rules for current library + allExhaustiveEffectiveRuleSets: [], // main data set for display all applied rules for current library + currentAndDefaultRawRuleSets: [], // data set to identify effective rules from (combines allDefaultLibraryRawRuleSets and allCurrentLibraryRawRuleSets) + storeInitialized: false, + }), + actions: { + // controllers + async init() { + await this.getItemTypes(); + await this.getLibraries(); + await this.getPatronCategories(); + }, + // utilities + formatTriggerSpecificRuleSetForDisplay( + context, + triggerNumber, + includeFallbacks = true + ) { + const triggerSpecificRuleSet = { + context, + }; + this.ruleSuffixes.forEach(ruleSuffix => { + triggerSpecificRuleSet[ + `overdue_${triggerNumber}_${ruleSuffix}` + ] = this.findEffectiveRule( + context, + ruleSuffix, + triggerNumber, + includeFallbacks + ); + }); + triggerSpecificRuleSet.context = context; + return triggerSpecificRuleSet; + }, + handleContext(value, data, type, displayProperty = "name") { + const item = data.find(item => item[type] === value); + return item[displayProperty]; + }, + handleNotice(notice) { + const letter = this.letters.find(letter => letter.code === notice); + return letter ? letter.name : notice; + }, + handleRestrictions(value) { + if (!value) { + return; + } + return value === "1" ? $__("Yes") : $__("No"); + }, + handleTransport(value, type, noLetter) { + if (!value || noLetter) { + return ""; + } + return value.includes(type) ? $__("Yes") : $__("No"); + }, + hasConflict(oldRuleSet, newRuleSet, triggerNumber) { + if (!oldRuleSet) { + return false; + } + return ( + oldRuleSet.context.library_id !== + newRuleSet.context.library_id || + oldRuleSet.context.item_type_id !== + newRuleSet.context.item_type_id || + oldRuleSet.context.patron_category_id !== + newRuleSet.context.patron_category_id || + oldRuleSet[`overdue_${triggerNumber}_delay`] !== + newRuleSet[`overdue_${triggerNumber}_delay`] || + oldRuleSet[`overdue_${triggerNumber}_notice`] !== + newRuleSet[`overdue_${triggerNumber}_notice`] || + oldRuleSet[`overdue_${triggerNumber}_restrict`] !== + newRuleSet[`overdue_${triggerNumber}_restrict`] || + !isEqual( + oldRuleSet[`overdue_${triggerNumber}_mtt`], + newRuleSet[`overdue_${triggerNumber}_mtt`] + ) + ); + }, + isOnlyRuleSetForTrigger(triggerNumber) { + return ( + this.allCurrentLibraryRawRuleSets.filter( + ruleSet => ruleSet[`overdue_${triggerNumber}_has_rules`] + ).length === 1 + ); + }, + isLastTrigger(triggerNumber) { + return ( + parseInt(triggerNumber) === + this.triggerCounts[this.currentLibraryId] + ); + }, + // services + findEffectiveRule( + context, + ruleSuffix, + triggerNumber, + includeFallbacks = true + ) { + if ( + !this.currentAndDefaultRawRuleSets || + !Array.isArray(this.currentAndDefaultRawRuleSets) || + this.currentAndDefaultRawRuleSets.length === 0 + ) { + return { value: null, isFallback: true }; + } + // Check if the current ruleSet's value for the ruleSuffix is undefined + const existingRule = this.currentAndDefaultRawRuleSets.find( + ruleSet => + ruleSet[`overdue_${triggerNumber}_${ruleSuffix}`] !== + undefined && + ruleSet[`overdue_${triggerNumber}_${ruleSuffix}`] !== + null && + ruleSet?.context.library_id === context.library_id && + ruleSet?.context.patron_category_id === + context.patron_category_id && + ruleSet?.context.item_type_id === context.item_type_id + ); + + // if handling 'has_rules', stop here + if (ruleSuffix === "has_rules") { + return { + value: existingRule?.[`overdue_${triggerNumber}_has_rules`], + isFallback: + !existingRule?.[`overdue_${triggerNumber}_has_rules`], + }; + } + + // If the current ruleSet's value is not null, use it directly + if (existingRule !== undefined) { + return { + value: existingRule[ + `overdue_${triggerNumber}_${ruleSuffix}` + ], + isFallback: + !existingRule[`overdue_${triggerNumber}_has_rules`], + }; + } + + // If set to return a raw set, return + if (!includeFallbacks) { + return; + } + + // Filter ruleSets to only those with non-null values for the specified ruleSuffix + // and that are no excluded from the selected context + const relevantRules = this.currentAndDefaultRawRuleSets.filter( + ruleSet => + ruleSet[`overdue_${triggerNumber}_${ruleSuffix}`] !== + undefined && + ruleSet[`overdue_${triggerNumber}_${ruleSuffix}`] !== + null && + (ruleSet.context.library_id === context.library_id || + ruleSet.context.library_id === "*") && + (ruleSet.context.patron_category_id === + context.patron_category_id || + ruleSet.context.patron_category_id === "*") && + (ruleSet.context.item_type_id === context.item_type_id || + ruleSet.context.item_type_id === "*") + ); + + // Function to calculate specificity score + const getSpecificityScore = ruleSetContext => { + let score = 0; + if ( + ruleSetContext.library_id !== "*" && + ruleSetContext.library_id === context.library_id + ) + score += 4; + if ( + ruleSetContext.patron_category_id !== "*" && + ruleSetContext.patron_category_id === + context.patron_category_id + ) + score += 2; + if ( + ruleSetContext.item_type_id !== "*" && + ruleSetContext.item_type_id === context.item_type_id + ) + score += 1; + return score; + }; + + // Sort the ruleSets based on specificity score, descending + const sortedRules = relevantRules.sort((a, b) => { + return ( + getSpecificityScore(b.context) - + getSpecificityScore(a.context) + ); + }); + // If no ruleSet found, return null + if (sortedRules.length === 0) { + return { value: null, isFallback: true }; + } + // Get the value from the most specific ruleSet + const bestRule = sortedRules[0]; + return { + value: bestRule[`overdue_${triggerNumber}_${ruleSuffix}`], + isFallback: true, + }; + }, + setAllExhaustiveEffectiveRuleSets() { + // clear array + this.allExhaustiveEffectiveRuleSets = []; + // generate complete rule set list + this.patronCategories.forEach(category => { + this.itemTypes.forEach(itemType => { + const effectiveRuleSet = { + context: { + library_id: this.currentLibraryId, + patron_category_id: category.patron_category_id, + item_type_id: itemType.item_type_id, + }, + }; + for ( + let i = 1; + i <= this.triggerCounts[this.currentLibraryId]; + i++ + ) { + this.ruleSuffixes.forEach(ruleSuffix => { + effectiveRuleSet[`overdue_${i}_${ruleSuffix}`] = + this.findEffectiveRule( + effectiveRuleSet.context, + ruleSuffix, + i + ); + }); + } + this.allExhaustiveEffectiveRuleSets.push(effectiveRuleSet); + }); + }); + }, + setAllEffectiveRuleSets() { + // clear array + this.allEffectiveRuleSets = []; + // generate complete rule set list + this.allCurrentLibraryRawRuleSets.forEach(ruleSet => { + const effectiveRuleSet = { + context: { ...ruleSet.context }, + }; + for ( + let i = 1; + i <= this.triggerCounts[this.currentLibraryId]; + i++ + ) { + if (ruleSet[`overdue_${i}_has_rules`] === null) { + continue; + } + this.ruleSuffixes.forEach(ruleSuffix => { + effectiveRuleSet[`overdue_${i}_${ruleSuffix}`] = + this.findEffectiveRule( + ruleSet.context, + ruleSuffix, + i + ); + }); + } + this.allEffectiveRuleSets.push(effectiveRuleSet); + }); + }, + setEffectiveTriggerFilteredRuleSet(context) { + const effectiveTriggerFilteredRuleSets = []; + for ( + let i = 1; + i <= this.triggerCounts[this.currentLibraryId]; + i++ + ) { + const triggerSpecificRuleSet = + this.formatTriggerSpecificRuleSetForDisplay(context, i); + if (!triggerSpecificRuleSet) { + continue; + } + effectiveTriggerFilteredRuleSets.push(triggerSpecificRuleSet); + } + return effectiveTriggerFilteredRuleSets; + }, + updateTriggerCount() { + // Library-specific triggerCounts can fall into the following use cases: + // - No rule sets specific to them exist. Therefore, their triggerCount is the same as default's. + // - Rule sets exists that override default triggers. Therefore, their triggerCount is the same as default's. + // - Rule sets exists for triggers for which there is no default. + // => such triggers are follow up addition to the existing default sequence. + // => the triggerCount for this library will be higher than default's, and equal to the highest trigger number for this library for which has_rules is not null. + + const ruleNames = Object.keys(this.allDefaultLibraryRawRuleSets[0]); + // Set the triggerCount for the default library rule set + if (this.currentLibraryId === "*") { + this.triggerCounts["*"] = ruleNames.filter( + ruleSuffix => + this.regex.test(ruleSuffix) && + this.allDefaultLibraryRawRuleSets.some( + ruleSet => ruleSet[ruleSuffix] !== null + ) + ).length; + return; + } + + // Set a library-specific trigger count: no rule set exists -> simply use the default trigger count + if (this.allCurrentLibraryRawRuleSets.length === 0) { + this.triggerCounts[this.currentLibraryId] = + this.triggerCounts["*"]; + return; + } + + // Set a library-specific trigger count: at least one rule set exists -> start from the first trigger for which there is no default rule set + let i = this.triggerCounts["*"] + 1; + while ( + ruleNames.includes(`overdue_${i}_has_rules`) && + this.allCurrentLibraryRawRuleSets.some( + ruleSet => ruleSet[`overdue_${i}_has_rules`] !== null + ) + ) { + i++; + } + this.triggerCounts[this.currentLibraryId] = i - 1; + }, + async setAllRawRuleSets() { + const client = APIClient.circRule; + try { + await this.getAllRawRuleSets(); + } catch (e) { + //TODO: handle e + } + this.currentAndDefaultRawRuleSets = [ + ...this.allCurrentLibraryRawRuleSets, + ...this.allDefaultLibraryRawRuleSets, + ]; + }, + // repositories + async deleteRuleSet(ruleSet, triggerNumber) { + const ruleSetInDb = await this.getSelectedRuleSet(ruleSet.context); + + if (this.hasConflict(ruleSet, ruleSetInDb, triggerNumber)) { + throw "The rule set for the selected trigger context could not be reset as it was updated elsewhere. Please see the updated trigger above."; + } + + const rulesForDeletion = { context: ruleSet.context }; + + if (ruleSet[`overdue_${triggerNumber}_delay`] !== null) { + rulesForDeletion[`overdue_${triggerNumber}_delay`] = null; + } + if (ruleSet[`overdue_${triggerNumber}_notice`] !== null) { + rulesForDeletion[`overdue_${triggerNumber}_notice`] = null; + } + if (ruleSet[`overdue_${triggerNumber}_restrict`] !== null) { + rulesForDeletion[`overdue_${triggerNumber}_restrict`] = null; + } + if (ruleSet[`overdue_${triggerNumber}_mtt`] !== null) { + rulesForDeletion[`overdue_${triggerNumber}_mtt`] = null; + } + rulesForDeletion[`overdue_${triggerNumber}_has_rules`] = null; + this.updateCircRuleSets(rulesForDeletion, triggerNumber); + }, + async getAllRawRuleSets() { + const client = APIClient.circRule; + try { + this.allDefaultLibraryRawRuleSets = + await client.circRules.getAll( + {}, + { library_id: "*", effective: false } + ); + this.allCurrentLibraryRawRuleSets = + await client.circRules.getAll( + {}, + { library_id: this.currentLibraryId, effective: false } + ); + } catch (e) { + throw e; + } + }, + async getItemTypes() { + const client = APIClient.item; + let itemTypes = []; + try { + itemTypes = await client.itemTypes.getAll(); + } catch (e) { + // TODO: handle e + } + itemTypes.unshift({ + item_type_id: "*", + description: $__("Default rule for all item types"), + }); + this.itemTypes = itemTypes; + }, + async getLibraries() { + const client = APIClient.library; + let libraries = []; + try { + libraries = await client.libraries.getAll(); + } catch (e) { + // TODO: handle e + } + libraries.unshift({ + library_id: "*", + name: $__("Default rule for all libraries"), + }); + this.libraries = libraries; + }, + async getPatronCategories() { + const client = APIClient.patron; + let patronCategories = []; + try { + patronCategories = await client.patronCategories.getAll(); + } catch (e) { + // TODO: handle e + } + patronCategories.unshift({ + patron_category_id: "*", + name: $__("Default rule for all categories"), + }); + this.patronCategories = patronCategories; + }, + async getSelectedRuleSet(context, effective = false) { + if (context.library_id === null) { + context.library_id = "*"; + } + const client = APIClient.circRule; + let result; + try { + result = await client.circRules.getAll( + {}, + { + library_id: context.library_id, + patron_category_id: context.patron_category_id, + item_type_id: context.item_type_id, + effective, + } + ); + } catch (e) { + throw e; + } + return result[0] ?? null; + }, + async updateCircRuleSets(existingRuleSet, triggerNumber) { + const circRuleSet = { context: existingRuleSet.context }; + circRuleSet[`overdue_${triggerNumber}_delay`] = + existingRuleSet[`overdue_${triggerNumber}_delay`]; + circRuleSet[`overdue_${triggerNumber}_notice`] = + existingRuleSet[`overdue_${triggerNumber}_notice`]; + circRuleSet[`overdue_${triggerNumber}_restrict`] = + existingRuleSet[`overdue_${triggerNumber}_restrict`]; + circRuleSet[`overdue_${triggerNumber}_mtt`] = + existingRuleSet[`overdue_${triggerNumber}_mtt`]; + circRuleSet[`overdue_${triggerNumber}_has_rules`] = + existingRuleSet[`overdue_${triggerNumber}_has_rules`]; + try { + const client = APIClient.circRule; + await client.circRules.update(circRuleSet); + } catch (e) { + //TODO: handle e + } + }, + }, +}); diff --git a/rspack.config.js b/rspack.config.js index e05273fb7b5..a57414f5c6c 100644 --- a/rspack.config.js +++ b/rspack.config.js @@ -27,7 +27,9 @@ module.exports = [ acquisitions: "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/acquisitions.ts", islands: "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/islands.ts", - }, + "admin/circulation_triggers": + "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/circulation_triggers.ts", + }, output: { filename: "[name].js", path: path.resolve( -- 2.51.0