ffzg/recall_notices.pl: added --interval and --dedup
[koha.git] / acqui / basketgroup.pl
index cdb392d..d29df74 100755 (executable)
@@ -8,18 +8,18 @@
 #
 # 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 2 of the License, or (at your option) any later
-# version.
+# 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.
+# 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, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 
 =head1 NAME
@@ -43,26 +43,26 @@ The bookseller who we want to display the baskets (and basketgroups) of.
 
 =cut
 
-use strict;
-use warnings;
+use Modern::Perl;
 use Carp;
 
-use C4::Input;
 use C4::Auth;
 use C4::Output;
-use CGI;
+use CGI qw ( -utf8 );
+use File::Spec;
 
-use C4::Bookseller qw/GetBookSellerFromId/;
-use C4::Budgets qw/ConvertCurrency/;
-use C4::Acquisition qw/CloseBasketgroup ReOpenBasketgroup GetOrders GetBasketsByBasketgroup GetBasketsByBookseller ModBasketgroup NewBasketgroup DelBasketgroup GetBasketgroups ModBasket GetBasketgroup GetBasket GetBasketGroupAsCSV/;
-use C4::Bookseller qw/GetBookSellerFromId/;
-use C4::Branch qw/GetBranches/;
-use C4::Members qw/GetMember/;
+use C4::Acquisition qw/CloseBasketgroup ReOpenBasketgroup GetOrders GetBasketsByBasketgroup GetBasketsByBookseller ModBasketgroup NewBasketgroup DelBasketgroup GetBasketgroups ModBasket GetBasketgroup GetBasket GetBasketGroupAsCSV get_rounded_price/;
+use Koha::EDI qw/create_edi_order get_edifact_ean/;
+
+use Koha::Biblioitems;
+use Koha::Acquisition::Booksellers;
+use Koha::ItemTypes;
+use Koha::Patrons;
 
 our $input=new CGI;
 
 our ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "acqui/basketgroup.tmpl",
+    = get_template_and_user({template_name => "acqui/basketgroup.tt",
                             query => $input,
                             type => "intranet",
                             authnotrequired => 0,
@@ -76,13 +76,13 @@ sub BasketTotal {
     my $total = 0;
     my @orders = GetOrders($basketno);
     for my $order (@orders){
-        $total = $total + ( $order->{ecost} * $order->{quantity} );
-        if ($bookseller->{invoiceincgst} && ! $bookseller->{listincgst} && ( $bookseller->{gstrate} // C4::Context->preference("gist") )) {
-            my $gst = $bookseller->{gstrate} // C4::Context->preference("gist");
-            $total = $total * ( $gst / 100 +1);
+        # FIXME The following is wrong
+        if ( $bookseller->listincgst ) {
+            $total = $total + ( get_rounded_price($order->{ecost_tax_included}) * $order->{quantity} );
+        } else {
+            $total = $total + ( get_rounded_price($order->{ecost_tax_excluded}) * $order->{quantity} );
         }
     }
-    $total .= " " . ($bookseller->{invoiceprice} // 0);
     return $total;
 }
 
@@ -119,34 +119,32 @@ sub displaybasketgroups {
         }
     }
     $template->param(baskets => $baskets);
-    $template->param( booksellername => $bookseller ->{'name'});
+    $template->param( booksellername => $bookseller->name);
 }
 
 sub printbasketgrouppdf{
     my ($basketgroupid) = @_;
-    
+
     my $pdfformat = C4::Context->preference("OrderPdfFormat");
-    if ($pdfformat eq 'pdfformat::layout3pages' || $pdfformat eq 'pdfformat::layout2pages' || $pdfformat eq 'pdfformat::layout3pagesfr'
-        || $pdfformat eq 'pdfformat::layout2pagesde'){
-       eval {
-        eval "require $pdfformat";
-           import $pdfformat;
-       };
-       if ($@){
-       }
+    my @valid_pdfformats = qw(pdfformat::layout3pages pdfformat::layout2pages pdfformat::layout3pagesfr pdfformat::layout2pagesde pdfformat::ffzg);
+    if (grep {$_ eq $pdfformat} @valid_pdfformats) {
+        $pdfformat = "Koha::$pdfformat";
+        my $pdfformat_filepath = File::Spec->catfile(split /::/, $pdfformat) . '.pm';
+        require $pdfformat_filepath;
+        import $pdfformat qw(printpdf);
     }
     else {
-       print $input->header;  
-       print $input->start_html;  # FIXME Should do a nicer page
-       print "<h1>Invalid PDF Format set</h1>";
-       print "Please go to the systempreferences and set a valid pdfformat";
-       exit;
+        print $input->header;
+        print $input->start_html;  # FIXME Should do a nicer page
+        print "<h1>Invalid PDF Format set</h1>";
+        print "Please go to the systempreferences and set a valid pdfformat";
+        exit;
     }
-    
+
     my $basketgroup = GetBasketgroup($basketgroupid);
-    my $bookseller = GetBookSellerFromId($basketgroup->{'booksellerid'});
+    my $bookseller = Koha::Acquisition::Booksellers->find( $basketgroup->{booksellerid} );
     my $baskets = GetBasketsByBasketgroup($basketgroupid);
-    
+
     my %orders;
     for my $basket (@$baskets) {
         my @ba_orders;
@@ -169,38 +167,21 @@ sub printbasketgrouppdf{
                 croak $@;
             }
 
-            $ord->{rrp} = ConvertCurrency( $ord->{'currency'}, $ord->{rrp} );
-            if ( $bookseller->{'listincgst'} ) {
-                $ord->{rrpgsti} = sprintf( "%.2f", $ord->{rrp} );
-                $ord->{gstgsti} = sprintf( "%.2f", $ord->{gstrate} * 100 );
-                $ord->{rrpgste} = sprintf( "%.2f", $ord->{rrp} / ( 1 + ( $ord->{gstgsti} / 100 ) ) );
-                $ord->{gstgste} = sprintf( "%.2f", $ord->{gstgsti} / ( 1 + ( $ord->{gstgsti} / 100 ) ) );
-                $ord->{ecostgsti} = sprintf( "%.2f", $ord->{ecost} );
-                $ord->{ecostgste} = sprintf( "%.2f", $ord->{ecost} / ( 1 + ( $ord->{gstgsti} / 100 ) ) );
-                $ord->{gstvalue} = sprintf( "%.2f", ( $ord->{ecostgsti} - $ord->{ecostgste} ) * $ord->{quantity});
-                $ord->{totalgste} = sprintf( "%.2f", $ord->{quantity} * $ord->{ecostgste} );
-                $ord->{totalgsti} = sprintf( "%.2f", $ord->{quantity} * $ord->{ecostgsti} );
-            } else {
-                $ord->{rrpgsti} = sprintf( "%.2f", $ord->{rrp} * ( 1 + ( $ord->{gstrate} ) ) );
-                $ord->{rrpgste} = sprintf( "%.2f", $ord->{rrp} );
-                $ord->{gstgsti} = sprintf( "%.2f", $ord->{gstrate} * 100 );
-                $ord->{gstgste} = sprintf( "%.2f", $ord->{gstrate} * 100 );
-                $ord->{ecostgsti} = sprintf( "%.2f", $ord->{ecost} * ( 1 + ( $ord->{gstrate} ) ) );
-                $ord->{ecostgste} = sprintf( "%.2f", $ord->{ecost} );
-                $ord->{gstvalue} = sprintf( "%.2f", ( $ord->{ecostgsti} - $ord->{ecostgste} ) * $ord->{quantity});
-                $ord->{totalgste} = sprintf( "%.2f", $ord->{quantity} * $ord->{ecostgste} );
-                $ord->{totalgsti} = sprintf( "%.2f", $ord->{quantity} * $ord->{ecostgsti} );
-            }
-            my $bib = GetBiblioData($ord->{biblionumber});
-            my $itemtypes = GetItemTypes();
+            $ord->{tax_value} = $ord->{tax_value_on_ordering};
+            $ord->{tax_rate} = $ord->{tax_rate_on_ordering};
+            $ord->{total_tax_included} = get_rounded_price($ord->{ecost_tax_included}) * $ord->{quantity};
+            $ord->{total_tax_excluded} = get_rounded_price($ord->{ecost_tax_excluded}) * $ord->{quantity};
+
+            my $biblioitem = Koha::Biblioitems->search({ biblionumber => $ord->{biblionumber} })->next;
 
             #FIXME DELETE ME
             # 0      1        2        3         4            5         6       7      8        9
-            #isbn, itemtype, author, title, publishercode, quantity, listprice ecost discount gstrate
+            #isbn, itemtype, author, title, publishercode, quantity, listprice ecost discount tax_rate
 
             # Editor Number
             my $en;
             my $edition;
+            $ord->{marcxml} = C4::Biblio::GetXmlBiblio( $ord->{biblionumber} );
             my $marcrecord=eval{MARC::Record::new_from_xml( $ord->{marcxml},'UTF-8' )};
             if ($marcrecord){
                 if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) {
@@ -212,17 +193,15 @@ sub printbasketgrouppdf{
                 }
             }
 
-            my $ba_order = {
-                isbn => ($ord->{isbn} ? $ord->{isbn} : undef),
-                itemtype => ( $ord->{itemtype} and $bib->{itemtype} ? $itemtypes->{$bib->{itemtype}}->{description} : undef ),
-                en => ( $en ? $en : undef ),
-                edition => ( $edition ? $edition : undef ),
-            };
-            for my $key ( qw/ gstrate author title itemtype publishercode copyrightdate publicationyear discount quantity rrpgsti rrpgste gstgsti gstgste ecostgsti ecostgste gstvalue totalgste totalgsti order_vendornote / ) {
-                $ba_order->{$key} = $ord->{$key};
-            }
+            my $itemtype = ( $ord->{itemtype} and $biblioitem->itemtype )
+                ? Koha::ItemTypes->find( $biblioitem->itemtype )
+                : undef;
+            $ord->{itemtype} = $itemtype ? $itemtype->description : undef;
+
+            $ord->{en} = $en ? $en : undef;
+            $ord->{edition} = $edition ? $edition : undef;
 
-            push(@ba_orders, $ba_order);
+            push(@ba_orders, $ord);
         }
         $orders{$basket->{basketno}} = \@ba_orders;
     }
@@ -230,17 +209,36 @@ sub printbasketgrouppdf{
         -type       => 'application/pdf',
         -attachment => ( $basketgroup->{name} || $basketgroupid ) . '.pdf'
     );
-    my $pdf = printpdf($basketgroup, $bookseller, $baskets, \%orders, $bookseller->{gstrate} // C4::Context->preference("gist")) || die "pdf generation failed";
+    my $pdf = printpdf($basketgroup, $bookseller, $baskets, \%orders, $bookseller->tax_rate // C4::Context->preference("gist")) || die "pdf generation failed";
     print $pdf;
 
 }
 
+sub generate_edifact_orders {
+    my $basketgroupid = shift;
+    my $baskets       = GetBasketsByBasketgroup($basketgroupid);
+    my $ean           = get_edifact_ean();
+
+    if($ean) {
+        for my $basket ( @{$baskets} ) {
+            create_edi_order( { ean => $ean, basketno => $basket->{basketno}, } );
+        }
+    } else {
+        my $booksellerid = $input->param('booksellerid') || 0;
+        print $input->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' .
+                               $booksellerid .
+                               '&message=No%20EDIFACT%20Setup');
+    }
+    return;
+}
+
 my $op = $input->param('op') || 'display';
 # possible values of $op :
 # - add : adds a new basketgroup, or edit an open basketgroup, or display a closed basketgroup
 # - mod_basket : modify an individual basket of the basketgroup
 # - closeandprint : close and print an closed basketgroup in pdf. called by clicking on "Close and print" button in closed basketgroups list
 # - print : print a closed basketgroup. called by clicking on "Print" button in closed basketgroups list
+# - ediprint : generate edi order messages for the baskets in the group
 # - export : export in CSV a closed basketgroup. called by clicking on "Export" button in closed basketgroups list
 # - delete : delete an open basketgroup. called by clicking on "Delete" button in open basketgroups list
 # - reopen : reopen a closed basketgroup. called by clicking on "Reopen" button in closed basketgroup list
@@ -248,6 +246,12 @@ my $op = $input->param('op') || 'display';
 # - display : display the list of all basketgroups for a vendor
 my $booksellerid = $input->param('booksellerid');
 $template->param(booksellerid => $booksellerid);
+my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
+
+my $schema = Koha::Database->new()->schema();
+my $rs = $schema->resultset('VendorEdiAccount')->search(
+    { vendor_id => $booksellerid, } );
+$template->param( ediaccount => ($rs->count > 0));
 
 if ( $op eq "add" ) {
 #
@@ -255,7 +259,7 @@ if ( $op eq "add" ) {
 # else, edit (if it is open) or display (if it is close) the basketgroup basketgroupid
 # the template will know if basketgroup must be displayed or edited, depending on the value of closed key
 #
-    my $bookseller = &GetBookSellerFromId($booksellerid);
+    my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
     my $basketgroupid = $input->param('basketgroupid');
     my $billingplace;
     my $deliveryplace;
@@ -284,14 +288,12 @@ if ( $op eq "add" ) {
         $template->param( closedbg => 0);
     }
     # determine default billing and delivery places depending on librarian homebranch and existing basketgroup data
-    my $borrower = GetMember( ( 'borrowernumber' => $loggedinuser ) );
-    $billingplace  = $billingplace  || $borrower->{'branchcode'};
-    $deliveryplace = $deliveryplace || $borrower->{'branchcode'};
-
-    my $branches = C4::Branch::GetBranchesLoop( $billingplace );
-    $template->param( billingplaceloop => $branches );
-    $branches = C4::Branch::GetBranchesLoop( $deliveryplace );
-    $template->param( deliveryplaceloop => $branches );
+    my $patron = Koha::Patrons->find( $loggedinuser ); # FIXME Not needed if billingplace and deliveryplace are set
+    $billingplace  = $billingplace  || $patron->branchcode;
+    $deliveryplace = $deliveryplace || $patron->branchcode;
+
+    $template->param( billingplace => $billingplace );
+    $template->param( deliveryplace => $deliveryplace );
     $template->param( booksellerid => $booksellerid );
 
     # the template will display a unique basketgroup
@@ -356,7 +358,7 @@ if ( $op eq "add" ) {
 #
     # Getting parameters
     my $basketgroup       = {};
-    my @baskets           = $input->param('basket');
+    my @baskets           = $input->multi_param('basket');
     my $basketgroupid     = $input->param('basketgroupid');
     my $basketgroupname   = $input->param('basketgroupname');
     my $booksellerid      = $input->param('booksellerid');
@@ -382,7 +384,7 @@ if ( $op eq "add" ) {
 # FIXME
         }
     }else{
-    # we create a new basketgroup (whith a closed basket)
+    # we create a new basketgroup (with a closed basket)
         $basketgroup = {
             name              => $basketgroupname,
             booksellerid      => $booksellerid,
@@ -399,10 +401,23 @@ if ( $op eq "add" ) {
     $redirectpath .=  "&amp;listclosed=1" if $closedbg ;
     print $input->redirect($redirectpath );
     
+} elsif ( $op eq 'ediprint') {
+    my $basketgroupid = $input->param('basketgroupid');
+    if ($template->param( 'ediaccount' )) {
+        generate_edifact_orders( $basketgroupid );
+        exit;
+    } else {
+        $template->param('NoEDIMessage' => 1);
+        my $basketgroups = &GetBasketgroups($booksellerid);
+        my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
+        my $baskets = &GetBasketsByBookseller($booksellerid);
+
+        displaybasketgroups($basketgroups, $bookseller, $baskets);
+    }
 }else{
 # no param : display the list of all basketgroups for a given vendor
     my $basketgroups = &GetBasketgroups($booksellerid);
-    my $bookseller = &GetBookSellerFromId($booksellerid);
+    my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
     my $baskets = &GetBasketsByBookseller($booksellerid);
 
     displaybasketgroups($basketgroups, $bookseller, $baskets);