(bug #3348) still fixing funds and budget table
[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 distinct quantity,datereceived,freight,unitprice,listprice,ecost,quantityreceived
226     as qrev,subscription,title,itype as itemtype,aqorders.biblionumber,aqorders.booksellerinvoicenumber,
227     quantity-quantityreceived as tleft,
228     aqorders.ordernumber
229     as ordnum,entrydate,budgetdate,aqbasket.booksellerid,aqbasket.basketno
230     from aqorders
231     inner join aqorderbreakdown on aqorderbreakdown.ordernumber = aqorders.ordernumber
232     inner join aqbasket on aqbasket.basketno = aqorders.basketno
233     left join items on  items.biblionumber=aqorders.biblionumber
234     where bookfundid=? 
235    and (datereceived >= ? and datereceived < ?)
236     and (datecancellationprinted is NULL or
237            datecancellationprinted='0000-00-00')
238     and (closedate >= ? and closedate < ?)
239     ";
240     my $sth = $dbh->prepare($query);
241     $sth->execute( $id, $start, $end, $start, $end);
242
243     my ($spent) = 0;
244     while ( my $data = $sth->fetchrow_hashref ) {
245         if($data->{datereceived}){
246             if ( $data->{'subscription'} == 1 ) {
247                 $spent += $data->{'quantity'} * $data->{'unitprice'};
248             }
249             else {
250                 $spent += ( $data->{'unitprice'} ) * ($data->{'qrev'}?$data->{'qrev'}:0);
251             }
252
253         }
254     }
255
256     # then do a seperate query for commited totals, (pervious single query was
257     # returning incorrect comitted results.
258
259     $query = "
260         SELECT  quantity,datereceived,freight,unitprice,
261                 listprice,ecost,quantityreceived AS qrev,
262                 subscription,title,itemtype,aqorders.biblionumber,
263                 aqorders.booksellerinvoicenumber,
264                 quantity-quantityreceived AS tleft,quantityreceived,
265                 aqorders.ordernumber AS ordnum,entrydate,budgetdate
266         FROM    aqorders
267         LEFT JOIN aqbasket USING (basketno)
268         LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=aqorders.biblioitemnumber
269         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
270         WHERE   bookfundid=?
271             AND (budgetdate >= ? AND budgetdate < ?)
272             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
273             AND (closedate >= ? AND closedate <= ?)
274     ";
275
276     $sth = $dbh->prepare($query);
277 #      warn "$start $end";     
278     $sth->execute( $id, $start, $end , $start, $end);
279
280     my $comtd=0;
281
282     while ( my $data = $sth->fetchrow_hashref ) {
283         if(not $data->{datereceived}){
284             my $left = $data->{'tleft'};
285             if ( !$left || $left eq '' ) {
286                 $left = $data->{'quantity'};
287             }
288             if ( $left && $left > 0 ) {
289                 my $subtotal = $left * $data->{'ecost'};
290                 $data->{subtotal} = $subtotal;
291                 $data->{'left'} = $left;
292                 $comtd += $subtotal;
293             }
294         }
295 #         use Data::Dumper; warn Dumper($data);    
296     }
297
298     $sth->finish;
299     return ( $spent, $comtd );
300 }
301
302 =head3 NewBookFund
303
304 &NewBookFund(bookfundid, bookfundname, branchcode);
305
306 this function create a new bookfund into the database.
307
308 =cut 
309
310 sub NewBookFund{
311     my ($bookfundid, $bookfundname, $branchcode) = @_;
312     $branchcode = undef unless $branchcode;
313     my $dbh = C4::Context->dbh;
314     my $query = "
315         INSERT
316         INTO aqbookfund
317             (bookfundid, bookfundname, branchcode)
318         VALUES
319             (?, ?, ?)
320     ";
321     my $sth=$dbh->prepare($query);
322     $sth->execute($bookfundid,$bookfundname,"$branchcode");
323 }
324
325 #-------------------------------------------------------------#
326
327 =head3 ModBookFund
328
329 &ModBookFund($bookfundname,$bookfundid,$current_branch, $branchcode)
330
331 This function updates the bookfundname and the branchcode in the aqbookfund table.
332
333 =cut
334
335 # FIXME: use placeholders,  ->prepare(), ->execute()
336
337 sub ModBookFund {
338     my ($bookfundname,$bookfundid,$current_branch, $branchcode) = @_;
339
340     my $dbh = C4::Context->dbh;
341
342     my $retval = $dbh->do("
343      UPDATE aqbookfund
344         SET    bookfundname = '$bookfundname', 
345                branchcode = '$branchcode'
346         WHERE  bookfundid = '$bookfundid'
347         AND branchcode = '$current_branch'
348     ");
349
350     ### $retval
351
352     # budgets depending on a bookfund must have the same branchcode
353
354     # if the bookfund branchcode is set, and previous update is successfull, then update aqbudget.branchcode too.
355     if (defined $branchcode && $retval > 0) {
356         my $query = "UPDATE  aqbudget  
357             SET     branchcode = ?
358             WHERE   bookfundid = ? ";
359
360         my $sth=$dbh->prepare($query);
361         $sth->execute($branchcode, $bookfundid) ;
362     }
363 }
364
365 #-------------------------------------------------------------#
366
367 =head3 SearchBookFund
368
369 @results = SearchBookFund(
370         $bookfundid,$filter,$filter_bookfundid,
371         $filter_bookfundname,$filter_branchcode);
372
373 this function searchs among the bookfunds corresponding to our filtering rules.
374
375 =cut
376
377 sub SearchBookFund {
378     my $dbh = C4::Context->dbh;
379     my ($filter,
380         $filter_bookfundid,
381         $filter_bookfundname,
382         $filter_branchcode
383        ) = @_;
384
385     my @bindings;
386
387     my $query = "
388         SELECT  bookfundid,
389                 bookfundname,
390                 bookfundgroup,
391                 branchcode
392         FROM aqbookfund
393         WHERE 1 ";
394
395     if ($filter) {
396         if ($filter_bookfundid) {
397             $query.= "AND bookfundid = ?";
398             push @bindings, $filter_bookfundid;
399         }
400         if ($filter_bookfundname) {
401             $query.= "AND bookfundname like ?";
402             push @bindings, '%'.$filter_bookfundname.'%';
403         }
404         if ($filter_branchcode) {
405             $query.= "AND branchcode = ?";
406             push @bindings, $filter_branchcode;
407         }
408     }
409     $query.= "ORDER BY bookfundid";
410
411     my $sth = $dbh->prepare($query);
412     $sth->execute(@bindings);
413     my @results;
414     while (my $row = $sth->fetchrow_hashref) {
415         push @results, $row;
416     }
417     return @results;
418 }
419
420 #-------------------------------------------------------------#
421
422 =head3 ModCurrencies
423
424 &ModCurrencies($currency, $newrate);
425
426 Sets the exchange rate for C<$currency> to be C<$newrate>.
427
428 =cut
429
430 sub ModCurrencies {
431     my ( $currency, $rate ) = @_;
432     my $dbh = C4::Context->dbh;
433     my $query = "
434         UPDATE currency
435         SET    rate=?
436         WHERE  currency=?
437     ";
438     my $sth = $dbh->prepare($query);
439     $sth->execute( $rate, $currency );
440 }
441
442 #-------------------------------------------------------------#
443
444 =head3 Countbookfund
445
446 $number = Countbookfund($bookfundid);
447
448 this function count the number of bookfund with id given on input arg.
449 return :
450 the result of the SQL query as a number.
451
452 =cut
453
454 sub Countbookfund {
455     my $bookfundid = shift;
456     my $branchcode = shift;
457     my $dbh = C4::Context->dbh;
458     my $query ="
459         SELECT COUNT(*)
460         FROM  aqbookfund
461         WHERE bookfundid = ?
462         AND   branchcode = ?
463     ";
464     my $sth = $dbh->prepare($query);
465     $sth->execute($bookfundid,"$branchcode");
466     return $sth->fetchrow;
467 }
468
469
470 #-------------------------------------------------------------#
471
472 =head3 ConvertCurrency
473
474 $foreignprice = &ConvertCurrency($currency, $localprice);
475
476 Converts the price C<$localprice> to foreign currency C<$currency> by
477 dividing by the exchange rate, and returns the result.
478
479 If no exchange rate is found, C<&ConvertCurrency> assumes the rate is one
480 to one.
481
482 =cut
483
484 sub ConvertCurrency {
485     my ( $currency, $price ) = @_;
486     my $dbh = C4::Context->dbh;
487     my $query = "
488         SELECT rate
489         FROM   currency
490         WHERE  currency=?
491     ";
492     my $sth = $dbh->prepare($query);
493     $sth->execute($currency);
494     my $cur = ( $sth->fetchrow_array() )[0];
495     unless($cur) {
496         $cur = 1;
497     }
498     return ( $price / $cur );
499 }
500
501 #-------------------------------------------------------------#
502
503 =head3 DelBookFund
504
505 &DelBookFund($bookfundid);
506 this function delete a bookfund which has $bokfundid as parameter on aqbookfund table and delete the approriate budget.
507
508 =cut
509
510 sub DelBookFund {
511     my $bookfundid = shift;
512     my $branchcode=shift;
513     my $dbh = C4::Context->dbh;
514     my $query = "
515         DELETE FROM aqbookfund
516         WHERE bookfundid=?
517         AND branchcode=?
518     ";
519     my $sth=$dbh->prepare($query);
520     $sth->execute($bookfundid,$branchcode);
521     $sth->finish;
522     $query = "
523         DELETE FROM aqbudget where bookfundid=? and branchcode=?
524     ";
525     $sth=$dbh->prepare($query);
526     $sth->execute($bookfundid,$branchcode);
527     $sth->finish;
528 }
529
530 END { }    # module clean-up code here (global destructor)
531
532 1;
533
534 __END__
535
536 =head1 AUTHOR
537
538 Koha Developement team <info@koha.org>
539
540 =cut