Adding autotruncation
[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     return @results;
170 }
171
172 #-------------------------------------------------------------#
173
174 =head3 GetCurrencies
175
176 @currencies = &GetCurrencies;
177
178 Returns the list of all known currencies.
179
180 C<$currencies> is a array; its elements are references-to-hash, whose
181 keys are the fields from the currency table in the Koha database.
182
183 =cut
184
185 sub GetCurrencies {
186     my $dbh = C4::Context->dbh;
187     my $results = $dbh->selectall_arrayref(
188         'SELECT * FROM currency', { Slice => {} } );
189     return @{$results};
190 }
191
192 #-------------------------------------------------------------#
193
194 =head3 GetBookFundBreakdown
195
196 ( $spent, $comtd ) = &GetBookFundBreakdown( $id, $start, $end );
197
198 returns the total comtd & spent for a given bookfund, and a given year
199 used in acqui-home.pl
200
201 =cut
202
203 sub GetBookFundBreakdown {
204     my ( $id, $start, $end ) = @_;
205     my $dbh = C4::Context->dbh;
206
207     # if no start/end dates given defaut to everything
208     if ( !$start ) {
209         $start = '0000-00-00';
210         $end   = 'now()';
211     }
212
213     # do a query for spent totals.
214     my $query = "
215         SELECT quantity,datereceived,freight,unitprice,listprice,ecost,
216                quantityreceived,subscription
217         FROM   aqorders
218         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
219         LEFT JOIN aqbookfund ON (aqorderbreakdown.bookfundid=aqbookfund.bookfundid and aqorderbreakdown.branchcode=aqbookfund.branchcode)
220         LEFT JOIN aqbudget ON (aqbudget.bookfundid=aqbookfund.bookfundid and aqbudget.branchcode=aqbookfund.branchcode)
221         WHERE  aqorderbreakdown.bookfundid=?
222             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
223             AND ((budgetdate >= ? and budgetdate < ?) OR (startdate>=? and enddate<=?))
224     ";
225     my $sth = $dbh->prepare($query);
226     $sth->execute( $id, $start, $end, $start, $end );
227
228     my ($spent) = 0;
229     while ( my $data = $sth->fetchrow_hashref ) {
230         if ( $data->{'subscription'} == 1 ) {
231             $spent += $data->{'quantity'} * $data->{'unitprice'};
232         }
233         else {
234             $spent += ( $data->{'unitprice'} ) * ($data->{'quantityreceived'}?$data->{'quantityreceived'}:0);
235
236         }
237     }
238
239     # then do a seperate query for commited totals, (pervious single query was
240     # returning incorrect comitted results.
241
242     $query = "
243         SELECT  quantity,datereceived,freight,unitprice,
244                 listprice,ecost,quantityreceived AS qrev,
245                 subscription,title,itemtype,aqorders.biblionumber,
246                 aqorders.booksellerinvoicenumber,
247                 quantity-quantityreceived AS tleft,
248                 aqorders.ordernumber AS ordnum,entrydate,budgetdate
249         FROM    aqorders
250         LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=aqorders.biblioitemnumber
251         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
252         WHERE   bookfundid=?
253             AND (budgetdate >= ? AND budgetdate < ?)
254             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
255     ";
256
257     $sth = $dbh->prepare($query);
258 #      warn "$start $end";     
259     $sth->execute( $id, $start, $end );
260
261     my $comtd=0;
262
263     while ( my $data = $sth->fetchrow_hashref ) {
264         my $left = $data->{'tleft'};
265         if ( !$left || $left eq '' ) {
266             $left = $data->{'quantity'};
267         }
268         if ( $left && $left > 0 ) {
269             my $subtotal = $left * $data->{'ecost'};
270             $data->{subtotal} = $subtotal;
271             $data->{'left'} = $left;
272             $comtd += $subtotal;
273         }
274 #         use Data::Dumper; warn Dumper($data);    
275     }
276
277     return ( $spent, $comtd );
278 }
279
280 =head3 NewBookFund
281
282 &NewBookFund(bookfundid, bookfundname, branchcode);
283
284 this function create a new bookfund into the database.
285
286 =cut 
287
288 sub NewBookFund{
289     my ($bookfundid, $bookfundname, $branchcode) = @_;
290     $branchcode = undef unless $branchcode;
291     my $dbh = C4::Context->dbh;
292     my $query = "
293         INSERT
294         INTO aqbookfund
295             (bookfundid, bookfundname, branchcode)
296         VALUES
297             (?, ?, ?)
298     ";
299     my $sth=$dbh->prepare($query);
300     $sth->execute($bookfundid,$bookfundname,"$branchcode");
301 }
302
303 #-------------------------------------------------------------#
304
305 =head3 ModBookFund
306
307 &ModBookFund($bookfundname,$bookfundid,$current_branch, $branchcode)
308
309 This function updates the bookfundname and the branchcode in the aqbookfund table.
310
311 =cut
312
313 # FIXME: use placeholders,  ->prepare(), ->execute()
314
315 sub ModBookFund {
316     my ($bookfundname,$bookfundid,$current_branch, $branchcode) = @_;
317
318     my $dbh = C4::Context->dbh;
319
320     my $retval = $dbh->do("
321      UPDATE aqbookfund
322         SET    bookfundname = '$bookfundname', 
323                branchcode = '$branchcode'
324         WHERE  bookfundid = '$bookfundid'
325         AND branchcode = '$current_branch'
326     ");
327
328     ### $retval
329
330     # budgets depending on a bookfund must have the same branchcode
331
332     # if the bookfund branchcode is set, and previous update is successfull, then update aqbudget.branchcode too.
333     if (defined $branchcode && $retval > 0) {
334         my $query = "UPDATE  aqbudget  
335             SET     branchcode = ?
336             WHERE   bookfundid = ? ";
337
338         my $sth=$dbh->prepare($query);
339         $sth->execute($branchcode, $bookfundid) ;
340     }
341 }
342
343 #-------------------------------------------------------------#
344
345 =head3 SearchBookFund
346
347 @results = SearchBookFund(
348         $bookfundid,$filter,$filter_bookfundid,
349         $filter_bookfundname,$filter_branchcode);
350
351 this function searchs among the bookfunds corresponding to our filtering rules.
352
353 =cut
354
355 sub SearchBookFund {
356     my $dbh = C4::Context->dbh;
357     my ($filter,
358         $filter_bookfundid,
359         $filter_bookfundname,
360         $filter_branchcode
361        ) = @_;
362
363     my @bindings;
364
365     my $query = "
366         SELECT  bookfundid,
367                 bookfundname,
368                 bookfundgroup,
369                 branchcode
370         FROM aqbookfund
371         WHERE 1 ";
372
373     if ($filter) {
374         if ($filter_bookfundid) {
375             $query.= "AND bookfundid = ?";
376             push @bindings, $filter_bookfundid;
377         }
378         if ($filter_bookfundname) {
379             $query.= "AND bookfundname like ?";
380             push @bindings, '%'.$filter_bookfundname.'%';
381         }
382         if ($filter_branchcode) {
383             $query.= "AND branchcode = ?";
384             push @bindings, $filter_branchcode;
385         }
386     }
387     $query.= "ORDER BY bookfundid";
388
389     my $sth = $dbh->prepare($query);
390     $sth->execute(@bindings);
391     my @results;
392     while (my $row = $sth->fetchrow_hashref) {
393         push @results, $row;
394     }
395     return @results;
396 }
397
398 #-------------------------------------------------------------#
399
400 =head3 ModCurrencies
401
402 &ModCurrencies($currency, $newrate);
403
404 Sets the exchange rate for C<$currency> to be C<$newrate>.
405
406 =cut
407
408 sub ModCurrencies {
409     my ( $currency, $rate ) = @_;
410     my $dbh = C4::Context->dbh;
411     $dbh->do('UPDATE currency SET rate=? WHERE currency=?', {}, $rate, $currency );
412     return;
413 }
414
415 #-------------------------------------------------------------#
416
417 =head3 Countbookfund
418
419 $number = Countbookfund($bookfundid);
420
421 this function count the number of bookfund with id given on input arg.
422 return :
423 the result of the SQL query as a number.
424
425 =cut
426
427 sub Countbookfund {
428     my $bookfundid = shift;
429     my $branchcode = shift;
430     my $dbh = C4::Context->dbh;
431     my $query ="
432         SELECT COUNT(*)
433         FROM  aqbookfund
434         WHERE bookfundid = ?
435         AND   branchcode = ?
436     ";
437     my $sth = $dbh->prepare($query);
438     $sth->execute($bookfundid,"$branchcode");
439     return $sth->fetchrow;
440 }
441
442
443 #-------------------------------------------------------------#
444
445 =head3 ConvertCurrency
446
447 $foreignprice = &ConvertCurrency($currency, $localprice);
448
449 Converts the price C<$localprice> to foreign currency C<$currency> by
450 dividing by the exchange rate, and returns the result.
451
452 If no exchange rate is found, C<&ConvertCurrency> assumes the rate is one
453 to one.
454
455 =cut
456
457 sub ConvertCurrency {
458     my ( $currency, $price ) = @_;
459     my $dbh = C4::Context->dbh;
460     my $query = "
461         SELECT rate
462         FROM   currency
463         WHERE  currency=?
464     ";
465     my $sth = $dbh->prepare($query);
466     $sth->execute($currency);
467     my $cur = ( $sth->fetchrow_array() )[0];
468     unless($cur) {
469         $cur = 1;
470     }
471     return ( $price / $cur );
472 }
473
474 #-------------------------------------------------------------#
475
476 =head3 DelBookFund
477
478 &DelBookFund($bookfundid);
479 this function delete a bookfund which has $bokfundid as parameter on aqbookfund table and delete the approriate budget.
480
481 =cut
482
483 sub DelBookFund {
484     my $bookfundid = shift;
485     my $branchcode=shift;
486     my $dbh = C4::Context->dbh;
487     $dbh->do('DELETE FROM aqbookfund WHERE bookfundid=?  AND branchcode=?', {}, $bookfundid,$branchcode);
488     $dbh->do('DELETE FROM aqbudget where bookfundid=? and branchcode=?', {}, $bookfundid,$branchcode);
489     return;
490 }
491
492 END { }    # module clean-up code here (global destructor)
493
494 1;
495
496 __END__
497
498 =head1 AUTHOR
499
500 Koha Developement team <info@koha.org>
501
502 =cut