Bug 11058: fix compilation warning in C4::Record
[koha.git] / C4 / Acquisition.pm
index 9678ffc..e470b24 100644 (file)
@@ -53,17 +53,27 @@ BEGIN {
         &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
         &GetBasketgroups &ReOpenBasketgroup
 
-        &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
-        &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
-        &SearchOrder &GetHistory &GetRecentAcqui
-        &ModReceiveOrder &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
 
+        &GetInvoices
+        &GetInvoice
+        &GetInvoiceDetails
+        &AddInvoice
+        &ModInvoice
+        &CloseInvoice
+        &ReopenInvoice
+        &DelInvoice
+        &MergeInvoices
+
         &GetItemnumbersFromOrder
 
         &AddClaim
@@ -165,7 +175,7 @@ sub GetBasket {
 =head3 NewBasket
 
   $basket = &NewBasket( $booksellerid, $authorizedby, $basketname, 
-      $basketnote, $basketbooksellernote, $basketcontractnumber );
+      $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace );
 
 Create a new basket in aqbasket table
 
@@ -181,21 +191,22 @@ The other parameters are optional, see ModBasketHeader for more info on them.
 
 =cut
 
-# FIXME : this function seems to be unused.
-
 sub NewBasket {
-    my ( $booksellerid, $authorisedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber ) = @_;
+    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);
+    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;
 }
 
@@ -257,8 +268,8 @@ sub GetBasketAsCSV {
             notes => $order->{'notes'},
             quantity => $order->{'quantity'},
             rrp => $order->{'rrp'},
-            deliveryplace => $basket->{'deliveryplace'},
-            billingplace => $basket->{'billingplace'}
+            deliveryplace => C4::Branch::GetBranchName( $basket->{'deliveryplace'} ),
+            billingplace => C4::Branch::GetBranchName( $basket->{'billingplace'} ),
         };
         foreach(qw(
             contractname author title publishercode collectiontitle notes
@@ -307,6 +318,7 @@ sub GetBasketGroupAsCSV {
         my @orders     = GetOrders( $$basket{basketno} );
         my $contract   = GetContract( $$basket{contractnumber} );
         my $bookseller = GetBookSellerFromId( $$basket{booksellerid} );
+        my $basketgroup = GetBasketgroup( $$basket{basketgroupid} );
 
         foreach my $order (@orders) {
             my $bd = GetBiblioData( $order->{'biblionumber'} );
@@ -331,6 +343,10 @@ sub GetBasketGroupAsCSV {
                 booksellerpostal => $bookseller->{postal},
                 contractnumber => $contract->{contractnumber},
                 contractname => $contract->{contractname},
+                basketgroupdeliveryplace => C4::Branch::GetBranchName( $basketgroup->{deliveryplace} ),
+                basketgroupbillingplace => C4::Branch::GetBranchName( $basketgroup->{billingplace} ),
+                basketdeliveryplace => C4::Branch::GetBranchName( $basket->{deliveryplace} ),
+                basketbillingplace => C4::Branch::GetBranchName( $basket->{billingplace} ),
             };
             foreach(qw(
                 basketname author title publishercode collectiontitle notes
@@ -478,17 +494,25 @@ Modifies a basket's header.
 
 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
 
+=item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
+
+=item C<$billingplace> is the "billingplace" field in the aqbasket table.
+
 =back
 
 =cut
 
 sub ModBasketHeader {
-    my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid) = @_;
+    my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace) = @_;
+    my $query = qq{
+        UPDATE aqbasket
+        SET basketname=?, note=?, booksellernote=?, booksellerid=?, deliveryplace=?, billingplace=?
+        WHERE basketno=?
+    };
 
-    my $query = "UPDATE aqbasket SET basketname=?, note=?, booksellernote=?, booksellerid=? WHERE basketno=?";
     my $dbh = C4::Context->dbh;
     my $sth = $dbh->prepare($query);
-    $sth->execute($basketname,$note,$booksellernote,$booksellerid,$basketno);
+    $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $basketno);
 
     if ( $contractnumber ) {
         my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
@@ -546,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
@@ -556,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;
 
@@ -565,12 +593,20 @@ sub GetBasketsInfosByBookseller {
         SELECT aqbasket.*,
           SUM(aqorders.quantity) AS total_items,
           COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
-          SUM(IF(aqorders.datereceived IS NULL, aqorders.quantity, 0)) AS expected_items
+          SUM(
+            IF(aqorders.datereceived IS NULL
+              AND aqorders.datecancellationprinted IS NULL
+            , aqorders.quantity
+            , 0)
+          ) 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({});
@@ -616,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.
@@ -629,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});
         }
@@ -673,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.
@@ -774,102 +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($booksellerid, $grouped, $owner);
-
-Finds pending orders from the bookseller with the given ID. Ignores
-completed and cancelled orders.
-
-C<$booksellerid> contains the bookseller identifier
-C<$grouped> contains 0 or 1. 0 means returns the list, 1 means return the total
-C<$owner> contains 0 or 1. 0 means any owner. 1 means only the list of orders entered by the user itself.
-
-C<$orders> is a reference-to-array; each element is a
-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
-
-=item C<authorizedby>
-
-=item C<entrydate>
-
-=item C<basketno>
-
-=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.
-
-=cut
-
-sub GetPendingOrders {
-    my ($supplierid,$grouped,$owner,$basketno) = @_;
-    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 booksellerid=?
-            AND (quantity > quantityreceived OR quantityreceived is NULL)
-            AND datecancellationprinted IS NULL";
-    my @query_params = ( $supplierid );
-    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 ($owner) {
-        $strsth .= " AND aqbasket.authorisedby=? ";
-        push @query_params, $userenv->{'number'};
-    }
-    if ($basketno) {
-        $strsth .= " AND aqbasket.basketno=? ";
-        push @query_params, $basketno;
-    }
-    $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);
@@ -892,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')
     ";
@@ -911,36 +872,38 @@ sub GetOrders {
 }
 
 #------------------------------------------------------------#
+=head3 GetOrdersByBiblionumber
 
-=head3 GetOrderNumber
+  @orders = &GetOrdersByBiblionumber($biblionumber);
 
-  $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
+Looks up the orders with linked to a specific $biblionumber, including
+cancelled orders and received orders.
 
-Looks up the ordernumber with the given biblionumber and biblioitemnumber.
-
-Returns the number of this order.
-
-=over
-
-=item C<$ordernumber> is the order number.
-
-=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;
 }
 
 #------------------------------------------------------------#
@@ -974,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
@@ -1000,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", "gst", "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
 
@@ -1029,6 +1053,14 @@ sub NewOrder {
     }
 
     my $ordernumber=InsertInTable("aqorders",$orderinfo);
+    if (not $orderinfo->{parent_ordernumber}) {
+        my $sth = $dbh->prepare("
+            UPDATE aqorders
+            SET parent_ordernumber = ordernumber
+            WHERE ordernumber = ?
+        ");
+        $sth->execute($ordernumber);
+    }
     return ( $orderinfo->{'basketno'}, $ordernumber );
 }
 
@@ -1084,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)){
@@ -1104,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);
@@ -1160,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);
@@ -1198,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')
@@ -1224,15 +1212,13 @@ sub GetCancelledOrders {
 =head3 ModReceiveOrder
 
   &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
-    $unitprice, $booksellerinvoicenumber, $biblioitemnumber,
-    $freight, $bookfund, $rrp);
+    $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
 same name in the aqorders table of the Koha database.
 
-If a partial order is received, splits the order into two.  The received
-portion must have a booksellerinvoicenumber.
+If a partial order is received, splits the order into two.
 
 Updates the order with bibilionumber C<$biblionumber> and ordernumber
 C<$ordernumber>.
@@ -1242,10 +1228,11 @@ C<$ordernumber>.
 
 sub ModReceiveOrder {
     my (
-        $biblionumber,    $ordernumber,  $quantrec, $user, $cost,
-        $invoiceno, $freight, $rrp, $budget_id, $datereceived, $received_items
+        $biblionumber,    $ordernumber,  $quantrec, $user, $cost, $ecost,
+        $invoiceid, $rrp, $budget_id, $datereceived, $received_items
     )
     = @_;
+
     my $dbh = C4::Context->dbh;
     $datereceived = C4::Dates->output('iso') unless $datereceived;
     my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
@@ -1264,126 +1251,280 @@ sub ModReceiveOrder {
     my $order = $sth->fetchrow_hashref();
     $sth->finish();
 
+    my $new_ordernumber = $ordernumber;
     if ( $order->{quantity} > $quantrec ) {
+        # Split order line in two parts: the first is the original order line
+        # without received items (the quantity is decreased),
+        # the second part is a new order line with quantity=quantityrec
+        # (entirely received)
         $sth=$dbh->prepare("
             UPDATE aqorders
-            SET quantityreceived=?
-                , datereceived=?
-                , booksellerinvoicenumber=?
-                , unitprice=?
-                , freight=?
-                , rrp=?
-                , quantity=?
-            WHERE biblionumber=? AND ordernumber=?");
-
-        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordernumber);
+            SET quantity = ?
+            WHERE ordernumber = ?
+        ");
+
+        $sth->execute($order->{quantity} - $quantrec, $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);
-        # Change ordernumber in aqorders_items for items not received
-        my @orderitems = GetItemnumbersFromOrder( $order->{'ordernumber'} );
-        my $count = scalar @orderitems;
-
-        for (my $i=0; $i<$count; $i++){
-            foreach (@$received_items){
-                splice (@orderitems, $i, 1) if ($orderitems[$i] == $_);
+        delete $order->{'ordernumber'};
+        $order->{'quantity'} = $quantrec;
+        $order->{'quantityreceived'} = $quantrec;
+        $order->{'datereceived'} = $datereceived;
+        $order->{'invoiceid'} = $invoiceid;
+        $order->{'unitprice'} = $cost;
+        $order->{'rrp'} = $rrp;
+        $order->{ecost} = $ecost;
+        $order->{'orderstatus'} = 3;    # totally received
+        my $basketno;
+        ( $basketno, $new_ordernumber ) = NewOrder($order);
+
+        if ($received_items) {
+            foreach my $itemnumber (@$received_items) {
+                ModItemOrder($itemnumber, $new_ordernumber);
             }
         }
-        foreach (@orderitems) {
-            ModItemOrder($_, $newOrder);
-        }
     } else {
         $sth=$dbh->prepare("update aqorders
-                            set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?,
-                                unitprice=?,freight=?,rrp=?
+                            set quantityreceived=?,datereceived=?,invoiceid=?,
+                                unitprice=?,rrp=?,ecost=?
                             where biblionumber=? and ordernumber=?");
-        $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordernumber);
+        $sth->execute($quantrec,$datereceived,$invoiceid,$cost,$rrp,$ecost,$biblionumber,$ordernumber);
         $sth->finish;
     }
-    return $datereceived;
+    return ($datereceived, $new_ordernumber);
 }
-#------------------------------------------------------------#
 
-=head3 SearchOrder
+=head3 CancelReceipt
 
-@results = &SearchOrder($search, $biblionumber, $complete);
+    my $parent_ordernumber = CancelReceipt($ordernumber);
 
-Searches for orders.
+    Cancel an order line receipt and update the parent order line, as if no
+    receipt was made.
+    If items are created at receipt (AcqCreateItem = receiving) then delete
+    these items.
 
-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).
+=cut
 
-If C<$complete> is C<yes>, the results will include only completed
-orders. In any case, C<&ordersearch> ignores cancelled orders.
+sub CancelReceipt {
+    my $ordernumber = shift;
 
-C<&ordersearch> returns an array.
-C<@results> is an array of references-to-hash with the following keys:
+    return unless $ordernumber;
 
-=over 4
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        SELECT datereceived, parent_ordernumber, quantity
+        FROM aqorders
+        WHERE ordernumber = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($ordernumber);
+    my $order = $sth->fetchrow_hashref;
+    unless($order) {
+        warn "CancelReceipt: order $ordernumber does not exist";
+        return;
+    }
+    unless($order->{'datereceived'}) {
+        warn "CancelReceipt: order $ordernumber is not received";
+        return;
+    }
+
+    my $parent_ordernumber = $order->{'parent_ordernumber'};
+
+    if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
+        # The order line has no parent, just mark it as not received
+        $query = qq{
+            UPDATE aqorders
+            SET quantityreceived = ?,
+                datereceived = ?,
+                invoiceid = ?
+            WHERE ordernumber = ?
+        };
+        $sth = $dbh->prepare($query);
+        $sth->execute(0, undef, undef, $ordernumber);
+    } else {
+        # The order line has a parent, increase parent quantity and delete
+        # the order line.
+        $query = qq{
+            SELECT quantity, datereceived
+            FROM aqorders
+            WHERE ordernumber = ?
+        };
+        $sth = $dbh->prepare($query);
+        $sth->execute($parent_ordernumber);
+        my $parent_order = $sth->fetchrow_hashref;
+        unless($parent_order) {
+            warn "Parent order $parent_ordernumber does not exist.";
+            return;
+        }
+        if($parent_order->{'datereceived'}) {
+            warn "CancelReceipt: parent order is received.".
+                " Can't cancel receipt.";
+            return;
+        }
+        $query = qq{
+            UPDATE aqorders
+            SET quantity = ?
+            WHERE ordernumber = ?
+        };
+        $sth = $dbh->prepare($query);
+        my $rv = $sth->execute(
+            $order->{'quantity'} + $parent_order->{'quantity'},
+            $parent_ordernumber
+        );
+        unless($rv) {
+            warn "Cannot update parent order line, so do not cancel".
+                " receipt";
+            return;
+        }
+        if(C4::Context->preference('AcqCreateItem') eq 'receiving') {
+            # Remove items that were created at receipt
+            $query = qq{
+                DELETE FROM items, aqorders_items
+                USING items, aqorders_items
+                WHERE items.itemnumber = ? AND aqorders_items.itemnumber = ?
+            };
+            $sth = $dbh->prepare($query);
+            my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
+            foreach my $itemnumber (@itemnumbers) {
+                $sth->execute($itemnumber, $itemnumber);
+            }
+        } else {
+            # Update items
+            my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
+            foreach my $itemnumber (@itemnumbers) {
+                ModItemOrder($itemnumber, $parent_ordernumber);
+            }
+        }
+        # Delete order line
+        $query = qq{
+            DELETE FROM aqorders
+            WHERE ordernumber = ?
+        };
+        $sth = $dbh->prepare($query);
+        $sth->execute($ordernumber);
 
-=item C<author>
+    }
 
-=item C<seriestitle>
+    return $parent_ordernumber;
+}
 
-=item C<branchcode>
+#------------------------------------------------------------#
 
-=item C<bookfundid>
+=head3 SearchOrders
 
-=back
+@results = &SearchOrders({
+    ordernumber => $ordernumber,
+    search => $search,
+    biblionumber => $biblionumber,
+    ean => $ean,
+    booksellerid => $booksellerid,
+    basketno => $basketno,
+    owner => $owner,
+    pending => $pending
+});
+
+Searches for orders.
+
+C<$owner> Finds order for the logged in user.
+C<$pending> Finds pending orders. Ignores completed and cancelled orders.
+
+
+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( $basketname ) {
+        $query .= 'AND aqbasket.basketname LIKE ?';
+        push @args, "%$basketname%";
     }
-    if($basket){
-        $query .= "AND aqorders.basketno = ?";
-        push @args, $basket;
+    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({});
 }
 
 #------------------------------------------------------------#
@@ -1416,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
@@ -1451,24 +1650,27 @@ sub GetParcel {
                 firstname,
                 aqorders.biblionumber,
                 aqorders.ordernumber,
+                aqorders.parent_ordernumber,
                 aqorders.quantity,
                 aqorders.quantityreceived,
                 aqorders.unitprice,
                 aqorders.listprice,
                 aqorders.rrp,
                 aqorders.ecost,
+                aqorders.gstrate,
                 biblio.title
         FROM aqorders
         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
         LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
+        LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
         WHERE
             aqbasket.booksellerid = ?
-            AND aqorders.booksellerinvoicenumber LIKE ?
+            AND aqinvoices.invoicenumber LIKE ?
             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 = ?
@@ -1537,18 +1739,19 @@ sub GetParcels {
     my $dbh    = C4::Context->dbh;
     my @query_params = ();
     my $strsth ="
-        SELECT  aqorders.booksellerinvoicenumber,
+        SELECT  aqinvoices.invoicenumber,
                 datereceived,purchaseordernumber,
                 count(DISTINCT biblionumber) AS biblio,
                 sum(quantity) AS itemsexpected,
                 sum(quantityreceived) AS itemsreceived
         FROM   aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
+        LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
         WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
     ";
     push @query_params, $bookseller;
 
     if ( defined $code ) {
-        $strsth .= ' and aqorders.booksellerinvoicenumber like ? ';
+        $strsth .= ' and aqinvoices.invoicenumber like ? ';
         # add a % to the end of the code to allow stemming.
         push @query_params, "$code%";
     }
@@ -1563,7 +1766,7 @@ sub GetParcels {
         push @query_params, $dateto;
     }
 
-    $strsth .= "group by aqorders.booksellerinvoicenumber,datereceived ";
+    $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
 
     # can't use a placeholder to place this column name.
     # but, we could probably be checking to make sure it is a column that will be fetched.
@@ -1638,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 ) {
@@ -1671,19 +1874,22 @@ sub GetLateOrders {
         $from .= ' AND borrowers.branchcode LIKE ? ';
         push @query_params, $branch;
     }
+
+    if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
+        $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
+    }
     if ( defined $estimateddeliverydatefrom ) {
-        $from .= '
-            AND aqbooksellers.deliverytime IS NOT NULL
-            AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
+        $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
         push @query_params, $estimateddeliverydatefrom;
     }
-    if ( defined $estimateddeliverydatefrom and defined $estimateddeliverydateto ) {
+    if ( defined $estimateddeliverydateto ) {
         $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
         push @query_params, $estimateddeliverydateto;
-    } elsif ( defined $estimateddeliverydatefrom ) {
+    }
+    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 ? ';
@@ -1756,6 +1962,7 @@ sub GetHistory {
     my $to_placed_on = $params{to_placed_on};
     my $basket = $params{basket};
     my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
+    my $basketgroupname = $params{basketgroupname};
     my @order_loop;
     my $total_qty         = 0;
     my $total_qtyreceived = 0;
@@ -1779,7 +1986,8 @@ sub GetHistory {
             aqorders.quantityreceived,
             aqorders.ecost,
             aqorders.ordernumber,
-            aqorders.booksellerinvoicenumber as invoicenumber,
+            aqorders.invoiceid,
+            aqinvoices.invoicenumber,
             aqbooksellers.id as id,
             aqorders.biblionumber
         FROM aqorders
@@ -1787,10 +1995,11 @@ sub GetHistory {
         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";
+        LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
+    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') ";
 
@@ -1841,11 +2050,16 @@ sub GetHistory {
     }
 
     if ($booksellerinvoicenumber) {
-        $query .= " AND (aqorders.booksellerinvoicenumber LIKE ? OR aqbasket.booksellerinvoicenumber LIKE ?)";
-        push @query_params, "%$booksellerinvoicenumber%", "%$booksellerinvoicenumber%";
+        $query .= " AND aqinvoices.invoicenumber LIKE ? ";
+        push @query_params, "%$booksellerinvoicenumber%";
     }
 
-    if ( C4::Context->preference("IndependantBranches") ) {
+    if ($basketgroupname) {
+        $query .= " AND aqbasketgroups.name LIKE ? ";
+        push @query_params, "%$basketgroupname%";
+    }
+
+    if ( C4::Context->preference("IndependentBranches") ) {
         my $userenv = C4::Context->userenv;
         if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
             $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
@@ -1983,7 +2197,407 @@ sub AddClaim {
         ";
     my $sth = $dbh->prepare($query);
     $sth->execute($ordernumber);
+}
+
+=head3 GetInvoices
+
+    my @invoices = GetInvoices(
+        invoicenumber => $invoicenumber,
+        suppliername => $suppliername,
+        shipmentdatefrom => $shipmentdatefrom, # ISO format
+        shipmentdateto => $shipmentdateto, # ISO format
+        billingdatefrom => $billingdatefrom, # ISO format
+        billingdateto => $billingdateto, # ISO format
+        isbneanissn => $isbn_or_ean_or_issn,
+        title => $title,
+        author => $author,
+        publisher => $publisher,
+        publicationyear => $publicationyear,
+        branchcode => $branchcode,
+        order_by => $order_by
+    );
+
+Return a list of invoices that match all given criteria.
+
+$order_by is "column_name (asc|desc)", where column_name is any of
+'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
+'shipmentcost', 'shipmentcost_budgetid'.
+
+asc is the default if omitted
+
+=cut
+
+sub GetInvoices {
+    my %args = @_;
+
+    my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
+        closedate shipmentcost shipmentcost_budgetid);
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        SELECT aqinvoices.*, aqbooksellers.name AS suppliername,
+          COUNT(
+            DISTINCT IF(
+              aqorders.datereceived IS NOT NULL,
+              aqorders.biblionumber,
+              NULL
+            )
+          ) AS receivedbiblios,
+          SUM(aqorders.quantityreceived) AS receiveditems
+        FROM aqinvoices
+          LEFT JOIN aqbooksellers ON aqbooksellers.id = aqinvoices.booksellerid
+          LEFT JOIN aqorders ON aqorders.invoiceid = aqinvoices.invoiceid
+          LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
+          LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
+          LEFT JOIN subscription ON biblio.biblionumber = subscription.biblionumber
+    };
+
+    my @bind_args;
+    my @bind_strs;
+    if($args{supplierid}) {
+        push @bind_strs, " aqinvoices.booksellerid = ? ";
+        push @bind_args, $args{supplierid};
+    }
+    if($args{invoicenumber}) {
+        push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
+        push @bind_args, "%$args{invoicenumber}%";
+    }
+    if($args{suppliername}) {
+        push @bind_strs, " aqbooksellers.name LIKE ? ";
+        push @bind_args, "%$args{suppliername}%";
+    }
+    if($args{shipmentdatefrom}) {
+        push @bind_strs, " aqinvoices.shipementdate >= ? ";
+        push @bind_args, $args{shipmentdatefrom};
+    }
+    if($args{shipmentdateto}) {
+        push @bind_strs, " aqinvoices.shipementdate <= ? ";
+        push @bind_args, $args{shipmentdateto};
+    }
+    if($args{billingdatefrom}) {
+        push @bind_strs, " aqinvoices.billingdate >= ? ";
+        push @bind_args, $args{billingdatefrom};
+    }
+    if($args{billingdateto}) {
+        push @bind_strs, " aqinvoices.billingdate <= ? ";
+        push @bind_args, $args{billingdateto};
+    }
+    if($args{isbneanissn}) {
+        push @bind_strs, " (biblioitems.isbn LIKE ? OR biblioitems.ean LIKE ? OR biblioitems.issn LIKE ? ) ";
+        push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn};
+    }
+    if($args{title}) {
+        push @bind_strs, " biblio.title LIKE ? ";
+        push @bind_args, $args{title};
+    }
+    if($args{author}) {
+        push @bind_strs, " biblio.author LIKE ? ";
+        push @bind_args, $args{author};
+    }
+    if($args{publisher}) {
+        push @bind_strs, " biblioitems.publishercode LIKE ? ";
+        push @bind_args, $args{publisher};
+    }
+    if($args{publicationyear}) {
+        push @bind_strs, " biblioitems.publicationyear = ? ";
+        push @bind_args, $args{publicationyear};
+    }
+    if($args{branchcode}) {
+        push @bind_strs, " aqorders.branchcode = ? ";
+        push @bind_args, $args{branchcode};
+    }
+
+    $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
+    $query .= " GROUP BY aqinvoices.invoiceid ";
+
+    if($args{order_by}) {
+        my ($column, $direction) = split / /, $args{order_by};
+        if(grep /^$column$/, @columns) {
+            $direction ||= 'ASC';
+            $query .= " ORDER BY $column $direction";
+        }
+    }
+
+    my $sth = $dbh->prepare($query);
+    $sth->execute(@bind_args);
+
+    my $results = $sth->fetchall_arrayref({});
+    return @$results;
+}
+
+=head3 GetInvoice
+
+    my $invoice = GetInvoice($invoiceid);
+
+Get informations about invoice with given $invoiceid
+
+Return a hash filled with aqinvoices.* fields
+
+=cut
+
+sub GetInvoice {
+    my ($invoiceid) = @_;
+    my $invoice;
+
+    return unless $invoiceid;
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        SELECT *
+        FROM aqinvoices
+        WHERE invoiceid = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($invoiceid);
+
+    $invoice = $sth->fetchrow_hashref;
+    return $invoice;
+}
+
+=head3 GetInvoiceDetails
+
+    my $invoice = GetInvoiceDetails($invoiceid)
+
+Return informations about an invoice + the list of related order lines
+
+Orders informations are in $invoice->{orders} (array ref)
+
+=cut
 
+sub GetInvoiceDetails {
+    my ($invoiceid) = @_;
+
+    if ( !defined $invoiceid ) {
+        carp 'GetInvoiceDetails called without an invoiceid';
+        return;
+    }
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        SELECT aqinvoices.*, aqbooksellers.name AS suppliername
+        FROM aqinvoices
+          LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
+        WHERE invoiceid = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($invoiceid);
+
+    my $invoice = $sth->fetchrow_hashref;
+
+    $query = qq{
+        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 = ?
+    };
+    $sth = $dbh->prepare($query);
+    $sth->execute($invoiceid);
+    $invoice->{orders} = $sth->fetchall_arrayref({});
+    $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails
+
+    return $invoice;
+}
+
+=head3 AddInvoice
+
+    my $invoiceid = AddInvoice(
+        invoicenumber => $invoicenumber,
+        booksellerid => $booksellerid,
+        shipmentdate => $shipmentdate,
+        billingdate => $billingdate,
+        closedate => $closedate,
+        shipmentcost => $shipmentcost,
+        shipmentcost_budgetid => $shipmentcost_budgetid
+    );
+
+Create a new invoice and return its id or undef if it fails.
+
+=cut
+
+sub AddInvoice {
+    my %invoice = @_;
+
+    return unless(%invoice and $invoice{invoicenumber});
+
+    my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
+        closedate shipmentcost shipmentcost_budgetid);
+
+    my @set_strs;
+    my @set_args;
+    foreach my $key (keys %invoice) {
+        if(0 < grep(/^$key$/, @columns)) {
+            push @set_strs, "$key = ?";
+            push @set_args, ($invoice{$key} || undef);
+        }
+    }
+
+    my $rv;
+    if(@set_args > 0) {
+        my $dbh = C4::Context->dbh;
+        my $query = "INSERT INTO aqinvoices SET ";
+        $query .= join (",", @set_strs);
+        my $sth = $dbh->prepare($query);
+        $rv = $sth->execute(@set_args);
+        if($rv) {
+            $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
+        }
+    }
+    return $rv;
+}
+
+=head3 ModInvoice
+
+    ModInvoice(
+        invoiceid => $invoiceid,    # Mandatory
+        invoicenumber => $invoicenumber,
+        booksellerid => $booksellerid,
+        shipmentdate => $shipmentdate,
+        billingdate => $billingdate,
+        closedate => $closedate,
+        shipmentcost => $shipmentcost,
+        shipmentcost_budgetid => $shipmentcost_budgetid
+    );
+
+Modify an invoice, invoiceid is mandatory.
+
+Return undef if it fails.
+
+=cut
+
+sub ModInvoice {
+    my %invoice = @_;
+
+    return unless(%invoice and $invoice{invoiceid});
+
+    my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
+        closedate shipmentcost shipmentcost_budgetid);
+
+    my @set_strs;
+    my @set_args;
+    foreach my $key (keys %invoice) {
+        if(0 < grep(/^$key$/, @columns)) {
+            push @set_strs, "$key = ?";
+            push @set_args, ($invoice{$key} || undef);
+        }
+    }
+
+    my $dbh = C4::Context->dbh;
+    my $query = "UPDATE aqinvoices SET ";
+    $query .= join(",", @set_strs);
+    $query .= " WHERE invoiceid = ?";
+
+    my $sth = $dbh->prepare($query);
+    $sth->execute(@set_args, $invoice{invoiceid});
+}
+
+=head3 CloseInvoice
+
+    CloseInvoice($invoiceid);
+
+Close an invoice.
+
+Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
+
+=cut
+
+sub CloseInvoice {
+    my ($invoiceid) = @_;
+
+    return unless $invoiceid;
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        UPDATE aqinvoices
+        SET closedate = CAST(NOW() AS DATE)
+        WHERE invoiceid = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($invoiceid);
+}
+
+=head3 ReopenInvoice
+
+    ReopenInvoice($invoiceid);
+
+Reopen an invoice
+
+Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => C4::Dates->new()->output('iso'))
+
+=cut
+
+sub ReopenInvoice {
+    my ($invoiceid) = @_;
+
+    return unless $invoiceid;
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        UPDATE aqinvoices
+        SET closedate = NULL
+        WHERE invoiceid = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $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;