Bug 16011: $VERSION - Remove the $VERSION init
[koha.git] / C4 / Overdues.pm
1 package C4::Overdues;
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # copyright 2010 BibLibre
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use Date::Calc qw/Today Date_to_Days/;
25 use Date::Manip qw/UnixDate/;
26 use List::MoreUtils qw( uniq );
27 use POSIX qw( floor ceil );
28 use Locale::Currency::Format 1.28;
29 use Carp;
30
31 use C4::Circulation;
32 use C4::Context;
33 use C4::Accounts;
34 use C4::Log; # logaction
35 use C4::Debug;
36 use Koha::DateUtils;
37 use Koha::Account::Line;
38 use Koha::Account::Lines;
39
40 use vars qw(@ISA @EXPORT);
41
42 BEGIN {
43     # set the version for version checking
44     require Exporter;
45     @ISA = qw(Exporter);
46
47     # subs to rename (and maybe merge some...)
48     push @EXPORT, qw(
49       &CalcFine
50       &Getoverdues
51       &checkoverdues
52       &NumberNotifyId
53       &AmountNotify
54       &UpdateFine
55       &GetFine
56       &get_chargeable_units
57       &CheckItemNotify
58       &GetOverduesForBranch
59       &RemoveNotifyLine
60       &AddNotifyLine
61       &GetOverdueMessageTransportTypes
62       &parse_overdues_letter
63     );
64
65     # subs to remove
66     push @EXPORT, qw(
67       &BorType
68     );
69
70     # check that an equivalent don't exist already before moving
71
72     # subs to move to Circulation.pm
73     push @EXPORT, qw(
74       &GetIssuesIteminfo
75     );
76
77     # &GetIssuingRules - delete.
78     # use C4::Circulation::GetIssuingRule instead.
79
80     # subs to move to Biblio.pm
81     push @EXPORT, qw(
82       &GetItems
83     );
84 }
85
86 =head1 NAME
87
88 C4::Circulation::Fines - Koha module dealing with fines
89
90 =head1 SYNOPSIS
91
92   use C4::Overdues;
93
94 =head1 DESCRIPTION
95
96 This module contains several functions for dealing with fines for
97 overdue items. It is primarily used by the 'misc/fines2.pl' script.
98
99 =head1 FUNCTIONS
100
101 =head2 Getoverdues
102
103   $overdues = Getoverdues( { minimumdays => 1, maximumdays => 30 } );
104
105 Returns the list of all overdue books, with their itemtype.
106
107 C<$overdues> is a reference-to-array. Each element is a
108 reference-to-hash whose keys are the fields of the issues table in the
109 Koha database.
110
111 =cut
112
113 #'
114 sub Getoverdues {
115     my $params = shift;
116     my $dbh = C4::Context->dbh;
117     my $statement;
118     if ( C4::Context->preference('item-level_itypes') ) {
119         $statement = "
120    SELECT issues.*, items.itype as itemtype, items.homebranch, items.barcode, items.itemlost, items.replacementprice
121      FROM issues 
122 LEFT JOIN items       USING (itemnumber)
123     WHERE date_due < NOW()
124 ";
125     } else {
126         $statement = "
127    SELECT issues.*, biblioitems.itemtype, items.itype, items.homebranch, items.barcode, items.itemlost, replacementprice
128      FROM issues 
129 LEFT JOIN items       USING (itemnumber)
130 LEFT JOIN biblioitems USING (biblioitemnumber)
131     WHERE date_due < NOW()
132 ";
133     }
134
135     my @bind_parameters;
136     if ( exists $params->{'minimumdays'} and exists $params->{'maximumdays'} ) {
137         $statement .= ' AND TO_DAYS( NOW() )-TO_DAYS( date_due ) BETWEEN ? and ? ';
138         push @bind_parameters, $params->{'minimumdays'}, $params->{'maximumdays'};
139     } elsif ( exists $params->{'minimumdays'} ) {
140         $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) > ? ';
141         push @bind_parameters, $params->{'minimumdays'};
142     } elsif ( exists $params->{'maximumdays'} ) {
143         $statement .= ' AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ? ';
144         push @bind_parameters, $params->{'maximumdays'};
145     }
146     $statement .= 'ORDER BY borrowernumber';
147     my $sth = $dbh->prepare( $statement );
148     $sth->execute( @bind_parameters );
149     return $sth->fetchall_arrayref({});
150 }
151
152
153 =head2 checkoverdues
154
155     ($count, $overdueitems) = checkoverdues($borrowernumber);
156
157 Returns a count and a list of overdueitems for a given borrowernumber
158
159 =cut
160
161 sub checkoverdues {
162     my $borrowernumber = shift or return;
163     # don't select biblioitems.marc or biblioitems.marcxml... too slow on large systems
164     my $sth = C4::Context->dbh->prepare(
165         "SELECT biblio.*, items.*, issues.*,
166                 biblioitems.volume,
167                 biblioitems.number,
168                 biblioitems.itemtype,
169                 biblioitems.isbn,
170                 biblioitems.issn,
171                 biblioitems.publicationyear,
172                 biblioitems.publishercode,
173                 biblioitems.volumedate,
174                 biblioitems.volumedesc,
175                 biblioitems.collectiontitle,
176                 biblioitems.collectionissn,
177                 biblioitems.collectionvolume,
178                 biblioitems.editionstatement,
179                 biblioitems.editionresponsibility,
180                 biblioitems.illus,
181                 biblioitems.pages,
182                 biblioitems.notes,
183                 biblioitems.size,
184                 biblioitems.place,
185                 biblioitems.lccn,
186                 biblioitems.url,
187                 biblioitems.cn_source,
188                 biblioitems.cn_class,
189                 biblioitems.cn_item,
190                 biblioitems.cn_suffix,
191                 biblioitems.cn_sort,
192                 biblioitems.totalissues
193          FROM issues
194          LEFT JOIN items       ON issues.itemnumber      = items.itemnumber
195          LEFT JOIN biblio      ON items.biblionumber     = biblio.biblionumber
196          LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
197             WHERE issues.borrowernumber  = ?
198             AND   issues.date_due < NOW()"
199     );
200     # FIXME: SELECT * across 4 tables?  do we really need the marc AND marcxml blobs??
201     $sth->execute($borrowernumber);
202     my $results = $sth->fetchall_arrayref({});
203     return ( scalar(@$results), $results);  # returning the count and the results is silly
204 }
205
206 =head2 CalcFine
207
208     ($amount, $chargename,  $units_minus_grace, $chargeable_units) = &CalcFine($item,
209                                   $categorycode, $branch,
210                                   $start_dt, $end_dt );
211
212 Calculates the fine for a book.
213
214 The issuingrules table in the Koha database is a fine matrix, listing
215 the penalties for each type of patron for each type of item and each branch (e.g., the
216 standard fine for books might be $0.50, but $1.50 for DVDs, or staff
217 members might get a longer grace period between the first and second
218 reminders that a book is overdue).
219
220
221 C<$item> is an item object (hashref).
222
223 C<$categorycode> is the category code (string) of the patron who currently has
224 the book.
225
226 C<$branchcode> is the library (string) whose issuingrules govern this transaction.
227
228 C<$start_date> & C<$end_date> are DateTime objects
229 defining the date range over which to determine the fine.
230
231 Fines scripts should just supply the date range over which to calculate the fine.
232
233 C<&CalcFine> returns four values:
234
235 C<$amount> is the fine owed by the patron (see above).
236
237 C<$chargename> is the chargename field from the applicable record in
238 the categoryitem table, whatever that is.
239
240 C<$units_minus_grace> is the number of chargeable units minus the grace period
241
242 C<$chargeable_units> is the number of chargeable units (days between start and end dates, Calendar adjusted where needed,
243 minus any applicable grace period, or hours)
244
245 FIXME: previously attempted to return C<$message> as a text message, either "First Notice", "Second Notice",
246 or "Final Notice".  But CalcFine never defined any value.
247
248 =cut
249
250 sub CalcFine {
251     my ( $item, $bortype, $branchcode, $due_dt, $end_date  ) = @_;
252     my $start_date = $due_dt->clone();
253     # get issuingrules (fines part will be used)
254     my $itemtype = $item->{itemtype} || $item->{itype};
255     my $data = C4::Circulation::GetIssuingRule($bortype, $itemtype, $branchcode);
256     my $fine_unit = $data->{lengthunit};
257     $fine_unit ||= 'days';
258
259     my $chargeable_units = get_chargeable_units($fine_unit, $start_date, $end_date, $branchcode);
260     my $units_minus_grace = $chargeable_units - $data->{firstremind};
261     my $amount = 0;
262     if ( $data->{'chargeperiod'} && ( $units_minus_grace > 0 ) ) {
263         my $units = C4::Context->preference('FinesIncludeGracePeriod') ? $chargeable_units : $units_minus_grace;
264         my $charge_periods = $units / $data->{'chargeperiod'};
265         # If chargeperiod_charge_at = 1, we charge a fine at the start of each charge period
266         # if chargeperiod_charge_at = 0, we charge at the end of each charge period
267         $charge_periods = $data->{'chargeperiod_charge_at'} == 1 ? ceil($charge_periods) : floor($charge_periods);
268         $amount = $charge_periods * $data->{'fine'};
269     } # else { # a zero (or null) chargeperiod or negative units_minus_grace value means no charge. }
270
271     $amount = $data->{overduefinescap} if $data->{overduefinescap} && $amount > $data->{overduefinescap};
272     $amount = $item->{replacementprice} if ( $data->{cap_fine_to_replacement_price} && $item->{replacementprice} && $amount > $item->{replacementprice} );
273     $debug and warn sprintf("CalcFine returning (%s, %s, %s, %s)", $amount, $data->{'chargename'}, $units_minus_grace, $chargeable_units);
274     return ($amount, $data->{'chargename'}, $units_minus_grace, $chargeable_units);
275     # FIXME: chargename is NEVER populated anywhere.
276 }
277
278
279 =head2 get_chargeable_units
280
281     get_chargeable_units($unit, $start_date_ $end_date, $branchcode);
282
283 return integer value of units between C<$start_date> and C<$end_date>, factoring in holidays for C<$branchcode>.
284
285 C<$unit> is 'days' or 'hours' (default is 'days').
286
287 C<$start_date> and C<$end_date> are the two DateTimes to get the number of units between.
288
289 C<$branchcode> is the branch whose calendar to use for finding holidays.
290
291 =cut
292
293 sub get_chargeable_units {
294     my ($unit, $date_due, $date_returned, $branchcode) = @_;
295
296     # If the due date is later than the return date
297     return 0 unless ( $date_returned > $date_due );
298
299     my $charge_units = 0;
300     my $charge_duration;
301     if ($unit eq 'hours') {
302         if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
303             my $calendar = Koha::Calendar->new( branchcode => $branchcode );
304             $charge_duration = $calendar->hours_between( $date_due, $date_returned );
305         } else {
306             $charge_duration = $date_returned->delta_ms( $date_due );
307         }
308         if($charge_duration->in_units('hours') == 0 && $charge_duration->in_units('seconds') > 0){
309             return 1;
310         }
311         return $charge_duration->in_units('hours');
312     }
313     else { # days
314         if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') {
315             my $calendar = Koha::Calendar->new( branchcode => $branchcode );
316             $charge_duration = $calendar->days_between( $date_due, $date_returned );
317         } else {
318             $charge_duration = $date_returned->delta_days( $date_due );
319         }
320         return $charge_duration->in_units('days');
321     }
322 }
323
324
325 =head2 GetSpecialHolidays
326
327     &GetSpecialHolidays($date_dues,$itemnumber);
328
329 return number of special days  between date of the day and date due
330
331 C<$date_dues> is the envisaged date of book return.
332
333 C<$itemnumber> is the book's item number.
334
335 =cut
336
337 sub GetSpecialHolidays {
338     my ( $date_dues, $itemnumber ) = @_;
339
340     # calcul the today date
341     my $today = join "-", &Today();
342
343     # return the holdingbranch
344     my $iteminfo = GetIssuesIteminfo($itemnumber);
345
346     # use sql request to find all date between date_due and today
347     my $dbh = C4::Context->dbh;
348     my $query =
349       qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date
350 FROM `special_holidays`
351 WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ?
352 AND   DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ?
353 AND branchcode=?
354 |;
355     my @result = GetWdayFromItemnumber($itemnumber);
356     my @result_date;
357     my $wday;
358     my $dateinsec;
359     my $sth = $dbh->prepare($query);
360     $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} )
361       ;    # FIXME: just use NOW() in SQL instead of passing in $today
362
363     while ( my $special_date = $sth->fetchrow_hashref ) {
364         push( @result_date, $special_date );
365     }
366
367     my $specialdaycount = scalar(@result_date);
368
369     for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) {
370         $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" );
371         ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) =
372           localtime($dateinsec);
373         for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) {
374             if ( $wday == ( $result[$j]->{'weekday'} ) ) {
375                 $specialdaycount--;
376             }
377         }
378     }
379
380     return $specialdaycount;
381 }
382
383 =head2 GetRepeatableHolidays
384
385     &GetRepeatableHolidays($date_dues, $itemnumber, $difference,);
386
387 return number of day closed between date of the day and date due
388
389 C<$date_dues> is the envisaged date of book return.
390
391 C<$itemnumber> is item number.
392
393 C<$difference> numbers of between day date of the day and date due
394
395 =cut
396
397 sub GetRepeatableHolidays {
398     my ( $date_dues, $itemnumber, $difference ) = @_;
399     my $dateinsec = UnixDate( $date_dues, "%o" );
400     my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
401       localtime($dateinsec);
402     my @result = GetWdayFromItemnumber($itemnumber);
403     my @dayclosedcount;
404     my $j;
405
406     for ( my $i = 0 ; $i < scalar(@result) ; $i++ ) {
407         my $k = $wday;
408
409         for ( $j = 0 ; $j < $difference ; $j++ ) {
410             if ( $result[$i]->{'weekday'} == $k ) {
411                 push( @dayclosedcount, $k );
412             }
413             $k++;
414             ( $k = 0 ) if ( $k eq 7 );
415         }
416     }
417     return scalar(@dayclosedcount);
418 }
419
420
421 =head2 GetWayFromItemnumber
422
423     &Getwdayfromitemnumber($itemnumber);
424
425 return the different week day from repeatable_holidays table
426
427 C<$itemnumber> is  item number.
428
429 =cut
430
431 sub GetWdayFromItemnumber {
432     my ($itemnumber) = @_;
433     my $iteminfo = GetIssuesIteminfo($itemnumber);
434     my @result;
435     my $query = qq|SELECT weekday
436     FROM repeatable_holidays
437     WHERE branchcode=?
438 |;
439     my $sth = C4::Context->dbh->prepare($query);
440
441     $sth->execute( $iteminfo->{'branchcode'} );
442     while ( my $weekday = $sth->fetchrow_hashref ) {
443         push( @result, $weekday );
444     }
445     return @result;
446 }
447
448
449 =head2 GetIssuesIteminfo
450
451     &GetIssuesIteminfo($itemnumber);
452
453 return all data from issues about item
454
455 C<$itemnumber> is  item number.
456
457 =cut
458
459 sub GetIssuesIteminfo {
460     my ($itemnumber) = @_;
461     my $dbh          = C4::Context->dbh;
462     my $query        = qq|SELECT *
463     FROM issues
464     WHERE itemnumber=?
465     |;
466     my $sth = $dbh->prepare($query);
467     $sth->execute($itemnumber);
468     my ($issuesinfo) = $sth->fetchrow_hashref;
469     return $issuesinfo;
470 }
471
472
473 =head2 UpdateFine
474
475     &UpdateFine({ issue_id => $issue_id, itemnumber => $itemnumber, borrwernumber => $borrowernumber, amount => $amount, type => $type, $due => $date_due });
476
477 (Note: the following is mostly conjecture and guesswork.)
478
479 Updates the fine owed on an overdue book.
480
481 C<$itemnumber> is the book's item number.
482
483 C<$borrowernumber> is the borrower number of the patron who currently
484 has the book on loan.
485
486 C<$amount> is the current amount owed by the patron.
487
488 C<$type> will be used in the description of the fine.
489
490 C<$due> is the due date formatted to the currently specified date format
491
492 C<&UpdateFine> looks up the amount currently owed on the given item
493 and sets it to C<$amount>, creating, if necessary, a new entry in the
494 accountlines table of the Koha database.
495
496 =cut
497
498 #
499 # Question: Why should the caller have to
500 # specify both the item number and the borrower number? A book can't
501 # be on loan to two different people, so the item number should be
502 # sufficient.
503 #
504 # Possible Answer: You might update a fine for a damaged item, *after* it is returned.
505 #
506 sub UpdateFine {
507     my ($params) = @_;
508
509     my $issue_id       = $params->{issue_id};
510     my $itemnum        = $params->{itemnumber};
511     my $borrowernumber = $params->{borrowernumber};
512     my $amount         = $params->{amount};
513     my $type           = $params->{type};
514     my $due            = $params->{due};
515
516     $debug and warn "UpdateFine({ itemnumber => $itemnum, borrowernumber => $borrowernumber, type => $type, due => $due, issue_id => $issue_id})";
517
518     unless ( $issue_id ) {
519         carp("No issue_id passed in!");
520         return;
521     }
522
523     my $dbh = C4::Context->dbh;
524     # FIXME - What exactly is this query supposed to do? It looks up an
525     # entry in accountlines that matches the given item and borrower
526     # numbers, where the description contains $due, and where the
527     # account type has one of several values, but what does this _mean_?
528     # Does it look up existing fines for this item?
529     # FIXME - What are these various account types? ("FU", "O", "F", "M")
530     #   "L"   is LOST item
531     #   "A"   is Account Management Fee
532     #   "N"   is New Card
533     #   "M"   is Sundry
534     #   "O"   is Overdue ??
535     #   "F"   is Fine ??
536     #   "FU"  is Fine UPDATE??
537     #   "Pay" is Payment
538     #   "REF" is Cash Refund
539     my $sth = $dbh->prepare(
540         "SELECT * FROM accountlines
541         WHERE borrowernumber=?
542         AND   accounttype IN ('FU','O','F','M')"
543     );
544     $sth->execute( $borrowernumber );
545     my $data;
546     my $total_amount_other = 0.00;
547     my $due_qr = qr/$due/;
548     # Cycle through the fines and
549     # - find line that relates to the requested $itemnum
550     # - accumulate fines for other items
551     # so we can update $itemnum fine taking in account fine caps
552     while (my $rec = $sth->fetchrow_hashref) {
553         if ( $rec->{issue_id} == $issue_id ) {
554             if ($data) {
555                 warn "Not a unique accountlines record for issue_id $issue_id";
556             }
557             else {
558                 $data = $rec;
559                 next;
560             }
561         }
562         $total_amount_other += $rec->{'amountoutstanding'};
563     }
564
565     if (my $maxfine = C4::Context->preference('MaxFine')) {
566         if ($total_amount_other + $amount > $maxfine) {
567             my $new_amount = $maxfine - $total_amount_other;
568             return if $new_amount <= 0.00;
569             warn "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
570             $amount = $new_amount;
571         }
572     }
573
574     if ( $data ) {
575         # we're updating an existing fine.  Only modify if amount changed
576         # Note that in the current implementation, you cannot pay against an accruing fine
577         # (i.e. , of accounttype 'FU').  Doing so will break accrual.
578         if ( $data->{'amount'} != $amount ) {
579             my $accountline = Koha::Account::Lines->find( $data->{accountlines_id} );
580             my $diff = $amount - $data->{'amount'};
581
582             #3341: diff could be positive or negative!
583             my $out   = $data->{'amountoutstanding'} + $diff;
584
585             $accountline->set(
586                 {
587                     date          => dt_from_string(),
588                     amount        => $amount,
589                     outstanding   => $out,
590                     lastincrement => $diff,
591                     accounttype   => 'FU',
592                 }
593             )->store();
594         }
595     } else {
596         if ( $amount ) { # Don't add new fines with an amount of 0
597             my $sth4 = $dbh->prepare(
598                 "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
599             );
600             $sth4->execute($itemnum);
601             my $title = $sth4->fetchrow;
602
603             my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
604
605             my $desc = ( $type ? "$type " : '' ) . "$title $due";    # FIXEDME, avoid whitespace prefix on empty $type
606
607             my $accountline = Koha::Account::Line->new(
608                 {
609                     borrowernumber    => $borrowernumber,
610                     itemnumber        => $itemnum,
611                     date              => dt_from_string(),
612                     amount            => $amount,
613                     description       => $desc,
614                     accounttype       => 'FU',
615                     amountoutstanding => $amount,
616                     lastincrement     => $amount,
617                     accountno         => $nextaccntno,
618                 }
619             )->store();
620         }
621     }
622     # logging action
623     &logaction(
624         "FINES",
625         $type,
626         $borrowernumber,
627         "due=".$due."  amount=".$amount." itemnumber=".$itemnum
628         ) if C4::Context->preference("FinesLog");
629 }
630
631 =head2 BorType
632
633     $borrower = &BorType($borrowernumber);
634
635 Looks up a patron by borrower number.
636
637 C<$borrower> is a reference-to-hash whose keys are all of the fields
638 from the borrowers and categories tables of the Koha database. Thus,
639 C<$borrower> contains all information about both the borrower and
640 category he or she belongs to.
641
642 =cut
643
644 sub BorType {
645     my ($borrowernumber) = @_;
646     my $dbh              = C4::Context->dbh;
647     my $sth              = $dbh->prepare(
648         "SELECT * from borrowers
649       LEFT JOIN categories ON borrowers.categorycode=categories.categorycode 
650       WHERE borrowernumber=?"
651     );
652     $sth->execute($borrowernumber);
653     return $sth->fetchrow_hashref;
654 }
655
656 =head2 GetFine
657
658     $data->{'sum(amountoutstanding)'} = &GetFine($itemnum,$borrowernumber);
659
660 return the total of fine
661
662 C<$itemnum> is item number
663
664 C<$borrowernumber> is the borrowernumber
665
666 =cut 
667
668 sub GetFine {
669     my ( $itemnum, $borrowernumber ) = @_;
670     my $dbh   = C4::Context->dbh();
671     my $query = q|SELECT sum(amountoutstanding) as fineamount FROM accountlines
672     where accounttype like 'F%'
673   AND amountoutstanding > 0 AND borrowernumber=?|;
674     my @query_param;
675     push @query_param, $borrowernumber;
676     if (defined $itemnum )
677     {
678         $query .= " AND itemnumber=?";
679         push @query_param, $itemnum;
680     }
681     my $sth = $dbh->prepare($query);
682     $sth->execute( @query_param );
683     my $fine = $sth->fetchrow_hashref();
684     if ($fine->{fineamount}) {
685         return $fine->{fineamount};
686     }
687     return 0;
688 }
689
690 =head2 NumberNotifyId
691
692     (@notify) = &NumberNotifyId($borrowernumber);
693
694 Returns amount for all file per borrowers
695 C<@notify> array contains all file per borrowers
696
697 C<$notify_id> contains the file number for the borrower number nad item number
698
699 =cut
700
701 sub NumberNotifyId{
702     my ($borrowernumber)=@_;
703     my $dbh = C4::Context->dbh;
704     my $query=qq|    SELECT distinct(notify_id)
705             FROM accountlines
706             WHERE borrowernumber=?|;
707     my @notify;
708     my $sth = $dbh->prepare($query);
709     $sth->execute($borrowernumber);
710     while ( my ($numberofnotify) = $sth->fetchrow ) {
711         push( @notify, $numberofnotify );
712     }
713     return (@notify);
714 }
715
716 =head2 AmountNotify
717
718     ($totalnotify) = &AmountNotify($notifyid);
719
720 Returns amount for all file per borrowers
721 C<$notifyid> is the file number
722
723 C<$totalnotify> contains amount of a file
724
725 C<$notify_id> contains the file number for the borrower number and item number
726
727 =cut
728
729 sub AmountNotify{
730     my ($notifyid,$borrowernumber)=@_;
731     my $dbh = C4::Context->dbh;
732     my $query=qq|    SELECT sum(amountoutstanding)
733             FROM accountlines
734             WHERE notify_id=? AND borrowernumber = ?|;
735     my $sth=$dbh->prepare($query);
736         $sth->execute($notifyid,$borrowernumber);
737         my $totalnotify=$sth->fetchrow;
738     $sth->finish;
739     return ($totalnotify);
740 }
741
742 =head2 GetItems
743
744     ($items) = &GetItems($itemnumber);
745
746 Returns the list of all delays from overduerules.
747
748 C<$items> is a reference-to-hash whose keys are all of the fields
749 from the items tables of the Koha database. Thus,
750
751 C<$itemnumber> contains the borrower categorycode
752
753 =cut
754
755 # FIXME: This is a bad function to have here.
756 # Shouldn't it be in C4::Items?
757 # Shouldn't it be called GetItem since you only get 1 row?
758 # Shouldn't it be called GetItem since you give it only 1 itemnumber?
759
760 sub GetItems {
761     my $itemnumber = shift or return;
762     my $query = qq|SELECT *
763              FROM items
764               WHERE itemnumber=?|;
765     my $sth = C4::Context->dbh->prepare($query);
766     $sth->execute($itemnumber);
767     my ($items) = $sth->fetchrow_hashref;
768     return ($items);
769 }
770
771 =head2 GetBranchcodesWithOverdueRules
772
773     my @branchcodes = C4::Overdues::GetBranchcodesWithOverdueRules()
774
775 returns a list of branch codes for branches with overdue rules defined.
776
777 =cut
778
779 sub GetBranchcodesWithOverdueRules {
780     my $dbh               = C4::Context->dbh;
781     my $branchcodes = $dbh->selectcol_arrayref(q|
782         SELECT DISTINCT(branchcode)
783         FROM overduerules
784         WHERE delay1 IS NOT NULL
785         ORDER BY branchcode
786     |);
787     if ( $branchcodes->[0] eq '' ) {
788         # If a default rule exists, all branches should be returned
789         my $availbranches = C4::Branch::GetBranches();
790         return keys %$availbranches;
791     }
792     return @$branchcodes;
793 }
794
795 =head2 CheckItemNotify
796
797 Sql request to check if the document has alreday been notified
798 this function is not exported, only used with GetOverduesForBranch
799
800 =cut
801
802 sub CheckItemNotify {
803     my ($notify_id,$notify_level,$itemnumber) = @_;
804     my $dbh = C4::Context->dbh;
805     my $sth = $dbh->prepare("
806     SELECT COUNT(*)
807      FROM notifys
808     WHERE notify_id    = ?
809      AND  notify_level = ? 
810      AND  itemnumber   = ? ");
811     $sth->execute($notify_id,$notify_level,$itemnumber);
812     my $notified = $sth->fetchrow;
813     return ($notified);
814 }
815
816 =head2 GetOverduesForBranch
817
818 Sql request for display all information for branchoverdues.pl
819 2 possibilities : with or without location .
820 display is filtered by branch
821
822 FIXME: This function should be renamed.
823
824 =cut
825
826 sub GetOverduesForBranch {
827     my ( $branch, $location) = @_;
828         my $itype_link =  (C4::Context->preference('item-level_itypes')) ?  " items.itype " :  " biblioitems.itemtype ";
829     my $dbh = C4::Context->dbh;
830     my $select = "
831     SELECT
832             borrowers.cardnumber,
833             borrowers.borrowernumber,
834             borrowers.surname,
835             borrowers.firstname,
836             borrowers.phone,
837             borrowers.email,
838                biblio.title,
839                biblio.author,
840                biblio.biblionumber,
841                issues.date_due,
842                issues.returndate,
843                issues.branchcode,
844              branches.branchname,
845                 items.barcode,
846                 items.homebranch,
847                 items.itemcallnumber,
848                 items.location,
849                 items.itemnumber,
850             itemtypes.description,
851          accountlines.notify_id,
852          accountlines.notify_level,
853          accountlines.amountoutstanding
854     FROM  accountlines
855     LEFT JOIN issues      ON    issues.itemnumber     = accountlines.itemnumber
856                           AND   issues.borrowernumber = accountlines.borrowernumber
857     LEFT JOIN borrowers   ON borrowers.borrowernumber = accountlines.borrowernumber
858     LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
859     LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
860     LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
861     LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
862     LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
863     WHERE (accountlines.amountoutstanding  != '0.000000')
864       AND (accountlines.accounttype         = 'FU'      )
865       AND (issues.branchcode =  ?   )
866       AND (issues.date_due  < NOW())
867     ";
868     my @getoverdues;
869     my $i = 0;
870     my $sth;
871     if ($location) {
872         $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
873         $sth->execute($branch, $location);
874     } else {
875         $sth = $dbh->prepare("$select ORDER BY borrowers.surname, borrowers.firstname");
876         $sth->execute($branch);
877     }
878     while ( my $data = $sth->fetchrow_hashref ) {
879     #check if the document has already been notified
880         my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
881         if ($countnotify eq '0') {
882             $getoverdues[$i] = $data;
883             $i++;
884         }
885     }
886     return (@getoverdues);
887 }
888
889
890 =head2 AddNotifyLine
891
892     &AddNotifyLine($borrowernumber, $itemnumber, $overduelevel, $method, $notifyId)
893
894 Create a line into notify, if the method is phone, the notification_send_date is implemented to
895
896 =cut
897
898 sub AddNotifyLine {
899     my ( $borrowernumber, $itemnumber, $overduelevel, $method, $notifyId ) = @_;
900     my $dbh = C4::Context->dbh;
901     if ( $method eq "phone" ) {
902         my $sth = $dbh->prepare(
903             "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_send_date,notify_level,method,notify_id)
904         VALUES (?,?,now(),now(),?,?,?)"
905         );
906         $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
907             $notifyId );
908     }
909     else {
910         my $sth = $dbh->prepare(
911             "INSERT INTO notifys (borrowernumber,itemnumber,notify_date,notify_level,method,notify_id)
912         VALUES (?,?,now(),?,?,?)"
913         );
914         $sth->execute( $borrowernumber, $itemnumber, $overduelevel, $method,
915             $notifyId );
916     }
917     return 1;
918 }
919
920 =head2 RemoveNotifyLine
921
922     &RemoveNotifyLine( $borrowernumber, $itemnumber, $notify_date );
923
924 Cancel a notification
925
926 =cut
927
928 sub RemoveNotifyLine {
929     my ( $borrowernumber, $itemnumber, $notify_date ) = @_;
930     my $dbh = C4::Context->dbh;
931     my $sth = $dbh->prepare(
932         "DELETE FROM notifys 
933             WHERE
934             borrowernumber=?
935             AND itemnumber=?
936             AND notify_date=?"
937     );
938     $sth->execute( $borrowernumber, $itemnumber, $notify_date );
939     return 1;
940 }
941
942 =head2 GetOverdueMessageTransportTypes
943
944     my $message_transport_types = GetOverdueMessageTransportTypes( $branchcode, $categorycode, $letternumber);
945
946     return a arrayref with all message_transport_type for given branchcode, categorycode and letternumber(1,2 or 3)
947
948 =cut
949
950 sub GetOverdueMessageTransportTypes {
951     my ( $branchcode, $categorycode, $letternumber ) = @_;
952     return unless $categorycode and $letternumber;
953     my $dbh = C4::Context->dbh;
954     my $sth = $dbh->prepare("
955         SELECT message_transport_type
956         FROM overduerules odr LEFT JOIN overduerules_transport_types ott USING (overduerules_id)
957         WHERE branchcode = ?
958           AND categorycode = ?
959           AND letternumber = ?
960     ");
961     $sth->execute( $branchcode, $categorycode, $letternumber );
962     my @mtts;
963     while ( my $mtt = $sth->fetchrow ) {
964         push @mtts, $mtt;
965     }
966
967     # Put 'print' in first if exists
968     # It avoid to sent a print notice with an email or sms template is no email or sms is defined
969     @mtts = uniq( 'print', @mtts )
970         if grep {/^print$/} @mtts;
971
972     return \@mtts;
973 }
974
975 =head2 parse_overdues_letter
976
977 parses the letter template, replacing the placeholders with data
978 specific to this patron, biblio, or item for overdues
979
980 named parameters:
981   letter - required hashref
982   borrowernumber - required integer
983   substitute - optional hashref of other key/value pairs that should
984     be substituted in the letter content
985
986 returns the C<letter> hashref, with the content updated to reflect the
987 substituted keys and values.
988
989 =cut
990
991 sub parse_overdues_letter {
992     my $params = shift;
993     foreach my $required (qw( letter_code borrowernumber )) {
994         return unless ( exists $params->{$required} && $params->{$required} );
995     }
996
997     my $substitute = $params->{'substitute'} || {};
998     $substitute->{today} ||= output_pref( { dt => dt_from_string, dateonly => 1} );
999
1000     my %tables = ( 'borrowers' => $params->{'borrowernumber'} );
1001     if ( my $p = $params->{'branchcode'} ) {
1002         $tables{'branches'} = $p;
1003     }
1004
1005     my $active_currency = Koha::Acquisition::Currencies->get_active;
1006
1007     my $currency_format;
1008     $currency_format = $active_currency->currency if defined($active_currency);
1009
1010     my @item_tables;
1011     if ( my $i = $params->{'items'} ) {
1012         my $item_format = '';
1013         foreach my $item (@$i) {
1014             my $fine = GetFine($item->{'itemnumber'}, $params->{'borrowernumber'});
1015             if ( !$item_format and defined $params->{'letter'}->{'content'} ) {
1016                 $params->{'letter'}->{'content'} =~ m/(<item>.*<\/item>)/;
1017                 $item_format = $1;
1018             }
1019
1020             $item->{'fine'} = currency_format($currency_format, "$fine", FMT_SYMBOL);
1021             # if active currency isn't correct ISO code fallback to sprintf
1022             $item->{'fine'} = sprintf('%.2f', $fine) unless $item->{'fine'};
1023
1024             push @item_tables, {
1025                 'biblio' => $item->{'biblionumber'},
1026                 'biblioitems' => $item->{'biblionumber'},
1027                 'items' => $item,
1028                 'issues' => $item->{'itemnumber'},
1029             };
1030         }
1031     }
1032
1033     return C4::Letters::GetPreparedLetter (
1034         module => 'circulation',
1035         letter_code => $params->{'letter_code'},
1036         branchcode => $params->{'branchcode'},
1037         tables => \%tables,
1038         substitute => $substitute,
1039         repeat => { item => \@item_tables },
1040         message_transport_type => $params->{message_transport_type},
1041     );
1042 }
1043
1044 1;
1045 __END__
1046
1047 =head1 AUTHOR
1048
1049 Koha Development Team <http://koha-community.org/>
1050
1051 =cut