From 2858f6e0ee53d123c079933d6d41509499cf976c Mon Sep 17 00:00:00 2001
From: Julian Maurice <julian.maurice@biblibre.com>
Date: Wed, 16 May 2012 15:19:15 +0200
Subject: [PATCH] Bug 7292: More granular permissions for claiming orders

Add a new permission order_claim_for_all.
Without this permission, user can only claim for orders in baskets he's
authorised to manage (depends on bug 7295)
---
 acqui/lateorders.pl                                |   89 +++++++++++++++-----
 .../data/mysql/de-DE/mandatory/userpermissions.sql |    1 +
 .../data/mysql/en/mandatory/userpermissions.sql    |    1 +
 .../data/mysql/es-ES/mandatory/userpermissions.sql |    1 +
 .../mysql/fr-FR/1-Obligatoire/userpermissions.sql  |    1 +
 .../data/mysql/it-IT/necessari/userpermissions.sql |    1 +
 .../mysql/nb-NO/1-Obligatorisk/userpermissions.sql |    1 +
 .../data/mysql/pl-PL/mandatory/userpermissions.sql |    1 +
 .../ru-RU/mandatory/permissions_and_user_flags.sql |    1 +
 .../uk-UA/mandatory/permissions_and_user_flags.sql |    1 +
 installer/data/mysql/updatedatabase.pl             |   11 +++
 .../prog/en/modules/acqui/lateorders.tt            |   15 +++-
 12 files changed, 100 insertions(+), 24 deletions(-)

diff --git a/acqui/lateorders.pl b/acqui/lateorders.pl
index 35ebec1..fab49ee 100755
--- a/acqui/lateorders.pl
+++ b/acqui/lateorders.pl
@@ -42,8 +42,7 @@ To know on which branch this script have to display late order.
 
 =cut
 
-use strict;
-use warnings;
+use Modern::Perl;
 use CGI;
 use C4::Bookseller qw( GetBooksellersWithLateOrders );
 use C4::Auth;
@@ -55,15 +54,36 @@ use C4::Letters;
 use C4::Branch; # GetBranches
 
 my $input = new CGI;
-my ($template, $loggedinuser, $cookie) = get_template_and_user({
-	template_name => "acqui/lateorders.tmpl",
-	query => $input,
-	 type => "intranet",
-	authnotrequired => 0,
-	flagsrequired => {acquisition => 'order_receive'},
-	debug => 1,
+my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
+    template_name => "acqui/lateorders.tt",
+    query => $input,
+    type => "intranet",
+    authnotrequired => 0,
+    flagsrequired => {acquisition => '*'},
+    debug => 1,
 });
 
+# Check if user has rights to access this page
+my $can_claim_for_all = 0;
+if ($userflags->{superlibrarian}
+    or (!ref $userflags->{acquisition} and $userflags->{acquisition})
+    or (ref $userflags->{acquisition}
+        and $userflags->{acquisition}->{order_claim_for_all}
+    )
+) {
+    $can_claim_for_all = 1;
+}
+
+if ( !$can_claim_for_all
+    and (
+        ref $userflags->{acquisition}
+        and not $userflags->{acquisition}->{order_receive}
+    )
+) {
+    # Will fail to authenticate, so redirect to login screen
+    checkauth($input, 0, { acquisition => 'order_receive' }, "intranet");
+}
+
 my $booksellerid = $input->param('booksellerid') || undef; # we don't want "" or 0
 my $delay      = $input->param('delay');
 my $estimateddeliverydatefrom = $input->param('estimateddeliverydatefrom');
@@ -77,21 +97,39 @@ if ( $delay and not $delay =~ /^\d{1,3}$/ ) {
 }
 
 if ($op and $op eq "send_alert"){
-    my @ordernums = $input->param("claim_for");# FIXME: Fallback values?
-    my $err;
-    eval {
-        $err = SendAlerts( 'claimacquisition', \@ordernums, $input->param("letter_code") );    # FIXME: Fallback value?
-        if ( not ref $err or not exists $err->{error} ) {
-            AddClaim ( $_ ) for @ordernums;
+    my @claim_for = $input->param('claim_for'); # FIXME: Fallback values?
+    my (@ordernums, @not_claimed);
+    if (not $can_claim_for_all) {
+        foreach my $ordernumber (@claim_for) {
+            my $order = GetOrder($ordernumber);
+            if (CanUserManageBasket($loggedinuser, $order->{basketno}, $userflags)) {
+                push @ordernums, $ordernumber;
+            } else {
+                push @not_claimed, $ordernumber;
+            }
         }
-    };
-    if ( $@ ) {
-        $template->param(error_claim => $@);
-    } elsif ( ref $err and exists $err->{error} and $err->{error} eq "no_email" ) {
-        $template->{VARS}->{'error_claim'} = "no_email";
     } else {
-        $template->{VARS}->{'info_claim'} = 1;
+        @ordernums = @claim_for;
     }
+    if (scalar @ordernums > 0) {
+        my $err;
+        eval {
+            $err = SendAlerts( 'claimacquisition', \@ordernums, $input->param("letter_code") );    # FIXME: Fallback value?
+            if ( not ref $err or not exists $err->{error} ) {
+                foreach my $ordernumber (@ordernums) {
+                    AddClaim($ordernumber);
+                }
+            }
+        };
+        if ( $@ ) {
+            $template->param(error_claim => $@);
+        } elsif ( ref $err and exists $err->{error} and $err->{error} eq "no_email" ) {
+            $template->param(error_claim => "no_email");
+        } else {
+            $template->param(info_claim => 1);
+        }
+    }
+    $template->param(not_claimed => \@not_claimed);
 }
 
 my %supplierlist = GetBooksellersWithLateOrders(
@@ -121,8 +159,13 @@ my @lateorders = GetLateOrders(
 );
 
 my $total;
-foreach (@lateorders){
-	$total += $_->{subtotal};
+foreach my $order (@lateorders){
+    if ( (not $can_claim_for_all)
+        and (not CanUserManageBasket($loggedinuser, $order->{basketno}, $userflags))
+    ) {
+        $order->{cannot_claim} = 1;
+    }
+    $total += $order->{subtotal};
 }
 
 my @letters;
diff --git a/installer/data/mysql/de-DE/mandatory/userpermissions.sql b/installer/data/mysql/de-DE/mandatory/userpermissions.sql
index b8e744f..d03d240 100644
--- a/installer/data/mysql/de-DE/mandatory/userpermissions.sql
+++ b/installer/data/mysql/de-DE/mandatory/userpermissions.sql
@@ -17,6 +17,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Bestellgruppen vewalten'),
    (11, 'order_receive', 'Lieferungen verwalten'),
    (11, 'budget_add_del', 'Konten hinzufügen/ändern, aber bestehende nicht ändern'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'Nachrichten für OPAC und Dienstoberfläche verfassen'),
    (13, 'label_creator', 'Etiketten und Barcodes aus Katalog- und Benutzerdaten erstellen'),
    (13, 'edit_calendar', 'Schließtage eintragen'),
diff --git a/installer/data/mysql/en/mandatory/userpermissions.sql b/installer/data/mysql/en/mandatory/userpermissions.sql
index 3517816..674e2df 100644
--- a/installer/data/mysql/en/mandatory/userpermissions.sql
+++ b/installer/data/mysql/en/mandatory/userpermissions.sql
@@ -17,6 +17,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Manage orders & basketgroups'),
    (11, 'order_receive', 'Manage orders & basket'),
    (11, 'budget_add_del', 'Add and delete budgets (but cant modify budgets)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
    (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
    (13, 'edit_calendar', 'Define days when the library is closed'),
diff --git a/installer/data/mysql/es-ES/mandatory/userpermissions.sql b/installer/data/mysql/es-ES/mandatory/userpermissions.sql
index 3517816..674e2df 100644
--- a/installer/data/mysql/es-ES/mandatory/userpermissions.sql
+++ b/installer/data/mysql/es-ES/mandatory/userpermissions.sql
@@ -17,6 +17,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Manage orders & basketgroups'),
    (11, 'order_receive', 'Manage orders & basket'),
    (11, 'budget_add_del', 'Add and delete budgets (but cant modify budgets)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'Write news for the OPAC and staff interfaces'),
    (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
    (13, 'edit_calendar', 'Define days when the library is closed'),
diff --git a/installer/data/mysql/fr-FR/1-Obligatoire/userpermissions.sql b/installer/data/mysql/fr-FR/1-Obligatoire/userpermissions.sql
index 3301f1d..57b5dae 100644
--- a/installer/data/mysql/fr-FR/1-Obligatoire/userpermissions.sql
+++ b/installer/data/mysql/fr-FR/1-Obligatoire/userpermissions.sql
@@ -33,6 +33,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Gérer les commandes et les bons de commande'),
    (11, 'order_receive', 'Gérer les réceptions'),
    (11, 'budget_add_del', 'Ajouter et supprimer les budgets (mais pas modifier)'),
+   (11, 'order_claim_for_all', 'Réclamer toutes les commandes'),
    (13, 'manage_csv_profiles', 'Gérer les profils d''export CSV'),
    (13, 'moderate_tags', 'Modérer les tags des adhérents'),
    (13, 'rotating_collections', 'Gérer les collections tournantes'),
diff --git a/installer/data/mysql/it-IT/necessari/userpermissions.sql b/installer/data/mysql/it-IT/necessari/userpermissions.sql
index 798a3ef..cbff5eb 100644
--- a/installer/data/mysql/it-IT/necessari/userpermissions.sql
+++ b/installer/data/mysql/it-IT/necessari/userpermissions.sql
@@ -19,6 +19,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Gestisci ordini e raccoglitori raggruppati'),
    (11, 'order_receive', 'Gestisci arrivi'),
    (11, 'budget_add_del', 'Aggiungi e cancella budgets (senza modificarli)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'Scrivi le news per l\'OPAC e per l\'interfaccia staff'),
    (13, 'label_creator', 'Crea etichette da stampare e barcodes dal catalogo e dai dati degli utenti'),
    (13, 'edit_calendar', 'Definisci i giorni di chiusura della biblioteca'),
diff --git a/installer/data/mysql/nb-NO/1-Obligatorisk/userpermissions.sql b/installer/data/mysql/nb-NO/1-Obligatorisk/userpermissions.sql
index 3793c51..b886e43 100644
--- a/installer/data/mysql/nb-NO/1-Obligatorisk/userpermissions.sql
+++ b/installer/data/mysql/nb-NO/1-Obligatorisk/userpermissions.sql
@@ -38,6 +38,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Administrere bestillinger og kurv-grupper'),
    (11, 'order_receive', 'Administrere bestillinger og kurver'),
    (11, 'budget_add_del', 'Legge til og slette budsjetter (men ikke endre budsjetter)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'Legge ut nyhter i OPACen og det interne grensesnittet'),
    (13, 'label_creator', 'Lage etiketter og strekkoder basert på bibliografiske poster og lånerdata'),
    (13, 'edit_calendar', 'Definere dager da biblioteket er stengt'),
diff --git a/installer/data/mysql/pl-PL/mandatory/userpermissions.sql b/installer/data/mysql/pl-PL/mandatory/userpermissions.sql
index c7e60fe..7e08376 100644
--- a/installer/data/mysql/pl-PL/mandatory/userpermissions.sql
+++ b/installer/data/mysql/pl-PL/mandatory/userpermissions.sql
@@ -17,6 +17,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Manage orders & basketgroups'),
    (11, 'order_receive', 'Manage orders & basket'),
    (11, 'budget_add_del', 'Add and delete budgets (but cant modify budgets)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news', 'RTworzeniei publikowanie wiadomości w interfejsie bibliotekarza i OPAC'),
    (13, 'label_creator', 'Create printable labels and barcodes from catalog and patron data'),
    (13, 'edit_calendar', 'Define days when the library is closed'),
diff --git a/installer/data/mysql/ru-RU/mandatory/permissions_and_user_flags.sql b/installer/data/mysql/ru-RU/mandatory/permissions_and_user_flags.sql
index 419c80d..7466ad9 100644
--- a/installer/data/mysql/ru-RU/mandatory/permissions_and_user_flags.sql
+++ b/installer/data/mysql/ru-RU/mandatory/permissions_and_user_flags.sql
@@ -41,6 +41,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Manage orders & basketgroups'),
    (11, 'order_receive', 'Manage orders & basket'),
    (11, 'budget_add_del', 'Add and delete budgets (but cant modify budgets)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news',                   'Написание новостей для электронного каталога и интерфейса библиотекарей'),
    (13, 'label_creator',               'Создание печатных наклеек и штрихкодов из каталога и с данными о пользователях'),
    (13, 'edit_calendar',               'Определение дней, когда библиотека закрыта'),
diff --git a/installer/data/mysql/uk-UA/mandatory/permissions_and_user_flags.sql b/installer/data/mysql/uk-UA/mandatory/permissions_and_user_flags.sql
index e26d782..02ef595 100644
--- a/installer/data/mysql/uk-UA/mandatory/permissions_and_user_flags.sql
+++ b/installer/data/mysql/uk-UA/mandatory/permissions_and_user_flags.sql
@@ -41,6 +41,7 @@ INSERT INTO permissions (module_bit, code, description) VALUES
    (11, 'group_manage', 'Manage orders & basketgroups'),
    (11, 'order_receive', 'Manage orders & basket'),
    (11, 'budget_add_del', 'Add and delete budgets (but cant modify budgets)'),
+   (11, 'order_claim_for_all', 'Claim for all orders'),
    (13, 'edit_news',                   'Написання новин для електронного каталогу та інтерфейсу бібліотекарів'),
    (13, 'label_creator',               'Створення друкованих наклейок і штрих-кодів з каталогу та з даними про користувачів'),
    (13, 'edit_calendar',               'Визначення днів, коли бібліотека закрита'),
diff --git a/installer/data/mysql/updatedatabase.pl b/installer/data/mysql/updatedatabase.pl
index eef1b05..42e648a 100755
--- a/installer/data/mysql/updatedatabase.pl
+++ b/installer/data/mysql/updatedatabase.pl
@@ -5280,6 +5280,17 @@ if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
 }
 
 
+$DBversion = "XXX";
+if ( C4::Context->preference("Version") < TransformToNum($DBversion) ) {
+    $dbh->do("
+        INSERT IGNORE INTO permissions (module_bit, code, description)
+        VALUES (11, 'order_claim_for_all', 'Claim for all orders')
+    ");
+
+    print "Upgrade to $DBversion done (Add permission order_claim_for_all)\n";
+    SetVersion($DBversion);
+}
+
 =head1 FUNCTIONS
 
 =head2 TableExists($table)
diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt
index cf54b03..416ae27 100644
--- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt
+++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt
@@ -43,6 +43,19 @@ $(document).ready(function() {
         <div class="error">[% error_claim %]</div>
     [% END %]
 [% END %]
+[% IF not_claimed.size %]
+    <div class="error">
+        <p>
+            The following orders were not claimed because you are not
+            authorised to claim for them:
+        </p>
+        <ul>
+            [% FOREACH ordernumber IN not_claimed %]
+                <li>[% ordernumber %]</li>
+            [% END %]
+        </ul>
+    </div>
+[% END %]
 [% IF info_claim %]
     <div class="dialog message">Email has been sent.</div>
 [% END %]
@@ -116,7 +129,7 @@ $(document).ready(function() {
             <td>[% lateorder.claims_count %]</td>
             <td>[% lateorder.claimed_date %]</td>
             <td>
-                [% UNLESS lateorder.budget_lock %]
+                [% UNLESS lateorder.cannot_claim %]
                     <input type="checkbox" class="checkbox" name="claim_for" value="[% lateorder.ordernumber %]"  booksellerid="[% lateorder.supplierid %]"/>
                 [% END %]
              </td>
-- 
1.7.10