6a7c9ee68c8fac4afa5340679169be7ea8b7750c
[koha.git] / C4 / Bookfund.pm
1 package C4::Bookfund;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 # use Smart::Comments;
23
24 use vars qw($VERSION @ISA @EXPORT);
25
26 # set the version for version checking
27 $VERSION = 3.00;
28
29 =head1 NAME
30
31 C4::Bookfund - Koha functions for dealing with bookfund, currency & money.
32
33 =head1 SYNOPSIS
34
35 use C4::Bookfund;
36
37 =head1 DESCRIPTION
38
39 the functions in this modules deal with bookfund, currency and money.
40 They allow to get and/or set some informations for a specific budget or currency.
41
42 =cut
43
44 @ISA    = qw(Exporter);
45 @EXPORT = qw(
46     &GetBookFund &GetBookFunds &GetBookFundsId &GetBookFundBreakdown &GetCurrencies
47     &NewBookFund
48     &ModBookFund &ModCurrencies
49     &SearchBookFund
50     &Countbookfund 
51     &ConvertCurrency
52     &DelBookFund
53 );
54
55 =head1 FUNCTIONS
56
57 =cut
58
59 #-------------------------------------------------------------#
60
61 =head2 GetBookFund
62
63 $dataaqbookfund = &GetBookFund($bookfundid);
64
65 this function get the bookfundid, bookfundname, the bookfundgroup,  the branchcode
66 from aqbookfund table for bookfundid given on input arg.
67 return: 
68 C<$dataaqbookfund> is a hashref full of bookfundid, bookfundname, bookfundgroup,
69 and branchcode.
70
71 =cut
72
73 sub GetBookFund {
74     my $bookfundid = shift;
75     my $branchcode = shift;
76     $branchcode=($branchcode?$branchcode:'');
77     my $dbh = C4::Context->dbh;
78     my $query = "
79         SELECT
80             bookfundid,
81             bookfundname,
82             bookfundgroup,
83             branchcode
84         FROM aqbookfund
85         WHERE bookfundid = ?
86         AND branchcode = ?";
87     my $sth=$dbh->prepare($query);
88     $sth->execute($bookfundid,$branchcode);
89     my $data=$sth->fetchrow_hashref;
90     return $data;
91 }
92
93
94 =head3 GetBookFundsId
95
96 $sth = &GetBookFundsId
97 Read on aqbookfund table and execute a simple SQL query.
98
99 return:
100 $sth->execute. Don't forget to fetch row from the database after using
101 this function by using, for example, $sth->fetchrow_hashref;
102
103 C<@results> is an array of id existing on the database.
104
105 =cut
106
107 sub GetBookFundsId {
108     my @bookfundids_loop;
109     my $dbh= C4::Context->dbh;
110     my $query = "
111         SELECT bookfundid,branchcode
112         FROM aqbookfund
113     ";
114     my $sth = $dbh->prepare($query);
115     $sth->execute;
116     return $sth;
117 }
118
119 #-------------------------------------------------------------#
120
121 =head3 GetBookFunds
122
123 @results = &GetBookFunds;
124
125 Returns a list of all book funds.
126
127 C<@results> is an array of references-to-hash, whose keys are fields from the aqbookfund and aqbudget tables of the Koha database. Results are ordered
128 alphabetically by book fund name.
129
130 =cut
131
132 sub GetBookFunds {
133     my ($branch) = @_;
134     my $dbh      = C4::Context->dbh;
135     my $userenv  = C4::Context->userenv;
136     my $strsth;
137
138     if ( $branch ne '' ) {
139         $strsth = "
140         SELECT *
141         FROM   aqbookfund
142         LEFT JOIN aqbudget ON aqbookfund.bookfundid=aqbudget.bookfundid
143         WHERE  startdate<now()
144             AND enddate>now()
145             AND (aqbookfund.branchcode='' OR aqbookfund.branchcode= ? )
146       GROUP BY aqbookfund.bookfundid ORDER BY bookfundname";
147     }
148     else {
149         $strsth = "
150             SELECT *
151             FROM   aqbookfund
152             LEFT JOIN aqbudget ON aqbookfund.bookfundid=aqbudget.bookfundid
153             WHERE startdate<now()
154                 AND enddate>now()
155             GROUP BY aqbookfund.bookfundid ORDER BY bookfundname
156         ";
157     }
158     my $sth = $dbh->prepare($strsth);
159     if ( $branch ne '' ) {
160         $sth->execute($branch);
161     }
162     else {
163         $sth->execute;
164     }
165     my @results = ();
166     while ( my $data = $sth->fetchrow_hashref ) {
167         push( @results, $data );
168     }
169     $sth->finish;
170     return @results;
171 }
172
173 #-------------------------------------------------------------#
174
175 =head3 GetCurrencies
176
177 @currencies = &GetCurrencies;
178
179 Returns the list of all known currencies.
180
181 C<$currencies> is a array; its elements are references-to-hash, whose
182 keys are the fields from the currency table in the Koha database.
183
184 =cut
185
186 sub GetCurrencies {
187     my $dbh = C4::Context->dbh;
188     my $query = "
189         SELECT *
190         FROM   currency
191     ";
192     my $sth = $dbh->prepare($query);
193     $sth->execute;
194     my @results = ();
195     while ( my $data = $sth->fetchrow_hashref ) {
196         push( @results, $data );
197     }
198     $sth->finish;
199     return @results;
200 }
201
202 #-------------------------------------------------------------#
203
204 =head3 GetBookFundBreakdown
205
206 ( $spent, $comtd ) = &GetBookFundBreakdown( $id, $start, $end );
207
208 returns the total comtd & spent for a given bookfund, and a given year
209 used in acqui-home.pl
210
211 =cut
212
213 sub GetBookFundBreakdown {
214     my ( $id, $start, $end ) = @_;
215     my $dbh = C4::Context->dbh;
216
217     # if no start/end dates given defaut to everything
218     if ( !$start ) {
219         $start = '0000-00-00';
220         $end   = 'now()';
221     }
222
223     # do a query for spent totals.
224     my $query = "
225         SELECT quantity,datereceived,freight,unitprice,listprice,ecost,
226                quantityreceived,subscription, closedate
227         FROM   aqorders
228         LEFT JOIN aqbasket USING (basketno)
229         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
230         LEFT JOIN aqbookfund ON (aqorderbreakdown.bookfundid=aqbookfund.bookfundid and aqorderbreakdown.branchcode=aqbookfund.branchcode)
231         LEFT JOIN aqbudget ON (aqbudget.bookfundid=aqbookfund.bookfundid and aqbudget.branchcode=aqbookfund.branchcode)
232         WHERE  aqorderbreakdown.bookfundid=?
233             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
234             AND ((budgetdate >= ? and budgetdate < ?) OR (startdate>=? and enddate<=?))
235             AND (closedate >= ? AND closedate <= ?)
236     ";
237     my $sth = $dbh->prepare($query);
238     $sth->execute( $id, $start, $end, $start, $end, $start, $end );
239
240     my ($spent) = 0;
241     while ( my $data = $sth->fetchrow_hashref ) {
242         if($data->{datereceived}){
243             if ( $data->{'subscription'} == 1 ) {
244                 $spent += $data->{'quantity'} * $data->{'unitprice'};
245             }
246             else {
247                 $spent += ( $data->{'unitprice'} ) * ($data->{'quantityreceived'}?$data->{'quantityreceived'}:0);
248     
249             }
250
251         }
252     }
253
254     # then do a seperate query for commited totals, (pervious single query was
255     # returning incorrect comitted results.
256
257     $query = "
258         SELECT  quantity,datereceived,freight,unitprice,
259                 listprice,ecost,quantityreceived AS qrev,
260                 subscription,title,itemtype,aqorders.biblionumber,
261                 aqorders.booksellerinvoicenumber,
262                 quantity-quantityreceived AS tleft,quantityreceived,
263                 aqorders.ordernumber AS ordnum,entrydate,budgetdate
264         FROM    aqorders
265         LEFT JOIN aqbasket USING (basketno)
266         LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=aqorders.biblioitemnumber
267         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
268         WHERE   bookfundid=?
269             AND (budgetdate >= ? AND budgetdate < ?)
270             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
271             AND (closedate >= ? AND closedate <= ?)
272     ";
273
274     $sth = $dbh->prepare($query);
275 #      warn "$start $end";     
276     $sth->execute( $id, $start, $end , $start, $end);
277
278     my $comtd=0;
279
280     while ( my $data = $sth->fetchrow_hashref ) {
281         if(not $data->{datereceived}){
282             my $left = $data->{'tleft'};
283             if ( !$left || $left eq '' ) {
284                 $left = $data->{'quantity'};
285             }
286             if ( $left && $left > 0 ) {
287                 my $subtotal = $left * $data->{'ecost'};
288                 $data->{subtotal} = $subtotal;
289                 $data->{'left'} = $left;
290                 $comtd += $subtotal;
291             }
292         }
293 #         use Data::Dumper; warn Dumper($data);    
294     }
295
296     $sth->finish;
297     return ( $spent, $comtd );
298 }
299
300 =head3 NewBookFund
301
302 &NewBookFund(bookfundid, bookfundname, branchcode);
303
304 this function create a new bookfund into the database.
305
306 =cut 
307
308 sub NewBookFund{
309     my ($bookfundid, $bookfundname, $branchcode) = @_;
310     $branchcode = undef unless $branchcode;
311     my $dbh = C4::Context->dbh;
312     my $query = "
313         INSERT
314         INTO aqbookfund
315             (bookfundid, bookfundname, branchcode)
316         VALUES
317             (?, ?, ?)
318     ";
319     my $sth=$dbh->prepare($query);
320     $sth->execute($bookfundid,$bookfundname,"$branchcode");
321 }
322
323 #-------------------------------------------------------------#
324
325 =head3 ModBookFund
326
327 &ModBookFund($bookfundname,$bookfundid,$current_branch, $branchcode)
328
329 This function updates the bookfundname and the branchcode in the aqbookfund table.
330
331 =cut
332
333 # FIXME: use placeholders,  ->prepare(), ->execute()
334
335 sub ModBookFund {
336     my ($bookfundname,$bookfundid,$current_branch, $branchcode) = @_;
337
338     my $dbh = C4::Context->dbh;
339
340     my $retval = $dbh->do("
341      UPDATE aqbookfund
342         SET    bookfundname = '$bookfundname', 
343                branchcode = '$branchcode'
344         WHERE  bookfundid = '$bookfundid'
345         AND branchcode = '$current_branch'
346     ");
347
348     ### $retval
349
350     # budgets depending on a bookfund must have the same branchcode
351
352     # if the bookfund branchcode is set, and previous update is successfull, then update aqbudget.branchcode too.
353     if (defined $branchcode && $retval > 0) {
354         my $query = "UPDATE  aqbudget  
355             SET     branchcode = ?
356             WHERE   bookfundid = ? ";
357
358         my $sth=$dbh->prepare($query);
359         $sth->execute($branchcode, $bookfundid) ;
360     }
361 }
362
363 #-------------------------------------------------------------#
364
365 =head3 SearchBookFund
366
367 @results = SearchBookFund(
368         $bookfundid,$filter,$filter_bookfundid,
369         $filter_bookfundname,$filter_branchcode);
370
371 this function searchs among the bookfunds corresponding to our filtering rules.
372
373 =cut
374
375 sub SearchBookFund {
376     my $dbh = C4::Context->dbh;
377     my ($filter,
378         $filter_bookfundid,
379         $filter_bookfundname,
380         $filter_branchcode
381        ) = @_;
382
383     my @bindings;
384
385     my $query = "
386         SELECT  bookfundid,
387                 bookfundname,
388                 bookfundgroup,
389                 branchcode
390         FROM aqbookfund
391         WHERE 1 ";
392
393     if ($filter) {
394         if ($filter_bookfundid) {
395             $query.= "AND bookfundid = ?";
396             push @bindings, $filter_bookfundid;
397         }
398         if ($filter_bookfundname) {
399             $query.= "AND bookfundname like ?";
400             push @bindings, '%'.$filter_bookfundname.'%';
401         }
402         if ($filter_branchcode) {
403             $query.= "AND branchcode = ?";
404             push @bindings, $filter_branchcode;
405         }
406     }
407     $query.= "ORDER BY bookfundid";
408
409     my $sth = $dbh->prepare($query);
410     $sth->execute(@bindings);
411     my @results;
412     while (my $row = $sth->fetchrow_hashref) {
413         push @results, $row;
414     }
415     return @results;
416 }
417
418 #-------------------------------------------------------------#
419
420 =head3 ModCurrencies
421
422 &ModCurrencies($currency, $newrate);
423
424 Sets the exchange rate for C<$currency> to be C<$newrate>.
425
426 =cut
427
428 sub ModCurrencies {
429     my ( $currency, $rate ) = @_;
430     my $dbh = C4::Context->dbh;
431     my $query = "
432         UPDATE currency
433         SET    rate=?
434         WHERE  currency=?
435     ";
436     my $sth = $dbh->prepare($query);
437     $sth->execute( $rate, $currency );
438 }
439
440 #-------------------------------------------------------------#
441
442 =head3 Countbookfund
443
444 $number = Countbookfund($bookfundid);
445
446 this function count the number of bookfund with id given on input arg.
447 return :
448 the result of the SQL query as a number.
449
450 =cut
451
452 sub Countbookfund {
453     my $bookfundid = shift;
454     my $branchcode = shift;
455     my $dbh = C4::Context->dbh;
456     my $query ="
457         SELECT COUNT(*)
458         FROM  aqbookfund
459         WHERE bookfundid = ?
460         AND   branchcode = ?
461     ";
462     my $sth = $dbh->prepare($query);
463     $sth->execute($bookfundid,"$branchcode");
464     return $sth->fetchrow;
465 }
466
467
468 #-------------------------------------------------------------#
469
470 =head3 ConvertCurrency
471
472 $foreignprice = &ConvertCurrency($currency, $localprice);
473
474 Converts the price C<$localprice> to foreign currency C<$currency> by
475 dividing by the exchange rate, and returns the result.
476
477 If no exchange rate is found, C<&ConvertCurrency> assumes the rate is one
478 to one.
479
480 =cut
481
482 sub ConvertCurrency {
483     my ( $currency, $price ) = @_;
484     my $dbh = C4::Context->dbh;
485     my $query = "
486         SELECT rate
487         FROM   currency
488         WHERE  currency=?
489     ";
490     my $sth = $dbh->prepare($query);
491     $sth->execute($currency);
492     my $cur = ( $sth->fetchrow_array() )[0];
493     unless($cur) {
494         $cur = 1;
495     }
496     return ( $price / $cur );
497 }
498
499 #-------------------------------------------------------------#
500
501 =head3 DelBookFund
502
503 &DelBookFund($bookfundid);
504 this function delete a bookfund which has $bokfundid as parameter on aqbookfund table and delete the approriate budget.
505
506 =cut
507
508 sub DelBookFund {
509     my $bookfundid = shift;
510     my $branchcode=shift;
511     my $dbh = C4::Context->dbh;
512     my $query = "
513         DELETE FROM aqbookfund
514         WHERE bookfundid=?
515         AND branchcode=?
516     ";
517     my $sth=$dbh->prepare($query);
518     $sth->execute($bookfundid,$branchcode);
519     $sth->finish;
520     $query = "
521         DELETE FROM aqbudget where bookfundid=? and branchcode=?
522     ";
523     $sth=$dbh->prepare($query);
524     $sth->execute($bookfundid,$branchcode);
525     $sth->finish;
526 }
527
528 END { }    # module clean-up code here (global destructor)
529
530 1;
531
532 __END__
533
534 =head1 AUTHOR
535
536 Koha Developement team <info@koha.org>
537
538 =cut