use Memoize because Memcache::Memoize is slow for me
[koha.git] / C4 / Acquisition.pm
index 43024b3..19c4f08 100644 (file)
@@ -13,18 +13,22 @@ 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 Carp;
 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,28 +36,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 &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
+    );
 }
 
 
@@ -71,15 +79,31 @@ 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
+sub GetItemnumbersFromOrder {
+    my ($ordernumber) = @_;
+    my $dbh          = C4::Context->dbh;
+    my $query        = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
+    my $sth = $dbh->prepare($query);
+    $sth->execute($ordernumber);
+    my @tab;
+
+    while (my $order = $sth->fetchrow_hashref) {
+    push @tab, $order->{'itemnumber'};
+    }
+
+    return @tab;
+
+}
 
 
 
@@ -105,16 +129,11 @@ orders, basket and parcels.
 
 =head3 GetBasket
 
-=over 4
-
-$aqbasket = &GetBasket($basketnumber);
+  $aqbasket = &GetBasket($basketnumber);
 
 get all basket informations in aqbasket for a given basket
 
-return :
-informations for a given basket returned as a hashref.
-
-=back
+B<returns:> informations for a given basket returned as a hashref.
 
 =cut
 
@@ -132,27 +151,28 @@ sub GetBasket {
     my $sth=$dbh->prepare($query);
     $sth->execute($basketno);
     my $basket = $sth->fetchrow_hashref;
-       return ( $basket );
+    return ( $basket );
 }
 
 #------------------------------------------------------------#
 
 =head3 NewBasket
 
-=over 4
-
-$basket = &NewBasket( $booksellerid, $authorizedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber );
+  $basket = &NewBasket( $booksellerid, $authorizedby, $basketname, 
+      $basketnote, $basketbooksellernote, $basketcontractnumber );
 
 Create a new basket in aqbasket table
 
+=over
+
 =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.
@@ -166,7 +186,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);
@@ -177,14 +197,10 @@ sub NewBasket {
 
 =head3 CloseBasket
 
-=over 4
-
-&CloseBasket($basketno);
+  &CloseBasket($basketno);
 
 close a basket (becomes unmodifiable,except for recieves)
 
-=back
-
 =cut
 
 sub CloseBasket {
@@ -201,23 +217,117 @@ sub CloseBasket {
 
 #------------------------------------------------------------#
 
-=head3 DelBasket
+=head3 GetBasketAsCSV
 
-=over 4
+  &GetBasketAsCSV($basketno);
+
+Export a basket as CSV
 
-&DelBasket($basketno);
+=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 entrydate isbn author title publishercode collectiontitle notes quantity rrp);
+
+    $csv->combine(@headers);                                                                                                        
+    $output = $csv->string() . "\n";   
+
+    my @rows;
+    foreach my $order (@orders) {
+       my @cols;
+       # newlines are not valid characters for Text::CSV combine()
+        $order->{'notes'} =~ s/[\r\n]+//g;
+       push(@cols,
+               $contract->{'contractname'},
+               $order->{'ordernumber'},
+               $order->{'entrydate'}, 
+               $order->{'isbn'},
+               $order->{'author'},
+               $order->{'title'},
+               $order->{'publishercode'},
+               $order->{'collectiontitle'},
+               $order->{'notes'},
+               $order->{'quantity'},
+               $order->{'rrp'},
+           );
+       push (@rows, \@cols);
+    }
+
+    foreach my $row (@rows) {
+       $csv->combine(@$row);                                                                                                                    
+       $output .= $csv->string() . "\n";    
+
+    }
+                                                                                                                                                      
+    return $output;             
+
+}
+
+
+=head3 CloseBasketgroup
+
+  &CloseBasketgroup($basketgroupno);
+
+close a basketgroup
+
+=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)
+
+  &ReOpenBaskergroup($basketgroupno);
+
+reopen a basketgroup
+
+=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
+
+  &DelBasket($basketno);
 
 Deletes the basket that has basketno field $basketno in the aqbasket table.
 
-=over 2
+=over
 
 =item C<$basketno> is the primary key of the basket in the aqbasket table.
 
 =back
 
-=back
-
 =cut
+
 sub DelBasket {
     my ( $basketno ) = @_;
     my $query = "DELETE FROM aqbasket WHERE basketno=?";
@@ -231,21 +341,18 @@ sub DelBasket {
 
 =head3 ModBasket
 
-=over 4
-
-&ModBasket($basketinfo);
+  &ModBasket($basketinfo);
 
 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
 
-=over 2
+=over
 
 =item C<$basketno> is the primary key of the basket in the aqbasket table.
 
 =back
 
-=back
-
 =cut
+
 sub ModBasket {
     my $basketinfo = shift;
     my $query = "UPDATE aqbasket SET ";
@@ -274,13 +381,11 @@ sub ModBasket {
 
 =head3 ModBasketHeader
 
-=over 4
-
-&ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber);
+  &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber);
 
 Modifies a basket's header.
 
-=over 2
+=over
 
 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
 
@@ -294,9 +399,8 @@ Modifies a basket's header.
 
 =back
 
-=back
-
 =cut
+
 sub ModBasketHeader {
     my ($basketno, $basketname, $note, $booksellernote, $contractnumber) = @_;
     my $query = "UPDATE aqbasket SET basketname=?, note=?, booksellernote=? WHERE basketno=?";
@@ -316,24 +420,20 @@ sub ModBasketHeader {
 
 =head3 GetBasketsByBookseller
 
-=over 4
-
-@results = &GetBasketsByBookseller($booksellerid, $extra);
+  @results = &GetBasketsByBookseller($booksellerid, $extra);
 
 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
 
-=over 2
+=over
 
 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
 
 =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)
-
-=back
+ $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
 
@@ -365,18 +465,10 @@ sub GetBasketsByBookseller {
 
 =head3 GetBasketsByBasketgroup
 
-=over 4
-
-$baskets = &GetBasketsByBasketgroup($basketgroupid);
-
-=over 2
+  $baskets = &GetBasketsByBasketgroup($basketgroupid);
 
 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
 
-=back
-
-=back
-
 =cut
 
 sub GetBasketsByBasketgroup {
@@ -395,11 +487,7 @@ sub GetBasketsByBasketgroup {
 
 =head3 NewBasketgroup
 
-=over 4
-
-$basketgroupid = NewBasketgroup(\%hashref);
-
-=over 2
+  $basketgroupid = NewBasketgroup(\%hashref);
 
 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
 
@@ -409,11 +497,11 @@ $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->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
+$hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
 
-=back
+$hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
 
-=back
+$hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
 
 =cut
 
@@ -422,7 +510,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});
@@ -452,11 +540,7 @@ sub NewBasketgroup {
 
 =head3 ModBasketgroup
 
-=over 4
-
-ModBasketgroup(\%hashref);
-
-=over 2
+  ModBasketgroup(\%hashref);
 
 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
 
@@ -466,11 +550,13 @@ $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->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
+$hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
 
-=back
+$hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
 
-=back
+$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.
 
 =cut
 
@@ -480,8 +566,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 freedeliveryplace deliverycomment closed)) {
+        if ( defined $basketgroupinfo->{$field} ) {
             $query .= "$field=?, ";
             push(@params, $basketgroupinfo->{$field});
         }
@@ -492,12 +578,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;
@@ -507,17 +596,13 @@ sub ModBasketgroup {
 
 =head3 DelBasketgroup
 
-=over 4
-
-DelBasketgroup($basketgroupid);
-
-=over 2
+  DelBasketgroup($basketgroupid);
 
 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
 
-=back
+=item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
 
 =back
 
@@ -535,28 +620,15 @@ sub DelBasketgroup {
 
 #------------------------------------------------------------#
 
-=back
 
 =head2 FUNCTIONS ABOUT ORDERS
 
-=over 2
-
-=cut
-
 =head3 GetBasketgroup
 
-=over 4
-
-$basketgroup = &GetBasketgroup($basketgroupid);
-
-=over 2
+  $basketgroup = &GetBasketgroup($basketgroupid);
 
 Returns a reference to the hash containing all infermation about the basketgroup.
 
-=back
-
-=back
-
 =cut
 
 sub GetBasketgroup {
@@ -575,24 +647,16 @@ sub GetBasketgroup {
 
 =head3 GetBasketgroups
 
-=over 4
-
-$basketgroups = &GetBasketgroups($booksellerid);
-
-=over 2
+  $basketgroups = &GetBasketgroups($booksellerid);
 
 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
 
-=back
-
-=back
-
 =cut
 
 sub GetBasketgroups {
     my $booksellerid = shift;
     die "bookseller id is required to edit a basketgroup" unless $booksellerid;
-    my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=?";
+    my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY `id` DESC";
     my $dbh = C4::Context->dbh;
     my $sth = $dbh->prepare($query);
     $sth->execute($booksellerid);
@@ -603,21 +667,15 @@ sub GetBasketgroups {
 
 #------------------------------------------------------------#
 
-=back
-
 =head2 FUNCTIONS ABOUT ORDERS
 
-=over 2
-
 =cut
 
 #------------------------------------------------------------#
 
 =head3 GetPendingOrders
 
-=over 4
-
-$orders = &GetPendingOrders($booksellerid, $grouped, $owner);
+  $orders = &GetPendingOrders($booksellerid, $grouped, $owner);
 
 Finds pending orders from the bookseller with the given ID. Ignores
 completed and cancelled orders.
@@ -631,7 +689,7 @@ reference-to-hash with the following fields:
 C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
 in a single result line
 
-=over 2
+=over
 
 =item C<authorizedby>
 
@@ -639,12 +697,10 @@ in a single result line
 
 =item C<basketno>
 
-These give the value of the corresponding field in the aqorders table
-of the Koha database.
-
 =back
 
-=back
+These give the value of the corresponding field in the aqorders table
+of the Koha database.
 
 Results are ordered from most to least recent.
 
@@ -655,12 +711,13 @@ sub GetPendingOrders {
     my $dbh = C4::Context->dbh;
     my $strsth = "
         SELECT    ".($grouped?"count(*),":"")."aqbasket.basketno,
-                    surname,firstname,aqorders.*,biblio.*,
+                    surname,firstname,aqorders.*,biblio.*,biblioitems.isbn,
                     aqbasket.closedate, aqbasket.creationdate, aqbasket.basketname
         FROM      aqorders
         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
         LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
+        LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
         WHERE booksellerid=?
             AND (quantity > quantityreceived OR quantityreceived is NULL)
             AND datecancellationprinted IS NULL
@@ -672,7 +729,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};
         }
     }
@@ -698,9 +755,7 @@ sub GetPendingOrders {
 
 =head3 GetOrders
 
-=over 4
-
-@orders = &GetOrders($basketnumber, $orderby);
+  @orders = &GetOrders($basketnumber, $orderby);
 
 Looks up the pending (non-cancelled) orders with the given basket
 number. If C<$booksellerID> is non-empty, only orders from that seller
@@ -711,15 +766,13 @@ C<&basket> returns a two-element array. C<@orders> is an array of
 references-to-hash, whose keys are the fields from the aqorders,
 biblio, and biblioitems tables in the Koha database.
 
-=back
-
 =cut
 
 sub GetOrders {
     my ( $basketno, $orderby ) = @_;
     my $dbh   = C4::Context->dbh;
     my $query  ="
-         SELECT biblio.*,biblioitems.*,
+        SELECT biblio.*,biblioitems.*,
                 aqorders.*,
                 aqbudgets.*,
                 biblio.title
@@ -744,23 +797,20 @@ sub GetOrders {
 
 =head3 GetOrderNumber
 
-=over 4
-
-$ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
-
-=back
+  $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
 
 Looks up the ordernumber with the given biblionumber and biblioitemnumber.
 
 Returns the number of this order.
 
-=over 4
+=over
 
 =item C<$ordernumber> is the order number.
 
 =back
 
 =cut
+
 sub GetOrderNumber {
     my ( $biblionumber,$biblioitemnumber ) = @_;
     my $dbh = C4::Context->dbh;
@@ -780,21 +830,17 @@ sub GetOrderNumber {
 
 =head3 GetOrder
 
-=over 4
-
-$order = &GetOrder($ordernumber);
+  $order = &GetOrder($ordernumber);
 
 Looks up an order by order number.
 
 Returns a reference-to-hash describing the order. The keys of
 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
 
-=back
-
 =cut
 
 sub GetOrder {
-    my ($ordnum) = @_;
+    my ($ordernumber) = @_;
     my $dbh      = C4::Context->dbh;
     my $query = "
         SELECT biblioitems.*, biblio.*, aqorders.*
@@ -805,7 +851,7 @@ sub GetOrder {
 
     ";
     my $sth= $dbh->prepare($query);
-    $sth->execute($ordnum);
+    $sth->execute($ordernumber);
     my $data = $sth->fetchrow_hashref;
     $sth->finish;
     return $data;
@@ -815,32 +861,29 @@ sub GetOrder {
 
 =head3 NewOrder
 
-=over 4
-
-&NewOrder(\%hashref);
+  &NewOrder(\%hashref);
 
 Adds a new order to the database. Any argument that isn't described
 below is the new value of the field with the same name in the aqorders
 table of the Koha database.
 
-=over 4
+=over
 
 =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"
 
-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".
+=item defaults entrydate to Now
 
-=back
+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
 
@@ -855,38 +898,21 @@ sub NewOrder {
 
     # if these parameters are missing, we can't continue
     for my $key (qw/basketno quantity biblionumber budget_id/) {
-        die "Mandatory parameter $key missing" unless $orderinfo->{$key};
+        croak "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 );
 }
 
 
@@ -895,17 +921,12 @@ sub NewOrder {
 
 =head3 NewOrderItem
 
-=over 4
-
-&NewOrderItem();
-
-
-=back
+  &NewOrderItem();
 
 =cut
 
 sub NewOrderItem {
-    #my ($biblioitemnumber,$ordnum, $biblionumber) = @_;
+    #my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
     my ($itemnumber, $ordernumber)  = @_;
     my $dbh = C4::Context->dbh;
     my $query = qq|
@@ -921,19 +942,12 @@ sub NewOrderItem {
 
 =head3 ModOrder
 
-=over 4
-
-&ModOrder(\%hashref);
-
-=over 2
+  &ModOrder(\%hashref);
 
 Modifies an existing order. Updates the order with order number
-$hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All other keys of the hash
-update the fields with the same name in the aqorders table of the Koha database.
-
-=back
-
-=back
+$hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All 
+other keys of the hash update the fields with the same name in the aqorders 
+table of the Koha database.
 
 =cut
 
@@ -945,6 +959,10 @@ sub ModOrder {
 
     my $dbh = C4::Context->dbh;
     my @params;
+
+    # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
+    $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
+
 #    delete($orderinfo->{'branchcode'});
     # the hash contains a lot of entries not in aqorders, so get the columns ...
     my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
@@ -970,39 +988,67 @@ sub ModOrder {
 
 #------------------------------------------------------------#
 
-=head3 ModOrderBibliotemNumber
+=head3 ModOrderItem
 
-=over 4
+  &ModOrderItem(\%hashref);
 
-&ModOrderBiblioitemNumber($biblioitemnumber,$ordnum, $biblionumber);
+Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
 
-Modifies the biblioitemnumber for an existing order.
-Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
+=over
+
+=item - itemnumber: the old itemnumber
+=item - ordernumber: the order this item is attached to
+=item - newitemnumber: the new itemnumber we want to attach the line to
 
 =back
 
 =cut
 
+sub ModOrderItem {
+    my $orderiteminfo = shift;
+    if (! $orderiteminfo->{'ordernumber'} || ! $orderiteminfo->{'itemnumber'} || ! $orderiteminfo->{'newitemnumber'}){
+        die "Ordernumber, itemnumber and newitemnumber is required";
+    }
+
+    my $dbh = C4::Context->dbh;
+
+    my $query = "UPDATE aqorders_items set itemnumber=? where itemnumber=? and ordernumber=?";
+    my @params = ($orderiteminfo->{'newitemnumber'}, $orderiteminfo->{'itemnumber'}, $orderiteminfo->{'ordernumber'});
+    my $sth = $dbh->prepare($query);
+    $sth->execute(@params);
+    return 0;
+}
+
+#------------------------------------------------------------#
+
+
+=head3 ModOrderBibliotemNumber
+
+  &ModOrderBiblioitemNumber($biblioitemnumber,$ordernumber, $biblionumber);
+
+Modifies the biblioitemnumber for an existing order.
+Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
+
+=cut
+
 #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 );
 }
 
 #------------------------------------------------------------#
 
 =head3 ModReceiveOrder
 
-=over 4
-
-&ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
+  &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
     $unitprice, $booksellerinvoicenumber, $biblioitemnumber,
     $freight, $bookfund, $rrp);
 
@@ -1016,36 +1062,37 @@ portion must have a booksellerinvoicenumber.
 Updates the order with bibilionumber C<$biblionumber> and ordernumber
 C<$ordernumber>.
 
-=back
-
 =cut
 
 
 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=?
@@ -1054,23 +1101,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;
@@ -1113,59 +1162,56 @@ C<@results> is an array of references-to-hash with the following keys:
 
 sub SearchOrder {
 #### -------- SearchOrder-------------------------------
-    my ($ordernumber, $search) = @_;
+    my ($ordernumber, $search, $supplierid, $basket) = @_;
 
-    if ($ordernumber) {
-        my $dbh = C4::Context->dbh;
-        my $query =
-            "SELECT *
-            FROM aqorders
-            LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
-            LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
-            LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
-                WHERE  ((datecancellationprinted is NULL)
-                AND (aqorders.ordernumber=?))";
-        my $sth = $dbh->prepare($query);
-        $sth->execute($ordernumber);
-        my $results = $sth->fetchall_arrayref({});
-        $sth->finish;
-        return $results;
-    } else {
-        my $dbh = C4::Context->dbh;
-        my $query =
+    my $dbh = C4::Context->dbh;
+    my @args = ();
+    my $query =
             "SELECT *
             FROM aqorders
             LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
             LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
             LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
-                WHERE  ((datecancellationprinted is NULL)
-                AND (biblio.title like ? OR biblioitems.isbn like ?))";
-        my $sth = $dbh->prepare($query);
-        $sth->execute("%$search%","%$search%");
-        my $results = $sth->fetchall_arrayref({});
-        $sth->finish;
-        return $results;
+                WHERE  (datecancellationprinted is NULL)";
+
+    if($ordernumber){
+        $query .= " AND (aqorders.ordernumber=?)";
+        push @args, $ordernumber;
+    }
+    if($search){
+        $query .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
+        push @args, ("%$search%","%$search%","%$search%");
+    }
+    if($supplierid){
+        $query .= "AND aqbasket.booksellerid = ?";
+        push @args, $supplierid;
     }
+    if($basket){
+        $query .= "AND aqorders.basketno = ?";
+        push @args, $basket;
+    }
+
+    my $sth = $dbh->prepare($query);
+    $sth->execute(@args);
+    my $results = $sth->fetchall_arrayref({});
+    $sth->finish;
+    return $results;
 }
 
 #------------------------------------------------------------#
 
 =head3 DelOrder
 
-=over 4
-
-&DelOrder($biblionumber, $ordernumber);
+  &DelOrder($biblionumber, $ordernumber);
 
 Cancel the order with the given order and biblio numbers. It does not
 delete any entries in the aqorders table, it merely marks them as
 cancelled.
 
-=back
-
 =cut
 
 sub DelOrder {
-    my ( $bibnum, $ordnum ) = @_;
+    my ( $bibnum, $ordernumber ) = @_;
     my $dbh = C4::Context->dbh;
     my $query = "
         UPDATE aqorders
@@ -1173,8 +1219,13 @@ sub DelOrder {
         WHERE  biblionumber=? AND ordernumber=?
     ";
     my $sth = $dbh->prepare($query);
-    $sth->execute( $bibnum, $ordnum );
+    $sth->execute( $bibnum, $ordernumber );
     $sth->finish;
+    my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
+    foreach my $itemnumber (@itemnumbers){
+       C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
+    }
+    
 }
 
 =head2 FUNCTIONS ABOUT PARCELS
@@ -1185,9 +1236,7 @@ sub DelOrder {
 
 =head3 GetParcel
 
-=over 4
-
-@results = &GetParcel($booksellerid, $code, $date);
+  @results = &GetParcel($booksellerid, $code, $date);
 
 Looks up all of the received items from the supplier with the given
 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
@@ -1197,8 +1246,6 @@ the aqorders, biblio, and biblioitems tables of the Koha database.
 
 C<@results> is sorted alphabetically by book title.
 
-=back
-
 =cut
 
 sub GetParcel {
@@ -1207,7 +1254,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,
@@ -1237,7 +1284,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};
         }
     }
@@ -1258,16 +1305,13 @@ sub GetParcel {
 
 =head3 GetParcels
 
-=over 4
+  $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
 
-$results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
 get a lists of parcels.
 
-=back
-
 * Input arg :
 
-=over 4
+=over
 
 =item $bookseller
 is the bookseller this function has to get parcels.
@@ -1281,9 +1325,13 @@ is the booksellerinvoicenumber.
 =item $datefrom & $dateto
 to know on what date this function has to filter its search.
 
+=back
+
 * return:
 a pointer on a hash list containing parcel informations as such :
 
+=over
+
 =item Creation date
 
 =item Last operation
@@ -1307,8 +1355,9 @@ sub GetParcels {
                 sum(quantity) AS itemsexpected,
                 sum(quantityreceived) AS itemsreceived
         FROM   aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
-        WHERE aqbasket.booksellerid = $bookseller and datereceived IS NOT NULL
+        WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
     ";
+    push @query_params, $bookseller;
 
     if ( defined $code ) {
         $strsth .= ' and aqorders.booksellerinvoicenumber like ? ';
@@ -1344,17 +1393,13 @@ sub GetParcels {
 
 =head3 GetLateOrders
 
-=over 4
-
-@results = &GetLateOrders;
+  @results = &GetLateOrders;
 
 Searches for bookseller with late orders.
 
 return:
 the table of supplier with late issues. This table is full of hashref.
 
-=back
-
 =cut
 
 sub GetLateOrders {
@@ -1368,55 +1413,57 @@ 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, biblio.title,
+        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
+        )
+        AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
     ";
-       my $having = "";
+    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) {
@@ -1424,13 +1471,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;
@@ -1445,15 +1492,22 @@ sub GetLateOrders {
 
 =head3 GetHistory
 
-=over 4
+  (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
 
-(\@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
+params:  
+  title
+  author
+  name
+  from_placed_on
+  to_placed_on
+  basket                  - search both basket name and number
+  booksellerinvoicenumber 
 
-  returns:
+returns:
     $order_loop is a list of hashrefs that each look like this:
-              {
+            {
                 'author'           => 'Twain, Mark',
                 'basketno'         => '1',
                 'biblionumber'     => '215',
@@ -1468,106 +1522,140 @@ 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
 
-=back
-
 =cut
 
 sub GetHistory {
-    my ( $title, $author, $name, $from_placed_on, $to_placed_on ) = @_;
+# don't run the query if there are no parameters (list would be too long for sure !)
+    croak "No search params" unless @_;
+    my %params = @_;
+    my $title = $params{title};
+    my $author = $params{author};
+    my $isbn   = $params{isbn};
+    my $name = $params{name};
+    my $from_placed_on = $params{from_placed_on};
+    my $to_placed_on = $params{to_placed_on};
+    my $basket = $params{basket};
+    my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
+
     my @order_loop;
     my $total_qty         = 0;
     my $total_qtyreceived = 0;
     my $total_price       = 0;
 
-# don't run the query if there are no parameters (list would be too long for sure !)
-    if ( $title || $author || $name || $from_placed_on || $to_placed_on ) {
-        my $dbh   = C4::Context->dbh;
-        my $query ="
-            SELECT
-                biblio.title,
-                biblio.author,
-                aqorders.basketno,
-                name,aqbasket.creationdate,
-                aqorders.datereceived,
-                aqorders.quantity,
-                aqorders.quantityreceived,
-                aqorders.ecost,
-                aqorders.ordernumber,
-                aqorders.booksellerinvoicenumber as invoicenumber,
-                aqbooksellers.id as id,
-                aqorders.biblionumber
-            FROM aqorders
-            LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
-            LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
-            LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
+    my $dbh   = C4::Context->dbh;
+    my $query ="
+        SELECT
+            biblio.title,
+            biblio.author,
+           biblioitems.isbn,
+            aqorders.basketno,
+    aqbasket.basketname,
+    aqbasket.basketgroupid,
+    aqbasketgroups.name as groupname,
+            aqbooksellers.name,
+    aqbasket.creationdate,
+            aqorders.datereceived,
+            aqorders.quantity,
+            aqorders.quantityreceived,
+            aqorders.ecost,
+            aqorders.ordernumber,
+            aqorders.booksellerinvoicenumber as invoicenumber,
+            aqbooksellers.id as id,
+            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 biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
+        LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
 
-        $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
-          if ( C4::Context->preference("IndependantBranches") );
+    $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
+    if ( C4::Context->preference("IndependantBranches") );
 
-        $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
+    $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
 
-        my @query_params  = ();
+    my @query_params  = ();
 
-        if ( defined $title ) {
-            $query .= " AND biblio.title LIKE ? ";
-            push @query_params, "%$title%";
-        }
+    if ( defined $title ) {
+        $query .= " AND biblio.title LIKE ? ";
+        $title =~ s/\s+/%/g;
+        push @query_params, "%$title%";
+    }
 
-        if ( defined $author ) {
-            $query .= " AND biblio.author LIKE ? ";
-            push @query_params, "%$author%";
-        }
+    if ( defined $author ) {
+        $query .= " AND biblio.author LIKE ? ";
+        push @query_params, "%$author%";
+    }
 
-        if ( defined $name ) {
-            $query .= " AND name LIKE ? ";
-            push @query_params, "%$name%";
-        }
+    if ( defined $isbn ) {
+        $query .= " AND biblioitems.isbn LIKE ? ";
+        push @query_params, "%$isbn%";
+    }
 
-        if ( defined $from_placed_on ) {
-            $query .= " AND creationdate >= ? ";
-            push @query_params, $from_placed_on;
-        }
+    if ( defined $name ) {
+        $query .= " AND aqbooksellers.name LIKE ? ";
+        push @query_params, "%$name%";
+    }
 
-        if ( defined $to_placed_on ) {
-            $query .= " AND creationdate <= ? ";
-            push @query_params, $to_placed_on;
-        }
+    if ( defined $from_placed_on ) {
+        $query .= " AND creationdate >= ? ";
+        push @query_params, $from_placed_on;
+    }
 
-        if ( C4::Context->preference("IndependantBranches") ) {
-            my $userenv = C4::Context->userenv;
-            if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
-                $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
-                push @query_params, $userenv->{branch};
-            }
+    if ( defined $to_placed_on ) {
+        $query .= " AND creationdate <= ? ";
+        push @query_params, $to_placed_on;
+    }
+
+    if ($basket) {
+        if ($basket =~ m/^\d+$/) {
+            $query .= " AND aqorders.basketno = ? ";
+            push @query_params, $basket;
+        } else {
+            $query .= " AND aqbasket.basketname LIKE ? ";
+            push @query_params, "%$basket%";
         }
-        $query .= " ORDER BY booksellerid";
-        my $sth = $dbh->prepare($query);
-        $sth->execute( @query_params );
-        my $cnt = 1;
-        while ( my $line = $sth->fetchrow_hashref ) {
-            $line->{count} = $cnt++;
-            $line->{toggle} = 1 if $cnt % 2;
-            push @order_loop, $line;
-            $line->{creationdate} = format_date( $line->{creationdate} );
-            $line->{datereceived} = format_date( $line->{datereceived} );
-            $total_qty         += $line->{'quantity'};
-            $total_qtyreceived += $line->{'quantityreceived'};
-            $total_price       += $line->{'quantity'} * $line->{'ecost'};
+    }
+
+    if ($booksellerinvoicenumber) {
+        $query .= " AND (aqorders.booksellerinvoicenumber LIKE ? OR aqbasket.booksellerinvoicenumber LIKE ?)";
+        push @query_params, "%$booksellerinvoicenumber%", "%$booksellerinvoicenumber%";
+    }
+
+    if ( C4::Context->preference("IndependantBranches") ) {
+        my $userenv = C4::Context->userenv;
+        if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
+            $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
+            push @query_params, $userenv->{branch};
         }
     }
+    $query .= " ORDER BY id";
+    my $sth = $dbh->prepare($query);
+    $sth->execute( @query_params );
+    my $cnt = 1;
+    while ( my $line = $sth->fetchrow_hashref ) {
+        $line->{count} = $cnt++;
+        $line->{toggle} = 1 if $cnt % 2;
+        push @order_loop, $line;
+        $line->{creationdate} = format_date( $line->{creationdate} );
+        $line->{datereceived} = format_date( $line->{datereceived} );
+        $total_qty         += $line->{'quantity'};
+        $total_qtyreceived += $line->{'quantityreceived'};
+        $total_price       += $line->{'quantity'} * $line->{'ecost'};
+    }
     return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
 }
 
 =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
 
@@ -1588,14 +1676,14 @@ sub GetRecentAcqui {
 
 =head3 GetContracts
 
-=over 4
-
-$contractlist = &GetContracts($booksellerid, $activeonly);
+  $contractlist = &GetContracts($booksellerid, $activeonly);
 
 Looks up the contracts that belong to a bookseller
 
 Returns a list of contracts
 
+=over
+
 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
 
 =item C<$activeonly> if exists get only contracts that are still active.
@@ -1603,6 +1691,7 @@ Returns a list of contracts
 =back
 
 =cut
+
 sub GetContracts {
     my ( $booksellerid, $activeonly ) = @_;
     my $dbh = C4::Context->dbh;
@@ -1633,17 +1722,14 @@ sub GetContracts {
 
 =head3 GetContract
 
-=over 4
-
-$contract = &GetContract($contractID);
+  $contract = &GetContract($contractID);
 
 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
 
 Returns a contract
 
-=back
-
 =cut
+
 sub GetContract {
     my ( $contractno ) = @_;
     my $dbh = C4::Context->dbh;
@@ -1664,6 +1750,6 @@ __END__
 
 =head1 AUTHOR
 
-Koha Developement team <info@koha.org>
+Koha Development Team <http://koha-community.org/>
 
 =cut