Bug 11058: fix compilation warning in C4::Record
[koha.git] / C4 / Acquisition.pm
index 83031be..e470b24 100644 (file)
@@ -53,13 +53,13 @@ BEGIN {
         &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
         &GetBasketgroups &ReOpenBasketgroup
 
-        &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
-        &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
-        &SearchOrder &GetHistory &GetRecentAcqui
-        &ModReceiveOrder &CancelReceipt &ModOrderBiblioitemNumber
-        &GetCancelledOrders
-
-        &NewOrderItem &ModOrderItem &ModItemOrder
+        &NewOrder &DelOrder &ModOrder &GetOrder &GetOrders &GetOrdersByBiblionumber
+        &GetLateOrders &GetOrderFromItemnumber
+        &SearchOrders &GetHistory &GetRecentAcqui
+        &ModReceiveOrder &CancelReceipt
+        &GetCancelledOrders &TransferOrder
+        &GetLastOrderNotReceivedFromSubscriptionid &GetLastOrderReceivedFromSubscriptionid
+        &NewOrderItem &ModItemOrder
 
         &GetParcels &GetParcel
         &GetContracts &GetContract
@@ -71,6 +71,8 @@ BEGIN {
         &ModInvoice
         &CloseInvoice
         &ReopenInvoice
+        &DelInvoice
+        &MergeInvoices
 
         &GetItemnumbersFromOrder
 
@@ -190,18 +192,21 @@ The other parameters are optional, see ModBasketHeader for more info on them.
 =cut
 
 sub NewBasket {
-    my ( $booksellerid, $authorisedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace ) = @_;
+    my ( $booksellerid, $authorisedby, $basketname, $basketnote,
+        $basketbooksellernote, $basketcontractnumber, $deliveryplace,
+        $billingplace ) = @_;
     my $dbh = C4::Context->dbh;
-    my $query = "
-        INSERT INTO aqbasket
-                (creationdate,booksellerid,authorisedby)
-        VALUES  (now(),'$booksellerid','$authorisedby')
-    ";
-    my $sth =
-    $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, $booksellerid, $deliveryplace || undef, $billingplace || undef );
+    my $query =
+        'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
+      . 'VALUES  (now(),?,?)';
+    $dbh->do( $query, {}, $booksellerid, $authorisedby );
+
+    my $basket = $dbh->{mysql_insertid};
+    $basketname           ||= q{}; # default to empty strings
+    $basketnote           ||= q{};
+    $basketbooksellernote ||= q{};
+    ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote,
+        $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace );
     return $basket;
 }
 
@@ -565,7 +570,11 @@ sub GetBasketsByBookseller {
 
 =head3 GetBasketsInfosByBookseller
 
-    my $baskets = GetBasketsInfosByBookseller($supplierid);
+    my $baskets = GetBasketsInfosByBookseller($supplierid, $allbaskets);
+
+The optional second parameter allbaskets is a boolean allowing you to
+select all baskets from the supplier; by default only active baskets (open or 
+closed but still something to receive) are returned.
 
 Returns in a arrayref of hashref all about booksellers baskets, plus:
     total_biblios: Number of distinct biblios in basket
@@ -575,7 +584,7 @@ Returns in a arrayref of hashref all about booksellers baskets, plus:
 =cut
 
 sub GetBasketsInfosByBookseller {
-    my ($supplierid) = @_;
+    my ($supplierid, $allbaskets) = @_;
 
     return unless $supplierid;
 
@@ -592,9 +601,12 @@ sub GetBasketsInfosByBookseller {
           ) AS expected_items
         FROM aqbasket
           LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
-        WHERE booksellerid = ?
-        GROUP BY aqbasket.basketno
-    };
+        WHERE booksellerid = ?};
+    if(!$allbaskets) {
+        $query.=" AND (closedate IS NULL OR (aqorders.quantity > aqorders.quantityreceived AND datecancellationprinted IS NULL))";
+    }
+    $query.=" GROUP BY aqbasket.basketno";
+
     my $sth = $dbh->prepare($query);
     $sth->execute($supplierid);
     return $sth->fetchall_arrayref({});
@@ -640,8 +652,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->{'freedeliveryplace'} is the 'freedeliveryplace' 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.
@@ -653,8 +669,8 @@ sub NewBasketgroup {
     die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
     my $query = "INSERT INTO aqbasketgroups (";
     my @params;
-    foreach my $field ('name', 'deliveryplace', 'deliverycomment', 'closed') {
-        if ( $basketgroupinfo->{$field} ) {
+    foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
+        if ( defined $basketgroupinfo->{$field} ) {
             $query .= "$field, ";
             push(@params, $basketgroupinfo->{$field});
         }
@@ -697,6 +713,8 @@ $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the
 
 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
 
+$hashref->{'freedeliveryplace'} is the 'freedeliveryplace' 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.
@@ -798,110 +816,18 @@ Returns a reference to the array of all the basketgroups of bookseller $booksell
 
 sub GetBasketgroups {
     my $booksellerid = shift;
-    die "bookseller id is required to edit a basketgroup" unless $booksellerid;
-    my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY `id` DESC";
+    die 'bookseller id is required to edit a basketgroup' unless $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);
-    my $results = $sth->fetchall_arrayref({});
-    $sth->finish;
-    return $results
+    return $sth->fetchall_arrayref({});
 }
 
 #------------------------------------------------------------#
 
 =head2 FUNCTIONS ABOUT ORDERS
 
-=cut
-
-#------------------------------------------------------------#
-
-=head3 GetPendingOrders
-
-$orders = &GetPendingOrders($supplierid,$grouped,$owner,$basketno,$ordernumber,$search,$ean);
-
-Finds pending orders from the bookseller with the given ID. Ignores
-completed and cancelled orders.
-
-C<$booksellerid> contains the bookseller identifier
-C<$owner> contains 0 or 1. 0 means any owner. 1 means only the list of orders entered by the user itself.
-C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
-in a single result line
-C<$orders> is a reference-to-array; each element is a reference-to-hash.
-
-Used also by the filter in parcel.pl
-I have added:
-
-C<$ordernumber>
-C<$search>
-C<$ean>
-
-These give the value of the corresponding field in the aqorders table
-of the Koha database.
-
-Results are ordered from most to least recent.
-
-=cut
-
-sub GetPendingOrders {
-    my ($supplierid,$grouped,$owner,$basketno,$ordernumber,$search,$ean) = @_;
-    my $dbh = C4::Context->dbh;
-    my $strsth = "
-        SELECT ".($grouped?"count(*),":"")."aqbasket.basketno,
-               surname,firstname,biblio.*,biblioitems.isbn,
-               aqbasket.closedate, aqbasket.creationdate, aqbasket.basketname,
-               aqorders.*
-        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 (quantity > quantityreceived OR quantityreceived is NULL)
-        AND datecancellationprinted IS NULL";
-    my @query_params;
-    my $userenv = C4::Context->userenv;
-    if ( C4::Context->preference("IndependantBranches") ) {
-        if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
-            $strsth .= " AND (borrowers.branchcode = ?
-                        or borrowers.branchcode  = '')";
-            push @query_params, $userenv->{branch};
-        }
-    }
-    if ($supplierid) {
-        $strsth .= " AND aqbasket.booksellerid = ?";
-        push @query_params, $supplierid;
-    }
-    if($ordernumber){
-        $strsth .= " AND (aqorders.ordernumber=?)";
-        push @query_params, $ordernumber;
-    }
-    if($search){
-        $strsth .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
-        push @query_params, ("%$search%","%$search%","%$search%");
-    }
-    if ($ean) {
-        $strsth .= " AND biblioitems.ean = ?";
-        push @query_params, $ean;
-    }
-    if ($basketno) {
-        $strsth .= " AND aqbasket.basketno=? ";
-        push @query_params, $basketno;
-    }
-    if ($owner) {
-        $strsth .= " AND aqbasket.authorisedby=? ";
-        push @query_params, $userenv->{'number'};
-    }
-    $strsth .= " group by aqbasket.basketno" if $grouped;
-    $strsth .= " order by aqbasket.basketno";
-    my $sth = $dbh->prepare($strsth);
-    $sth->execute( @query_params );
-    my $results = $sth->fetchall_arrayref({});
-    $sth->finish;
-    return $results;
-}
-
-#------------------------------------------------------------#
-
 =head3 GetOrders
 
   @orders = &GetOrders($basketnumber, $orderby);
@@ -924,11 +850,14 @@ sub GetOrders {
         SELECT biblio.*,biblioitems.*,
                 aqorders.*,
                 aqbudgets.*,
-                biblio.title
+                biblio.title,
+                aqorders_transfers.ordernumber_from AS transferred_from,
+                aqorders_transfers.timestamp AS transferred_from_timestamp
         FROM    aqorders
             LEFT JOIN aqbudgets        ON aqbudgets.budget_id = aqorders.budget_id
             LEFT JOIN biblio           ON biblio.biblionumber = aqorders.biblionumber
             LEFT JOIN biblioitems      ON biblioitems.biblionumber =biblio.biblionumber
+            LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
         WHERE   basketno=?
             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
     ";
@@ -943,36 +872,38 @@ sub GetOrders {
 }
 
 #------------------------------------------------------------#
+=head3 GetOrdersByBiblionumber
 
-=head3 GetOrderNumber
-
-  $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
-
-Looks up the ordernumber with the given biblionumber and biblioitemnumber.
-
-Returns the number of this order.
-
-=over
+  @orders = &GetOrdersByBiblionumber($biblionumber);
 
-=item C<$ordernumber> is the order number.
+Looks up the orders with linked to a specific $biblionumber, including
+cancelled orders and received orders.
 
-=back
+return :
+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.
 
 =cut
 
-sub GetOrderNumber {
-    my ( $biblionumber,$biblioitemnumber ) = @_;
-    my $dbh = C4::Context->dbh;
-    my $query = "
-        SELECT ordernumber
-        FROM   aqorders
-        WHERE  biblionumber=?
-        AND    biblioitemnumber=?
+sub GetOrdersByBiblionumber {
+    my $biblionumber = shift;
+    return unless $biblionumber;
+    my $dbh   = C4::Context->dbh;
+    my $query  ="
+        SELECT biblio.*,biblioitems.*,
+                aqorders.*,
+                aqbudgets.*
+        FROM    aqorders
+            LEFT JOIN aqbudgets        ON aqbudgets.budget_id = aqorders.budget_id
+            LEFT JOIN biblio           ON biblio.biblionumber = aqorders.biblionumber
+            LEFT JOIN biblioitems      ON biblioitems.biblionumber =biblio.biblionumber
+        WHERE   aqorders.biblionumber=?
     ";
     my $sth = $dbh->prepare($query);
-    $sth->execute( $biblionumber, $biblioitemnumber );
-
-    return $sth->fetchrow;
+    $sth->execute($biblionumber);
+    my $results = $sth->fetchall_arrayref({});
+    $sth->finish;
+    return @$results;
 }
 
 #------------------------------------------------------------#
@@ -1006,6 +937,67 @@ sub GetOrder {
     return $data;
 }
 
+=head3 GetLastOrderNotReceivedFromSubscriptionid
+
+  $order = &GetLastOrderNotReceivedFromSubscriptionid($subscriptionid);
+
+Returns a reference-to-hash describing the last order not received for a subscription.
+
+=cut
+
+sub GetLastOrderNotReceivedFromSubscriptionid {
+    my ( $subscriptionid ) = @_;
+    my $dbh                = C4::Context->dbh;
+    my $query              = qq|
+        SELECT * FROM aqorders
+        LEFT JOIN subscription
+            ON ( aqorders.subscriptionid = subscription.subscriptionid )
+        WHERE aqorders.subscriptionid = ?
+            AND aqorders.datereceived IS NULL
+        LIMIT 1
+    |;
+    my $sth = $dbh->prepare( $query );
+    $sth->execute( $subscriptionid );
+    my $order = $sth->fetchrow_hashref;
+    return $order;
+}
+
+=head3 GetLastOrderReceivedFromSubscriptionid
+
+  $order = &GetLastOrderReceivedFromSubscriptionid($subscriptionid);
+
+Returns a reference-to-hash describing the last order received for a subscription.
+
+=cut
+
+sub GetLastOrderReceivedFromSubscriptionid {
+    my ( $subscriptionid ) = @_;
+    my $dbh                = C4::Context->dbh;
+    my $query              = qq|
+        SELECT * FROM aqorders
+        LEFT JOIN subscription
+            ON ( aqorders.subscriptionid = subscription.subscriptionid )
+        WHERE aqorders.subscriptionid = ?
+            AND aqorders.datereceived =
+                (
+                    SELECT MAX( aqorders.datereceived )
+                    FROM aqorders
+                    LEFT JOIN subscription
+                        ON ( aqorders.subscriptionid = subscription.subscriptionid )
+                        WHERE aqorders.subscriptionid = ?
+                            AND aqorders.datereceived IS NOT NULL
+                )
+        ORDER BY ordernumber DESC
+        LIMIT 1
+    |;
+    my $sth = $dbh->prepare( $query );
+    $sth->execute( $subscriptionid, $subscriptionid );
+    my $order = $sth->fetchrow_hashref;
+    return $order;
+
+}
+
+
 #------------------------------------------------------------#
 
 =head3 NewOrder
@@ -1032,7 +1024,7 @@ Else, the upcoming July 1st is used.
 
 =item defaults entrydate to Now
 
-The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "biblioitemnumber", "rrp", "ecost", "gstrate", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "bookfundid".
+The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "rrp", "ecost", "gstrate", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "budget_id".
 
 =back
 
@@ -1124,6 +1116,9 @@ sub ModOrder {
     my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
     $sth->execute;
     my $colnames = $sth->{NAME};
+        #FIXME Be careful. If aqorders would have columns with diacritics,
+        #you should need to decode what you get back from NAME.
+        #See report 10110 and guided_reports.pl
     my $query = "UPDATE aqorders SET ";
 
     foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
@@ -1144,37 +1139,6 @@ sub ModOrder {
 
 #------------------------------------------------------------#
 
-=head3 ModOrderItem
-
-  &ModOrderItem(\%hashref);
-
-Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
-
-=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 ModItemOrder
 
     ModItemOrder($itemnumber, $ordernumber);
@@ -1200,29 +1164,6 @@ sub ModItemOrder {
 
 #------------------------------------------------------------#
 
-
-=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,$ordernumber, $biblionumber) = @_;
-    my $dbh = C4::Context->dbh;
-    my $query = "
-    UPDATE aqorders
-    SET    biblioitemnumber = ?
-    WHERE  ordernumber = ?
-    AND biblionumber =  ?";
-    my $sth = $dbh->prepare($query);
-    $sth->execute( $biblioitemnumber, $ordernumber, $biblionumber );
-}
-
 =head3 GetCancelledOrders
 
   my @orders = GetCancelledOrders($basketno, $orderby);
@@ -1238,11 +1179,18 @@ sub GetCancelledOrders {
 
     my $dbh   = C4::Context->dbh;
     my $query = "
-        SELECT biblio.*, biblioitems.*, aqorders.*, aqbudgets.*
+        SELECT
+            biblio.*,
+            biblioitems.*,
+            aqorders.*,
+            aqbudgets.*,
+            aqorders_transfers.ordernumber_to AS transferred_to,
+            aqorders_transfers.timestamp AS transferred_to_timestamp
         FROM aqorders
           LEFT JOIN aqbudgets   ON aqbudgets.budget_id = aqorders.budget_id
           LEFT JOIN biblio      ON biblio.biblionumber = aqorders.biblionumber
           LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
+          LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_from = aqorders.ordernumber
         WHERE basketno = ?
           AND (datecancellationprinted IS NOT NULL
                AND datecancellationprinted <> '0000-00-00')
@@ -1264,8 +1212,7 @@ sub GetCancelledOrders {
 =head3 ModReceiveOrder
 
   &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
-    $unitprice, $invoiceid, $biblioitemnumber,
-    $bookfund, $rrp, \@received_itemnumbers);
+    $cost, $ecost, $invoiceid, rrp, budget_id, datereceived, \@received_itemnumbers);
 
 Updates an order, to reflect the fact that it was received, at least
 in part. All arguments not mentioned below update the fields with the
@@ -1329,7 +1276,8 @@ sub ModReceiveOrder {
         $order->{'rrp'} = $rrp;
         $order->{ecost} = $ecost;
         $order->{'orderstatus'} = 3;    # totally received
-        $new_ordernumber = NewOrder($order);
+        my $basketno;
+        ( $basketno, $new_ordernumber ) = NewOrder($order);
 
         if ($received_items) {
             foreach my $itemnumber (@$received_items) {
@@ -1463,80 +1411,120 @@ sub CancelReceipt {
 
 #------------------------------------------------------------#
 
-=head3 SearchOrder
+=head3 SearchOrders
 
-@results = &SearchOrder($search, $biblionumber, $complete);
+@results = &SearchOrders({
+    ordernumber => $ordernumber,
+    search => $search,
+    biblionumber => $biblionumber,
+    ean => $ean,
+    booksellerid => $booksellerid,
+    basketno => $basketno,
+    owner => $owner,
+    pending => $pending
+});
 
 Searches for orders.
 
-C<$search> may take one of several forms: if it is an ISBN,
-C<&ordersearch> returns orders with that ISBN. If C<$search> is an
-order number, C<&ordersearch> returns orders with that order number
-and biblionumber C<$biblionumber>. Otherwise, C<$search> is considered
-to be a space-separated list of search terms; in this case, all of the
-terms must appear in the title (matching the beginning of title
-words).
-
-If C<$complete> is C<yes>, the results will include only completed
-orders. In any case, C<&ordersearch> ignores cancelled orders.
-
-C<&ordersearch> returns an array.
-C<@results> is an array of references-to-hash with the following keys:
-
-=over 4
-
-=item C<author>
-
-=item C<seriestitle>
+C<$owner> Finds order for the logged in user.
+C<$pending> Finds pending orders. Ignores completed and cancelled orders.
 
-=item C<branchcode>
 
-=item C<bookfundid>
-
-=back
+C<@results> is an array of references-to-hash with the keys are fields
+from aqorders, biblio, biblioitems and aqbasket tables.
 
 =cut
 
-sub SearchOrder {
-#### -------- SearchOrder-------------------------------
-    my ( $ordernumber, $search, $ean, $supplierid, $basket ) = @_;
+sub SearchOrders {
+    my ( $params ) = @_;
+    my $ordernumber = $params->{ordernumber};
+    my $search = $params->{search};
+    my $ean = $params->{ean};
+    my $booksellerid = $params->{booksellerid};
+    my $basketno = $params->{basketno};
+    my $basketname = $params->{basketname};
+    my $basketgroupname = $params->{basketgroupname};
+    my $owner = $params->{owner};
+    my $pending = $params->{pending};
 
     my $dbh = C4::Context->dbh;
     my @args = ();
-    my $query =
-            "SELECT *
-            FROM aqorders
+    my $query = q{
+        SELECT aqbasket.basketno,
+               borrowers.surname,
+               borrowers.firstname,
+               biblio.*,
+               biblioitems.isbn,
+               biblioitems.biblioitemnumber,
+               aqbasket.closedate,
+               aqbasket.creationdate,
+               aqbasket.basketname,
+               aqorders.*
+        FROM aqorders
+            LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
+            LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
+            LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
             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)";
+        WHERE (datecancellationprinted is NULL)
+    };
+
+    $query .= q{
+        AND (quantity > quantityreceived OR quantityreceived is NULL)
+    } if $pending;
+
+    my $userenv = C4::Context->userenv;
+    if ( C4::Context->preference("IndependentBranches") ) {
+        if ( ( $userenv ) and ( $userenv->{flags} != 1 ) ) {
+            $query .= q{
+                AND (
+                    borrowers.branchcode = ?
+                    OR borrowers.branchcode  = ''
+                )
+            };
+            push @args, $userenv->{branch};
+        }
+    }
 
-    if($ordernumber){
-        $query .= " AND (aqorders.ordernumber=?)";
+    if ( $ordernumber ) {
+        $query .= ' AND (aqorders.ordernumber=?)';
         push @args, $ordernumber;
     }
-    if($search){
-        $query .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
+    if( $search ) {
+        $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)';
         push @args, ("%$search%","%$search%","%$search%");
     }
-    if ($ean) {
-        $query .= " AND biblioitems.ean = ?";
+    if ( $ean ) {
+        $query .= ' AND biblioitems.ean = ?';
         push @args, $ean;
     }
-    if ($supplierid) {
-        $query .= "AND aqbasket.booksellerid = ?";
-        push @args, $supplierid;
+    if ( $booksellerid ) {
+        $query .= 'AND aqbasket.booksellerid = ?';
+        push @args, $booksellerid;
+    }
+    if( $basketno ) {
+        $query .= 'AND aqbasket.basketno = ?';
+        push @args, $basketno;
     }
-    if($basket){
-        $query .= "AND aqorders.basketno = ?";
-        push @args, $basket;
+    if( $basketname ) {
+        $query .= 'AND aqbasket.basketname LIKE ?';
+        push @args, "%$basketname%";
+    }
+    if( $basketgroupname ) {
+        $query .= ' AND aqbasketgroups.name LIKE ?';
+        push @args, "%$basketgroupname%";
     }
 
+    if ( $owner ) {
+        $query .= ' AND aqbasket.authorisedby=? ';
+        push @args, $userenv->{'number'};
+    }
+
+    $query .= ' ORDER BY aqbasket.basketno';
+
     my $sth = $dbh->prepare($query);
     $sth->execute(@args);
-    my $results = $sth->fetchall_arrayref({});
-    $sth->finish;
-    return $results;
+    return $sth->fetchall_arrayref({});
 }
 
 #------------------------------------------------------------#
@@ -1569,6 +1557,64 @@ sub DelOrder {
     
 }
 
+=head3 TransferOrder
+
+    my $newordernumber = TransferOrder($ordernumber, $basketno);
+
+Transfer an order line to a basket.
+Mark $ordernumber as cancelled with an internal note 'Cancelled and transfered
+to BOOKSELLER on DATE' and create new order with internal note
+'Transfered from BOOKSELLER on DATE'.
+Move all attached items to the new order.
+Received orders cannot be transfered.
+Return the ordernumber of created order.
+
+=cut
+
+sub TransferOrder {
+    my ($ordernumber, $basketno) = @_;
+
+    return unless ($ordernumber and $basketno);
+
+    my $order = GetOrder( $ordernumber );
+    return if $order->{datereceived};
+    my $basket = GetBasket($basketno);
+    return unless $basket;
+
+    my $dbh = C4::Context->dbh;
+    my ($query, $sth, $rv);
+
+    $query = qq{
+        UPDATE aqorders
+        SET datecancellationprinted = CAST(NOW() AS date)
+        WHERE ordernumber = ?
+    };
+    $sth = $dbh->prepare($query);
+    $rv = $sth->execute($ordernumber);
+
+    delete $order->{'ordernumber'};
+    $order->{'basketno'} = $basketno;
+    my $newordernumber;
+    (undef, $newordernumber) = NewOrder($order);
+
+    $query = qq{
+        UPDATE aqorders_items
+        SET ordernumber = ?
+        WHERE ordernumber = ?
+    };
+    $sth = $dbh->prepare($query);
+    $sth->execute($newordernumber, $ordernumber);
+
+    $query = q{
+        INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to)
+        VALUES (?, ?)
+    };
+    $sth = $dbh->prepare($query);
+    $sth->execute($ordernumber, $newordernumber);
+
+    return $newordernumber;
+}
+
 =head2 FUNCTIONS ABOUT PARCELS
 
 =cut
@@ -1624,7 +1670,7 @@ sub GetParcel {
             AND aqorders.datereceived = ? ";
 
     my @query_params = ( $supplierid, $code, $datereceived );
-    if ( C4::Context->preference("IndependantBranches") ) {
+    if ( C4::Context->preference("IndependentBranches") ) {
         my $userenv = C4::Context->userenv;
         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
             $strsth .= " and (borrowers.branchcode = ?
@@ -1795,8 +1841,8 @@ sub GetLateOrders {
     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,
+        aqorders.quantity - COALESCE(aqorders.quantityreceived,0)                 AS quantity,
+        (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
         DATEDIFF(CAST(now() AS date),closedate) AS latesince
         ";
         if ( defined $delay ) {
@@ -1843,7 +1889,7 @@ sub GetLateOrders {
     if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
         $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
     }
-    if (C4::Context->preference("IndependantBranches")
+    if (C4::Context->preference("IndependentBranches")
             && C4::Context->userenv
             && C4::Context->userenv->{flags} != 1 ) {
         $from .= ' AND borrowers.branchcode LIKE ? ';
@@ -1940,6 +1986,7 @@ sub GetHistory {
             aqorders.quantityreceived,
             aqorders.ecost,
             aqorders.ordernumber,
+            aqorders.invoiceid,
             aqinvoices.invoicenumber,
             aqbooksellers.id as id,
             aqorders.biblionumber
@@ -1952,7 +1999,7 @@ sub GetHistory {
     LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid";
 
     $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
-    if ( C4::Context->preference("IndependantBranches") );
+    if ( C4::Context->preference("IndependentBranches") );
 
     $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
 
@@ -2012,7 +2059,7 @@ sub GetHistory {
         push @query_params, "%$basketgroupname%";
     }
 
-    if ( C4::Context->preference("IndependantBranches") ) {
+    if ( C4::Context->preference("IndependentBranches") ) {
         my $userenv = C4::Context->userenv;
         if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
             $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
@@ -2319,9 +2366,11 @@ Orders informations are in $invoice->{orders} (array ref)
 
 sub GetInvoiceDetails {
     my ($invoiceid) = @_;
-    my $invoice;
 
-    return unless $invoiceid;
+    if ( !defined $invoiceid ) {
+        carp 'GetInvoiceDetails called without an invoiceid';
+        return;
+    }
 
     my $dbh = C4::Context->dbh;
     my $query = qq{
@@ -2333,11 +2382,13 @@ sub GetInvoiceDetails {
     my $sth = $dbh->prepare($query);
     $sth->execute($invoiceid);
 
-    $invoice = $sth->fetchrow_hashref;
+    my $invoice = $sth->fetchrow_hashref;
 
     $query = qq{
-        SELECT aqorders.*, biblio.*
+        SELECT aqorders.*, biblio.*,
+        aqbasket.basketname
         FROM aqorders
+          LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
           LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
         WHERE invoiceid = ?
     };
@@ -2491,6 +2542,64 @@ sub ReopenInvoice {
     $sth->execute($invoiceid);
 }
 
+=head3 DelInvoice
+
+    DelInvoice($invoiceid);
+
+Delete an invoice if there are no items attached to it.
+
+=cut
+
+sub DelInvoice {
+    my ($invoiceid) = @_;
+
+    return unless $invoiceid;
+
+    my $dbh   = C4::Context->dbh;
+    my $query = qq{
+        SELECT COUNT(*)
+        FROM aqorders
+        WHERE invoiceid = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($invoiceid);
+    my $res = $sth->fetchrow_arrayref;
+    if ( $res && $res->[0] == 0 ) {
+        $query = qq{
+            DELETE FROM aqinvoices
+            WHERE invoiceid = ?
+        };
+        my $sth = $dbh->prepare($query);
+        return ( $sth->execute($invoiceid) > 0 );
+    }
+    return;
+}
+
+=head3 MergeInvoices
+
+    MergeInvoices($invoiceid, \@sourceids);
+
+Merge the invoices identified by the IDs in \@sourceids into
+the invoice identified by $invoiceid.
+
+=cut
+
+sub MergeInvoices {
+    my ($invoiceid, $sourceids) = @_;
+
+    return unless $invoiceid;
+    foreach my $sourceid (@$sourceids) {
+        next if $sourceid == $invoiceid;
+        my $source = GetInvoiceDetails($sourceid);
+        foreach my $order (@{$source->{'orders'}}) {
+            $order->{'invoiceid'} = $invoiceid;
+            ModOrder($order);
+        }
+        DelInvoice($source->{'invoiceid'});
+    }
+    return;
+}
+
 1;
 __END__