updated links in README
[koha_fer] / C4 / Acquisition.pm
index e446e2a..4616d69 100644 (file)
@@ -13,18 +13,21 @@ package C4::Acquisition;
 # 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., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# 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.
 
 
 use strict;
+use warnings;
 use C4::Context;
 use C4::Debug;
 use C4::Dates qw(format_date format_date_in_iso);
 use MARC::Record;
 use C4::Suggestions;
+use C4::Biblio;
 use C4::Debug;
+use C4::SQLHelper qw(InsertInTable);
 
 use Time::localtime;
 use HTML::Entities;
@@ -32,29 +35,32 @@ use HTML::Entities;
 use vars qw($VERSION @ISA @EXPORT);
 
 BEGIN {
-       # set the version for version checking
-       $VERSION = 3.01;
-       require Exporter;
-       @ISA    = qw(Exporter);
-       @EXPORT = qw(
-               &GetBasket &NewBasket &CloseBasket &DelBasket &ModBasket
-               &ModBasketHeader &GetBasketsByBookseller &GetBasketsByBasketgroup
-               &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup
-               &GetBasketgroups
-
-               &GetPendingOrders &GetOrder &GetOrders
-               &GetOrderNumber &GetLateOrders &NewOrder &DelOrder
-               &SearchOrder &GetHistory &GetRecentAcqui
-               &ModOrder &ModOrderItem &ModReceiveOrder &ModOrderBiblioitemNumber
-
-        &NewOrderItem
-
-               &GetParcels &GetParcel
-               &GetContracts &GetContract
-
-        &GetOrderFromItemnumber
+    # set the version for version checking
+    $VERSION = 3.01;
+    require Exporter;
+    @ISA    = qw(Exporter);
+    @EXPORT = qw(
+        &GetBasket &NewBasket &CloseBasket &DelBasket &ModBasket
+       &GetBasketAsCSV
+        &GetBasketsByBookseller &GetBasketsByBasketgroup
+
+        &ModBasketHeader
+
+        &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
+        &GetBasketgroups &ReOpenBasketgroup
+
+        &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
+        &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
+        &SearchOrder &GetHistory &GetRecentAcqui
+        &ModReceiveOrder &ModOrderBiblioitemNumber
+
+        &NewOrderItem &ModOrderItem
+
+        &GetParcels &GetParcel
+        &GetContracts &GetContract
+
         &GetItemnumbersFromOrder
-       );
+    );
 }
 
 
@@ -72,16 +78,16 @@ sub GetOrderFromItemnumber {
 
     my $sth = $dbh->prepare($query);
 
-    $sth->trace(3);
+#    $sth->trace(3);
 
     $sth->execute($itemnumber);
 
     my $order = $sth->fetchrow_hashref;
-       return ( $order  );
+    return ( $order  );
 
 }
 
-# Returns the itemnumber(s) associated with the ordernumber given in parameter 
+# Returns the itemnumber(s) associated with the ordernumber given in parameter
 sub GetItemnumbersFromOrder {
     my ($ordernumber) = @_;
     my $dbh          = C4::Context->dbh;
@@ -91,7 +97,7 @@ sub GetItemnumbersFromOrder {
     my @tab;
 
     while (my $order = $sth->fetchrow_hashref) {
-       push @tab, $order->{'itemnumber'}; 
+    push @tab, $order->{'itemnumber'};
     }
 
     return @tab;
@@ -149,7 +155,7 @@ sub GetBasket {
     my $sth=$dbh->prepare($query);
     $sth->execute($basketno);
     my $basket = $sth->fetchrow_hashref;
-       return ( $basket );
+    return ( $basket );
 }
 
 #------------------------------------------------------------#
@@ -160,16 +166,20 @@ sub GetBasket {
 
 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber );
 
+=back
+
 Create a new basket in aqbasket table
 
+=over 2
+
 =item C<$booksellerid> is a foreign key in the aqbasket table
 
 =item C<$authorizedby> is the username of who created the basket
 
-The other parameters are optional, see ModBasketHeader for more info on them.
-
 =back
 
+The other parameters are optional, see ModBasketHeader for more info on them.
+
 =cut
 
 # FIXME : this function seems to be unused.
@@ -183,7 +193,7 @@ sub NewBasket {
         VALUES  (now(),'$booksellerid','$authorisedby')
     ";
     my $sth =
-      $dbh->do($query);
+    $dbh->do($query);
 #find & return basketno MYSQL dependant, but $dbh->last_insert_id always returns null :-(
     my $basket = $dbh->{'mysql_insertid'};
     ModBasketHeader($basket, $basketname || '', $basketnote || '', $basketbooksellernote || '', $basketcontractnumber || undef);
@@ -218,6 +228,117 @@ sub CloseBasket {
 
 #------------------------------------------------------------#
 
+=head3 GetBasketAsCSV
+
+=over 4
+
+&GetBasketAsCSV($basketno);
+
+Export a basket as CSV
+
+=back
+
+=cut
+sub GetBasketAsCSV {
+    my ($basketno) = @_;
+    my $basket = GetBasket($basketno);
+    my @orders = GetOrders($basketno);
+    my $contract = GetContract($basket->{'contractnumber'});
+    my $csv = Text::CSV->new();
+    my $output; 
+
+    # TODO: Translate headers
+    my @headers = qw(contractname ordernumber line entrydate isbn author title publishercode collectiontitle notes quantity rrp);
+
+    $csv->combine(@headers);                                                                                                        
+    $output = $csv->string() . "\n";   
+
+    my @rows;
+    foreach my $order (@orders) {
+       my @cols;
+       my $bd = GetBiblioData($order->{'biblionumber'});
+       push(@cols,
+               $contract->{'contractname'},
+               $order->{'ordernumber'},
+               $order->{'entrydate'}, 
+               $order->{'isbn'},
+               $bd->{'author'},
+               $bd->{'title'},
+               $bd->{'publishercode'},
+               $bd->{'collectiontitle'},
+               $order->{'notes'},
+               $order->{'quantity'},
+               $order->{'rrp'},
+           );
+       push (@rows, \@cols);
+    }
+
+    # Sort by publishercode 
+    # TODO: Sort by publishercode then by title
+    @rows = sort { @$a[7] cmp @$b[7] } @rows;
+
+    foreach my $row (@rows) {
+       $csv->combine(@$row);                                                                                                                    
+       $output .= $csv->string() . "\n";    
+
+    }
+                                                                                                                                                      
+    return $output;             
+
+}
+
+
+=head3 CloseBasketgroup
+
+=over 4
+
+&CloseBasketgroup($basketgroupno);
+
+close a basketgroup
+
+=back
+
+=cut
+
+sub CloseBasketgroup {
+    my ($basketgroupno) = @_;
+    my $dbh        = C4::Context->dbh;
+    my $sth = $dbh->prepare("
+        UPDATE aqbasketgroups
+        SET    closed=1
+        WHERE  id=?
+    ");
+    $sth->execute($basketgroupno);
+}
+
+#------------------------------------------------------------#
+
+=head3 ReOpenBaskergroup($basketgroupno)
+
+=over 4
+
+&ReOpenBaskergroup($basketgroupno);
+
+reopen a basketgroup
+
+=back
+
+=cut
+
+sub ReOpenBasketgroup {
+    my ($basketgroupno) = @_;
+    my $dbh        = C4::Context->dbh;
+    my $sth = $dbh->prepare("
+        UPDATE aqbasketgroups
+        SET    closed=0
+        WHERE  id=?
+    ");
+    $sth->execute($basketgroupno);
+}
+
+#------------------------------------------------------------#
+
+
 =head3 DelBasket
 
 =over 4
@@ -345,10 +466,10 @@ Returns a list of hashes of all the baskets that belong to bookseller 'bookselle
 
 =item C<$extra> is the extra sql parameters, can be
 
-  - $extra->{groupby}: group baskets by column
-       ex. $extra->{groupby} = aqbasket.basketgroupid
-  - $extra->{orderby}: order baskets by column
-  - $extra->{limit}: limit number of results (can be helpful for pagination)
+- $extra->{groupby}: group baskets by column
+    ex. $extra->{groupby} = aqbasket.basketgroupid
+- $extra->{orderby}: order baskets by column
+- $extra->{limit}: limit number of results (can be helpful for pagination)
 
 =back
 
@@ -426,6 +547,10 @@ $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups
 
 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
 
+$hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
+
+$hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
+
 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
 
 =back
@@ -439,7 +564,7 @@ sub NewBasketgroup {
     die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
     my $query = "INSERT INTO aqbasketgroups (";
     my @params;
-    foreach my $field ('name', 'closed') {
+    foreach my $field ('name', 'deliveryplace', 'deliverycomment', 'closed') {
         if ( $basketgroupinfo->{$field} ) {
             $query .= "$field, ";
             push(@params, $basketgroupinfo->{$field});
@@ -483,6 +608,12 @@ $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups
 
 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
 
+$hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
+
+$hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
+
+$hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
+
 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
 
 =back
@@ -497,8 +628,8 @@ sub ModBasketgroup {
     my $dbh = C4::Context->dbh;
     my $query = "UPDATE aqbasketgroups SET ";
     my @params;
-    foreach my $field (qw(name closed)) {
-        if ( $basketgroupinfo->{$field} ne undef) {
+    foreach my $field (qw(name billingplace deliveryplace deliverycomment closed)) {
+        if ( defined $basketgroupinfo->{$field} ) {
             $query .= "$field=?, ";
             push(@params, $basketgroupinfo->{$field});
         }
@@ -509,12 +640,15 @@ sub ModBasketgroup {
     push(@params, $basketgroupinfo->{'id'});
     my $sth = $dbh->prepare($query);
     $sth->execute(@params);
+
+    $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
+    $sth->execute($basketgroupinfo->{'id'});
+
     if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
+        $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
         foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
-            my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
-            my $sth2 = $dbh->prepare($query2);
-            $sth2->execute($basketgroupinfo->{'id'}, $basketno);
-            $sth2->finish;
+            $sth->execute($basketgroupinfo->{'id'}, $basketno);
+            $sth->finish;
         }
     }
     $sth->finish;
@@ -528,13 +662,13 @@ sub ModBasketgroup {
 
 DelBasketgroup($basketgroupid);
 
-=over 2
+=back
 
 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
 
-=item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
+=over 2
 
-=back
+=item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
 
 =back
 
@@ -552,7 +686,6 @@ sub DelBasketgroup {
 
 #------------------------------------------------------------#
 
-=back
 
 =head2 FUNCTIONS ABOUT ORDERS
 
@@ -560,6 +693,8 @@ sub DelBasketgroup {
 
 =cut
 
+=back
+
 =head3 GetBasketgroup
 
 =over 4
@@ -620,12 +755,8 @@ sub GetBasketgroups {
 
 #------------------------------------------------------------#
 
-=back
-
 =head2 FUNCTIONS ABOUT ORDERS
 
-=over 2
-
 =cut
 
 #------------------------------------------------------------#
@@ -690,7 +821,7 @@ sub GetPendingOrders {
     if ( C4::Context->preference("IndependantBranches") ) {
         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
             $strsth .= " and (borrowers.branchcode = ?
-                          or borrowers.branchcode  = '')";
+                        or borrowers.branchcode  = '')";
             push @query_params, $userenv->{branch};
         }
     }
@@ -737,7 +868,7 @@ sub GetOrders {
     my ( $basketno, $orderby ) = @_;
     my $dbh   = C4::Context->dbh;
     my $query  ="
-         SELECT biblio.*,biblioitems.*,
+        SELECT biblio.*,biblioitems.*,
                 aqorders.*,
                 aqbudgets.*,
                 biblio.title
@@ -812,7 +943,7 @@ C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha d
 =cut
 
 sub GetOrder {
-    my ($ordnum) = @_;
+    my ($ordernumber) = @_;
     my $dbh      = C4::Context->dbh;
     my $query = "
         SELECT biblioitems.*, biblio.*, aqorders.*
@@ -823,7 +954,7 @@ sub GetOrder {
 
     ";
     my $sth= $dbh->prepare($query);
-    $sth->execute($ordnum);
+    $sth->execute($ordernumber);
     my $data = $sth->fetchrow_hashref;
     $sth->finish;
     return $data;
@@ -846,16 +977,18 @@ table of the Koha database.
 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
 
 
-=item $hashref->{'ordnum'} is a "minimum order number." 
+=item $hashref->{'ordernumber'} is a "minimum order number."
 
 =item $hashref->{'budgetdate'} is effectively ignored.
-  If it's undef (anything false) or the string 'now', the current day is used.
-  Else, the upcoming July 1st is used.
+If it's undef (anything false) or the string 'now', the current day is used.
+Else, the upcoming July 1st is used.
 
 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
 
 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
 
+=item defaults entrydate to Now
+
 The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "biblioitemnumber", "rrp", "ecost", "gst", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "bookfundid".
 
 =back
@@ -876,35 +1009,18 @@ sub NewOrder {
         die "Mandatory parameter $key missing" unless $orderinfo->{$key};
     }
 
-    if ( $orderinfo->{'subscription'} eq 'yes' ) {
+    if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
         $orderinfo->{'subscription'} = 1;
     } else {
         $orderinfo->{'subscription'} = 0;
     }
-
-    my $query = "INSERT INTO aqorders (";
-    foreach my $orderinfokey (keys %{$orderinfo}) {
-        next if $orderinfokey =~ m/branchcode|entrydate/;   # skip branchcode and entrydate, branchcode isnt a vaild col, entrydate we add manually with NOW()
-        $query .= "$orderinfokey,";
-        push(@params, $orderinfo->{$orderinfokey});
-    }
-
-    $query .= "entrydate) VALUES (";
-    foreach (@params) {
-        $query .= "?,";
+    $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
+    if (!$orderinfo->{quantityreceived}) {
+        $orderinfo->{quantityreceived} = 0;
     }
-    $query .= " NOW() )";  #ADDING CURRENT DATE TO  'budgetdate, entrydate, purchaseordernumber'...
-
-    my $sth = $dbh->prepare($query);
-
-    $sth->execute(@params);
-    $sth->finish;
-
-    #get ordnum MYSQL dependant, but $dbh->last_insert_id returns null
-    my $ordnum = $dbh->{'mysql_insertid'};
 
-    $sth->finish;
-    return ( $orderinfo->{'basketno'}, $ordnum );
+    my $ordernumber=InsertInTable("aqorders",$orderinfo);
+    return ( $orderinfo->{'basketno'}, $ordernumber );
 }
 
 
@@ -923,7 +1039,7 @@ sub NewOrder {
 =cut
 
 sub NewOrderItem {
-    #my ($biblioitemnumber,$ordnum, $biblionumber) = @_;
+    #my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
     my ($itemnumber, $ordernumber)  = @_;
     my $dbh = C4::Context->dbh;
     my $query = qq|
@@ -997,9 +1113,9 @@ sub ModOrder {
 =over 2
 
 Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
-  - itemnumber: the old itemnumber
-  - ordernumber: the order this item is attached to
-  - newitemnumber: the new itemnumber we want to attach the line to
+- itemnumber: the old itemnumber
+- ordernumber: the order this item is attached to
+- newitemnumber: the new itemnumber we want to attach the line to
 
 =back
 
@@ -1031,7 +1147,7 @@ sub ModOrderItem {
 
 =over 4
 
-&ModOrderBiblioitemNumber($biblioitemnumber,$ordnum, $biblionumber);
+&ModOrderBiblioitemNumber($biblioitemnumber,$ordernumber, $biblionumber);
 
 Modifies the biblioitemnumber for an existing order.
 Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
@@ -1042,15 +1158,15 @@ Updates the order with order number C<$ordernum> and biblionumber C<$biblionumbe
 
 #FIXME: is this used at all?
 sub ModOrderBiblioitemNumber {
-    my ($biblioitemnumber,$ordnum, $biblionumber) = @_;
+    my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
     my $dbh = C4::Context->dbh;
     my $query = "
-      UPDATE aqorders
-      SET    biblioitemnumber = ?
-      WHERE  ordernumber = ?
-      AND biblionumber =  ?";
+    UPDATE aqorders
+    SET    biblioitemnumber = ?
+    WHERE  ordernumber = ?
+    AND biblionumber =  ?";
     my $sth = $dbh->prepare($query);
-    $sth->execute( $biblioitemnumber, $ordnum, $biblionumber );
+    $sth->execute( $biblioitemnumber, $ordernumber, $biblionumber );
 }
 
 #------------------------------------------------------------#
@@ -1080,29 +1196,32 @@ C<$ordernumber>.
 
 sub ModReceiveOrder {
     my (
-        $biblionumber,    $ordnum,  $quantrec, $user, $cost,
+        $biblionumber,    $ordernumber,  $quantrec, $user, $cost,
         $invoiceno, $freight, $rrp, $budget_id, $datereceived
-      )
-      = @_;
+    )
+    = @_;
     my $dbh = C4::Context->dbh;
 #     warn "DATE BEFORE : $daterecieved";
 #    $daterecieved=POSIX::strftime("%Y-%m-%d",CORE::localtime) unless $daterecieved;
 #     warn "DATE REC : $daterecieved";
-       $datereceived = C4::Dates->output('iso') unless $datereceived;
+    $datereceived = C4::Dates->output('iso') unless $datereceived;
     my $suggestionid = GetSuggestionFromBiblionumber( $dbh, $biblionumber );
     if ($suggestionid) {
-        ModStatus( $suggestionid, 'AVAILABLE', '', $biblionumber );
+        ModSuggestion( {suggestionid=>$suggestionid,
+                                               STATUS=>'AVAILABLE',
+                                               biblionumber=> $biblionumber}
+                                               );
     }
 
-       my $sth=$dbh->prepare("
-        SELECT * FROM   aqorders  
-           WHERE           biblionumber=? AND aqorders.ordernumber=?");
+    my $sth=$dbh->prepare("
+        SELECT * FROM   aqorders
+        WHERE           biblionumber=? AND aqorders.ordernumber=?");
 
-    $sth->execute($biblionumber,$ordnum);
+    $sth->execute($biblionumber,$ordernumber);
     my $order = $sth->fetchrow_hashref();
     $sth->finish();
 
-       if ( $order->{quantity} > $quantrec ) {
+    if ( $order->{quantity} > $quantrec ) {
         $sth=$dbh->prepare("
             UPDATE aqorders
             SET quantityreceived=?
@@ -1111,23 +1230,25 @@ sub ModReceiveOrder {
                 , unitprice=?
                 , freight=?
                 , rrp=?
-                , quantityreceived=?
+                , quantity=?
             WHERE biblionumber=? AND ordernumber=?");
 
-        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordnum);
+        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordernumber);
         $sth->finish;
 
         # create a new order for the remaining items, and set its bookfund.
         foreach my $orderkey ( "linenumber", "allocation" ) {
             delete($order->{'$orderkey'});
         }
+        $order->{'quantity'} -= $quantrec;
+        $order->{'quantityreceived'} = 0;
         my $newOrder = NewOrder($order);
-  } else {
+} else {
         $sth=$dbh->prepare("update aqorders
-                                                       set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?,
-                                                               unitprice=?,freight=?,rrp=?
+                            set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?,
+                                unitprice=?,freight=?,rrp=?
                             where biblionumber=? and ordernumber=?");
-        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordnum);
+        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordernumber);
         $sth->finish;
     }
     return $datereceived;
@@ -1181,7 +1302,7 @@ sub SearchOrder {
             LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
             LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
                 WHERE  (datecancellationprinted is NULL)";
-                
+
     if($ordernumber){
         $query .= " AND (aqorders.ordernumber=?)";
         push @args, $ordernumber;
@@ -1223,7 +1344,7 @@ cancelled.
 =cut
 
 sub DelOrder {
-    my ( $bibnum, $ordnum ) = @_;
+    my ( $bibnum, $ordernumber ) = @_;
     my $dbh = C4::Context->dbh;
     my $query = "
         UPDATE aqorders
@@ -1231,7 +1352,7 @@ sub DelOrder {
         WHERE  biblionumber=? AND ordernumber=?
     ";
     my $sth = $dbh->prepare($query);
-    $sth->execute( $bibnum, $ordnum );
+    $sth->execute( $bibnum, $ordernumber );
     $sth->finish;
 }
 
@@ -1265,7 +1386,7 @@ sub GetParcel {
     my $dbh     = C4::Context->dbh;
     my @results = ();
     $code .= '%'
-      if $code;  # add % if we search on a given code (otherwise, let him empty)
+    if $code;  # add % if we search on a given code (otherwise, let him empty)
     my $strsth ="
         SELECT  authorisedby,
                 creationdate,
@@ -1295,7 +1416,7 @@ sub GetParcel {
         my $userenv = C4::Context->userenv;
         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
             $strsth .= " and (borrowers.branchcode = ?
-                          or borrowers.branchcode  = '')";
+                        or borrowers.branchcode  = '')";
             push @query_params, $userenv->{branch};
         }
     }
@@ -1426,55 +1547,56 @@ sub GetLateOrders {
     my $dbdriver = C4::Context->config("db_scheme") || "mysql";
 
     my @query_params = ($delay);       # delay is the first argument regardless
-       my $select = "
-      SELECT aqbasket.basketno,
-          aqorders.ordernumber,
-          DATE(aqbasket.closedate)  AS orderdate,
-          aqorders.rrp              AS unitpricesupplier,
-          aqorders.ecost            AS unitpricelib,
-          aqbudgets.budget_name     AS budget,
-          borrowers.branchcode      AS branch,
-          aqbooksellers.name        AS supplier,
-          biblio.author,
-          biblioitems.publishercode AS publisher,
-          biblioitems.publicationyear,
-       ";
-       my $from = "
-      FROM (((
-          (aqorders LEFT JOIN biblio     ON biblio.biblionumber         = aqorders.biblionumber)
-          LEFT JOIN biblioitems          ON biblioitems.biblionumber    = biblio.biblionumber)
-          LEFT JOIN aqbudgets            ON aqorders.budget_id          = aqbudgets.budget_id),
-          (aqbasket LEFT JOIN borrowers  ON aqbasket.authorisedby       = borrowers.borrowernumber)
-          LEFT JOIN aqbooksellers        ON aqbasket.booksellerid       = aqbooksellers.id
-          WHERE aqorders.basketno = aqbasket.basketno
-          AND ( (datereceived = '' OR datereceived IS NULL)
-              OR (aqorders.quantityreceived < aqorders.quantity)
-          )
+    my $select = "
+    SELECT aqbasket.basketno,
+        aqorders.ordernumber,
+        DATE(aqbasket.closedate)  AS orderdate,
+        aqorders.rrp              AS unitpricesupplier,
+        aqorders.ecost            AS unitpricelib,
+        aqbudgets.budget_name     AS budget,
+        borrowers.branchcode      AS branch,
+        aqbooksellers.name        AS supplier,
+        biblio.author,
+        biblioitems.publishercode AS publisher,
+        biblioitems.publicationyear,
     ";
-       my $having = "";
+    my $from = "
+    FROM
+        aqorders LEFT JOIN biblio     ON biblio.biblionumber         = aqorders.biblionumber
+        LEFT JOIN biblioitems         ON biblioitems.biblionumber    = biblio.biblionumber
+        LEFT JOIN aqbudgets           ON aqorders.budget_id          = aqbudgets.budget_id,
+        aqbasket LEFT JOIN borrowers  ON aqbasket.authorisedby       = borrowers.borrowernumber
+        LEFT JOIN aqbooksellers       ON aqbasket.booksellerid       = aqbooksellers.id
+        WHERE aqorders.basketno = aqbasket.basketno
+        AND ( datereceived = ''
+            OR datereceived IS NULL
+            OR aqorders.quantityreceived < aqorders.quantity
+        )
+    ";
+    my $having = "";
     if ($dbdriver eq "mysql") {
-               $select .= "
-           aqorders.quantity - IFNULL(aqorders.quantityreceived,0)                 AS quantity,
-          (aqorders.quantity - IFNULL(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
-          DATEDIFF(CURDATE( ),closedate) AS latesince
-               ";
+        $select .= "
+        aqorders.quantity - IFNULL(aqorders.quantityreceived,0)                 AS quantity,
+        (aqorders.quantity - IFNULL(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
+        DATEDIFF(CURDATE( ),closedate) AS latesince
+        ";
         $from .= " AND (closedate <= DATE_SUB(CURDATE( ),INTERVAL ? DAY)) ";
-               $having = "
-         HAVING quantity          <> 0
+        $having = "
+        HAVING quantity          <> 0
             AND unitpricesupplier <> 0
             AND unitpricelib      <> 0
-               ";
+        ";
     } else {
-               # FIXME: account for IFNULL as above
+        # FIXME: account for IFNULL as above
         $select .= "
                 aqorders.quantity                AS quantity,
                 aqorders.quantity * aqorders.rrp AS subtotal,
                 (CURDATE - closedate)            AS latesince
-               ";
+        ";
         $from .= " AND (closedate <= (CURDATE -(INTERVAL ? DAY)) ";
     }
     if (defined $supplierid) {
-               $from .= ' AND aqbasket.booksellerid = ? ';
+        $from .= ' AND aqbasket.booksellerid = ? ';
         push @query_params, $supplierid;
     }
     if (defined $branch) {
@@ -1482,13 +1604,13 @@ sub GetLateOrders {
         push @query_params, $branch;
     }
     if (C4::Context->preference("IndependantBranches")
-             && C4::Context->userenv
-             && C4::Context->userenv->{flags} != 1 ) {
+            && C4::Context->userenv
+            && C4::Context->userenv->{flags} != 1 ) {
         $from .= ' AND borrowers.branchcode LIKE ? ';
         push @query_params, C4::Context->userenv->{branch};
     }
-       my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
-       $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
+    my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
+    $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
     my $sth = $dbh->prepare($query);
     $sth->execute(@query_params);
     my @results;
@@ -1507,11 +1629,11 @@ sub GetLateOrders {
 
 (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( $title, $author, $name, $from_placed_on, $to_placed_on );
 
-  Retreives some acquisition history information
+Retreives some acquisition history information
 
-  returns:
+returns:
     $order_loop is a list of hashrefs that each look like this:
-              {
+            {
                 'author'           => 'Twain, Mark',
                 'basketno'         => '1',
                 'biblionumber'     => '215',
@@ -1526,7 +1648,7 @@ sub GetLateOrders {
                 'quantity'         => 1,
                 'quantityreceived' => undef,
                 'title'            => 'The Adventures of Huckleberry Finn'
-              }
+            }
     $total_qty is the sum of all of the quantities in $order_loop
     $total_price is the cost of each in $order_loop times the quantity
     $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
@@ -1550,7 +1672,11 @@ sub GetHistory {
                 biblio.title,
                 biblio.author,
                 aqorders.basketno,
-                name,aqbasket.creationdate,
+               aqbasket.basketname,
+               aqbasket.basketgroupid,
+               aqbasketgroups.name as groupname,
+                aqbooksellers.name,
+               aqbasket.creationdate,
                 aqorders.datereceived,
                 aqorders.quantity,
                 aqorders.quantityreceived,
@@ -1561,12 +1687,13 @@ sub GetHistory {
                 aqorders.biblionumber
             FROM aqorders
             LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
+           LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
             LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
             LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
 
         $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
-          if ( C4::Context->preference("IndependantBranches") );
-
+        if ( C4::Context->preference("IndependantBranches") );
+       
         $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
 
         my @query_params  = ();
@@ -1582,7 +1709,7 @@ sub GetHistory {
         }
 
         if ( defined $name ) {
-            $query .= " AND name LIKE ? ";
+            $query .= " AND aqbooksellers.name LIKE ? ";
             push @query_params, "%$name%";
         }
 
@@ -1603,7 +1730,8 @@ sub GetHistory {
                 push @query_params, $userenv->{branch};
             }
         }
-        $query .= " ORDER BY booksellerid";
+        $query .= " ORDER BY id";
+       warn $query;
         my $sth = $dbh->prepare($query);
         $sth->execute( @query_params );
         my $cnt = 1;
@@ -1623,9 +1751,9 @@ sub GetHistory {
 
 =head2 GetRecentAcqui
 
-   $results = GetRecentAcqui($days);
+$results = GetRecentAcqui($days);
 
-   C<$results> is a ref to a table which containts hashref
+C<$results> is a ref to a table which containts hashref
 
 =cut
 
@@ -1650,10 +1778,14 @@ sub GetRecentAcqui {
 
 $contractlist = &GetContracts($booksellerid, $activeonly);
 
+=back
+
 Looks up the contracts that belong to a bookseller
 
 Returns a list of contracts
 
+=over 2
+
 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
 
 =item C<$activeonly> if exists get only contracts that are still active.