Merge remote branch 'kc/new/biblibre_reports' into kcmaster
[koha.git] / C4 / Serials.pm
1 package C4::Serials;
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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22 use C4::Dates qw(format_date format_date_in_iso);
23 use Date::Calc qw(:all);
24 use POSIX qw(strftime);
25 use C4::Suggestions;
26 use C4::Koha;
27 use C4::Biblio;
28 use C4::Branch;
29 use C4::Items;
30 use C4::Search;
31 use C4::Letters;
32 use C4::Log;    # logaction
33 use C4::Debug;
34
35 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
36
37 BEGIN {
38     $VERSION = 3.01;    # set version for version checking
39     require Exporter;
40     @ISA    = qw(Exporter);
41     @EXPORT = qw(
42       &NewSubscription    &ModSubscription    &DelSubscription    &GetSubscriptions
43       &GetSubscription    &CountSubscriptionFromBiblionumber      &GetSubscriptionsFromBiblionumber
44       &GetFullSubscriptionsFromBiblionumber   &GetFullSubscription &ModSubscriptionHistory
45       &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
46
47       &GetNextSeq         &NewIssue           &ItemizeSerials    &GetSerials
48       &GetLatestSerials   &ModSerialStatus    &GetNextDate       &GetSerials2
49       &ReNewSubscription  &GetLateIssues      &GetLateOrMissingIssues
50       &GetSerialInformation                   &AddItem2Serial
51       &PrepareSerialsData &GetNextExpected    &ModNextExpected
52
53       &UpdateClaimdateIssues
54       &GetSuppliersWithLateIssues             &getsupplierbyserialid
55       &GetDistributedTo   &SetDistributedTo
56       &getroutinglist     &delroutingmember   &addroutingmember
57       &reorder_members
58       &check_routing &updateClaim &removeMissingIssue
59       &CountIssues
60       HasItems
61
62     );
63 }
64
65 =head1 NAME
66
67 C4::Serials - Serials Module Functions
68
69 =head1 SYNOPSIS
70
71   use C4::Serials;
72
73 =head1 DESCRIPTION
74
75 Functions for handling subscriptions, claims routing etc.
76
77
78 =head1 SUBROUTINES
79
80 =head2 GetSuppliersWithLateIssues
81
82 $supplierlist = GetSuppliersWithLateIssues()
83
84 this function get all suppliers with late issues.
85
86 return :
87 an array_ref of suppliers each entry is a hash_ref containing id and name
88 the array is in name order
89
90 =cut
91
92 sub GetSuppliersWithLateIssues {
93     my $dbh   = C4::Context->dbh;
94     my $query = q|
95     SELECT DISTINCT aqbooksellerid as id, aqbooksellers.name as name
96     FROM            subscription
97     LEFT JOIN       serial ON serial.subscriptionid=subscription.subscriptionid
98     LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
99     WHERE id > 0 AND (planneddate < now() OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
100     return $dbh->selectall_arrayref($query, { Slice => {} });
101 }
102
103 =head2 GetLateIssues
104
105 @issuelist = GetLateIssues($supplierid)
106
107 this function selects late issues from the database
108
109 return :
110 the issuelist as an array. Each element of this array contains a hashi_ref containing
111 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
112
113 =cut
114
115 sub GetLateIssues {
116     my ($supplierid) = @_;
117     my $dbh = C4::Context->dbh;
118     my $sth;
119     if ($supplierid) {
120         my $query = qq|
121             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
122             FROM       subscription
123             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
124             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
125             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
126             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
127             AND        subscription.aqbooksellerid=$supplierid
128             ORDER BY   title
129         |;
130         $sth = $dbh->prepare($query);
131     } else {
132         my $query = qq|
133             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
134             FROM       subscription
135             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
136             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
137             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
138             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
139             ORDER BY   title
140         |;
141         $sth = $dbh->prepare($query);
142     }
143     $sth->execute;
144     my @issuelist;
145     my $last_title;
146     my $odd   = 0;
147     while ( my $line = $sth->fetchrow_hashref ) {
148         $odd++ unless $line->{title} eq $last_title;
149         $line->{title} = "" if $line->{title} eq $last_title;
150         $last_title = $line->{title} if ( $line->{title} );
151         $line->{planneddate} = format_date( $line->{planneddate} );
152         push @issuelist, $line;
153     }
154     return @issuelist;
155 }
156
157 =head2 GetSubscriptionHistoryFromSubscriptionId
158
159 $sth = GetSubscriptionHistoryFromSubscriptionId()
160 this function prepares the SQL request and returns the statement handle
161 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
162
163 =cut
164
165 sub GetSubscriptionHistoryFromSubscriptionId() {
166     my $dbh   = C4::Context->dbh;
167     my $query = qq|
168         SELECT *
169         FROM   subscriptionhistory
170         WHERE  subscriptionid = ?
171     |;
172     return $dbh->prepare($query);
173 }
174
175 =head2 GetSerialStatusFromSerialId
176
177 $sth = GetSerialStatusFromSerialId();
178 this function returns a statement handle
179 After this function, don't forget to execute it by using $sth->execute($serialid)
180 return :
181 $sth = $dbh->prepare($query).
182
183 =cut
184
185 sub GetSerialStatusFromSerialId() {
186     my $dbh   = C4::Context->dbh;
187     my $query = qq|
188         SELECT status
189         FROM   serial
190         WHERE  serialid = ?
191     |;
192     return $dbh->prepare($query);
193 }
194
195 =head2 GetSerialInformation
196
197
198 $data = GetSerialInformation($serialid);
199 returns a hash_ref containing :
200   items : items marcrecord (can be an array)
201   serial table field
202   subscription table field
203   + information about subscription expiration
204
205 =cut
206
207 sub GetSerialInformation {
208     my ($serialid) = @_;
209     my $dbh        = C4::Context->dbh;
210     my $query      = qq|
211         SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
212     if (   C4::Context->preference('IndependantBranches')
213         && C4::Context->userenv
214         && C4::Context->userenv->{'flags'} != 1
215         && C4::Context->userenv->{'branch'} ) {
216         $query .= "
217       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
218     }
219     $query .= qq|             
220         FROM   serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
221         WHERE  serialid = ?
222     |;
223     my $rq = $dbh->prepare($query);
224     $rq->execute($serialid);
225     my $data = $rq->fetchrow_hashref;
226
227     # create item information if we have serialsadditems for this subscription
228     if ( $data->{'serialsadditems'} ) {
229         my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
230         $queryitem->execute($serialid);
231         my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
232         if ( scalar(@$itemnumbers) > 0 ) {
233             foreach my $itemnum (@$itemnumbers) {
234
235                 #It is ASSUMED that GetMarcItem ALWAYS WORK...
236                 #Maybe GetMarcItem should return values on failure
237                 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
238                 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
239                 $itemprocessed->{'itemnumber'}   = $itemnum->[0];
240                 $itemprocessed->{'itemid'}       = $itemnum->[0];
241                 $itemprocessed->{'serialid'}     = $serialid;
242                 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
243                 push @{ $data->{'items'} }, $itemprocessed;
244             }
245         } else {
246             my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
247             $itemprocessed->{'itemid'}       = "N$serialid";
248             $itemprocessed->{'serialid'}     = $serialid;
249             $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
250             $itemprocessed->{'countitems'}   = 0;
251             push @{ $data->{'items'} }, $itemprocessed;
252         }
253     }
254     $data->{ "status" . $data->{'serstatus'} } = 1;
255     $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
256     $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
257     return $data;
258 }
259
260 =head2 AddItem2Serial
261
262 $rows = AddItem2Serial($serialid,$itemnumber);
263 Adds an itemnumber to Serial record
264 returns the number of rows affected
265
266 =cut
267
268 sub AddItem2Serial {
269     my ( $serialid, $itemnumber ) = @_;
270     my $dbh = C4::Context->dbh;
271     my $rq  = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
272     $rq->execute( $serialid, $itemnumber );
273     return $rq->rows;
274 }
275
276 =head2 UpdateClaimdateIssues
277
278 UpdateClaimdateIssues($serialids,[$date]);
279
280 Update Claimdate for issues in @$serialids list with date $date
281 (Take Today if none)
282
283 =cut
284
285 sub UpdateClaimdateIssues {
286     my ( $serialids, $date ) = @_;
287     my $dbh = C4::Context->dbh;
288     $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
289     my $query = "
290         UPDATE serial SET claimdate = ?, status = 7
291         WHERE  serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
292     my $rq = $dbh->prepare($query);
293     $rq->execute($date, @$serialids);
294     return $rq->rows;
295 }
296
297 =head2 GetSubscription
298
299 $subs = GetSubscription($subscriptionid)
300 this function returns the subscription which has $subscriptionid as id.
301 return :
302 a hashref. This hash containts
303 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
304
305 =cut
306
307 sub GetSubscription {
308     my ($subscriptionid) = @_;
309     my $dbh              = C4::Context->dbh;
310     my $query            = qq(
311         SELECT  subscription.*,
312                 subscriptionhistory.*,
313                 aqbooksellers.name AS aqbooksellername,
314                 biblio.title AS bibliotitle,
315                 subscription.biblionumber as bibnum);
316     if (   C4::Context->preference('IndependantBranches')
317         && C4::Context->userenv
318         && C4::Context->userenv->{'flags'} != 1
319         && C4::Context->userenv->{'branch'} ) {
320         $query .= "
321       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
322     }
323     $query .= qq(             
324        FROM subscription
325        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
326        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
327        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
328        WHERE subscription.subscriptionid = ?
329     );
330
331     #     if (C4::Context->preference('IndependantBranches') &&
332     #         C4::Context->userenv &&
333     #         C4::Context->userenv->{'flags'} != 1){
334     # #       $debug and warn "flags: ".C4::Context->userenv->{'flags'};
335     #       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
336     #     }
337     $debug and warn "query : $query\nsubsid :$subscriptionid";
338     my $sth = $dbh->prepare($query);
339     $sth->execute($subscriptionid);
340     return $sth->fetchrow_hashref;
341 }
342
343 =head2 GetFullSubscription
344
345    $array_ref = GetFullSubscription($subscriptionid)
346    this function reads the serial table.
347
348 =cut
349
350 sub GetFullSubscription {
351     my ($subscriptionid) = @_;
352     my $dbh              = C4::Context->dbh;
353     my $query            = qq|
354   SELECT    serial.serialid,
355             serial.serialseq,
356             serial.planneddate, 
357             serial.publisheddate, 
358             serial.status, 
359             serial.notes as notes,
360             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
361             aqbooksellers.name as aqbooksellername,
362             biblio.title as bibliotitle,
363             subscription.branchcode AS branchcode,
364             subscription.subscriptionid AS subscriptionid |;
365     if (   C4::Context->preference('IndependantBranches')
366         && C4::Context->userenv
367         && C4::Context->userenv->{'flags'} != 1
368         && C4::Context->userenv->{'branch'} ) {
369         $query .= "
370       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
371     }
372     $query .= qq|
373   FROM      serial 
374   LEFT JOIN subscription ON 
375           (serial.subscriptionid=subscription.subscriptionid )
376   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
377   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
378   WHERE     serial.subscriptionid = ? 
379   ORDER BY year DESC,
380           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
381           serial.subscriptionid
382           |;
383     $debug and warn "GetFullSubscription query: $query";
384     my $sth = $dbh->prepare($query);
385     $sth->execute($subscriptionid);
386     return $sth->fetchall_arrayref( {} );
387 }
388
389 =head2 PrepareSerialsData
390
391    $array_ref = PrepareSerialsData($serialinfomation)
392    where serialinformation is a hashref array
393
394 =cut
395
396 sub PrepareSerialsData {
397     my ($lines) = @_;
398     my %tmpresults;
399     my $year;
400     my @res;
401     my $startdate;
402     my $aqbooksellername;
403     my $bibliotitle;
404     my @loopissues;
405     my $first;
406     my $previousnote = "";
407
408     foreach my $subs (@{$lines}) {
409         for my $datefield ( qw(publisheddate planneddate) ) {
410             # handle both undef and undef returned as 0000-00-00
411             if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
412                 $subs->{$datefield} = 'XXX';
413             }
414             else {
415                 $subs->{$datefield} = format_date( $subs->{$datefield}  );
416             }
417         }
418         $subs->{'branchname'} = GetBranchName( $subs->{'branchcode'} );
419         $subs->{ "status" . $subs->{'status'} } = 1;
420         $subs->{"checked"}                      = $subs->{'status'} =~ /1|3|4|7/;
421
422         if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
423             $year = $subs->{'year'};
424         } else {
425             $year = "manage";
426         }
427         if ( $tmpresults{$year} ) {
428             push @{ $tmpresults{$year}->{'serials'} }, $subs;
429         } else {
430             $tmpresults{$year} = {
431                 'year'             => $year,
432                 'aqbooksellername' => $subs->{'aqbooksellername'},
433                 'bibliotitle'      => $subs->{'bibliotitle'},
434                 'serials'          => [$subs],
435                 'first'            => $first,
436             };
437         }
438     }
439     foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
440         push @res, $tmpresults{$key};
441     }
442     $res[0]->{'first'} = 1;
443     return \@res;
444 }
445
446 =head2 GetSubscriptionsFromBiblionumber
447
448 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
449 this function get the subscription list. it reads the subscription table.
450 return :
451 reference to an array of subscriptions which have the biblionumber given on input arg.
452 each element of this array is a hashref containing
453 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
454
455 =cut
456
457 sub GetSubscriptionsFromBiblionumber {
458     my ($biblionumber) = @_;
459     my $dbh            = C4::Context->dbh;
460     my $query          = qq(
461         SELECT subscription.*,
462                branches.branchname,
463                subscriptionhistory.*,
464                aqbooksellers.name AS aqbooksellername,
465                biblio.title AS bibliotitle
466        FROM subscription
467        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
468        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
469        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
470        LEFT JOIN branches ON branches.branchcode=subscription.branchcode
471        WHERE subscription.biblionumber = ?
472     );
473     my $sth = $dbh->prepare($query);
474     $sth->execute($biblionumber);
475     my @res;
476     while ( my $subs = $sth->fetchrow_hashref ) {
477         $subs->{startdate}     = format_date( $subs->{startdate} );
478         $subs->{histstartdate} = format_date( $subs->{histstartdate} );
479         $subs->{histenddate}   = format_date( $subs->{histenddate} );
480         $subs->{opacnote}     =~ s/\n/\<br\/\>/g;
481         $subs->{missinglist}  =~ s/\n/\<br\/\>/g;
482         $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
483         $subs->{ "periodicity" . $subs->{periodicity} }     = 1;
484         $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
485         $subs->{ "status" . $subs->{'status'} }             = 1;
486         $subs->{'cannotedit'} =
487           (      C4::Context->preference('IndependantBranches')
488               && C4::Context->userenv
489               && C4::Context->userenv->{flags} % 2 != 1
490               && C4::Context->userenv->{branch}
491               && $subs->{branchcode}
492               && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
493
494         if ( $subs->{enddate} eq '0000-00-00' ) {
495             $subs->{enddate} = '';
496         } else {
497             $subs->{enddate} = format_date( $subs->{enddate} );
498         }
499         $subs->{'abouttoexpire'}       = abouttoexpire( $subs->{'subscriptionid'} );
500         $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
501         push @res, $subs;
502     }
503     return \@res;
504 }
505
506 =head2 GetFullSubscriptionsFromBiblionumber
507
508    $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
509    this function reads the serial table.
510
511 =cut
512
513 sub GetFullSubscriptionsFromBiblionumber {
514     my ($biblionumber) = @_;
515     my $dbh            = C4::Context->dbh;
516     my $query          = qq|
517   SELECT    serial.serialid,
518             serial.serialseq,
519             serial.planneddate, 
520             serial.publisheddate, 
521             serial.status, 
522             serial.notes as notes,
523             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
524             biblio.title as bibliotitle,
525             subscription.branchcode AS branchcode,
526             subscription.subscriptionid AS subscriptionid|;
527     if (   C4::Context->preference('IndependantBranches')
528         && C4::Context->userenv
529         && C4::Context->userenv->{'flags'} != 1
530         && C4::Context->userenv->{'branch'} ) {
531         $query .= "
532       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
533     }
534
535     $query .= qq|      
536   FROM      serial 
537   LEFT JOIN subscription ON 
538           (serial.subscriptionid=subscription.subscriptionid)
539   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
540   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
541   WHERE     subscription.biblionumber = ? 
542   ORDER BY year DESC,
543           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
544           serial.subscriptionid
545           |;
546     my $sth = $dbh->prepare($query);
547     $sth->execute($biblionumber);
548     return $sth->fetchall_arrayref( {} );
549 }
550
551 =head2 GetSubscriptions
552
553 @results = GetSubscriptions($title,$ISSN,$biblionumber);
554 this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
555 return:
556 a table of hashref. Each hash containt the subscription.
557
558 =cut
559
560 sub GetSubscriptions {
561     my ( $string, $issn, $biblionumber ) = @_;
562
563     #return unless $title or $ISSN or $biblionumber;
564     my $dbh = C4::Context->dbh;
565     my $sth;
566     my $sql = qq(
567             SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
568             FROM   subscription
569             LEFT JOIN subscriptionhistory USING(subscriptionid)
570             LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
571             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
572     );
573     my @bind_params;
574     my $sqlwhere;
575     if ($biblionumber) {
576         $sqlwhere = "   WHERE biblio.biblionumber=?";
577         push @bind_params, $biblionumber;
578     }
579     if ($string) {
580         my @sqlstrings;
581         my @strings_to_search;
582         @strings_to_search = map { "%$_%" } split( / /, $string );
583         foreach my $index qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes) {
584             push @bind_params, @strings_to_search;
585             my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
586             $debug && warn "$tmpstring";
587             $tmpstring =~ s/^AND //;
588             push @sqlstrings, $tmpstring;
589         }
590         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "(" . join( ") OR (", @sqlstrings ) . ")";
591     }
592     if ($issn) {
593         my @sqlstrings;
594         my @strings_to_search;
595         @strings_to_search = map { "%$_%" } split( / /, $issn );
596         foreach my $index qw(biblioitems.issn subscription.callnumber) {
597             push @bind_params, @strings_to_search;
598             my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
599             $debug && warn "$tmpstring";
600             $tmpstring =~ s/^OR //;
601             push @sqlstrings, $tmpstring;
602         }
603         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "(" . join( ") OR (", @sqlstrings ) . ")";
604     }
605     $sql .= "$sqlwhere ORDER BY title";
606     $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
607     $sth = $dbh->prepare($sql);
608     $sth->execute(@bind_params);
609     my @results;
610     my $previoustitle = "";
611     my $odd           = 1;
612
613     while ( my $line = $sth->fetchrow_hashref ) {
614         if ( $previoustitle eq $line->{title} ) {
615             $line->{title} = "";
616             $line->{issn}  = "";
617         } else {
618             $previoustitle = $line->{title};
619             $odd           = -$odd;
620         }
621         $line->{toggle} = 1 if $odd == 1;
622         $line->{'cannotedit'} =
623           (      C4::Context->preference('IndependantBranches')
624               && C4::Context->userenv
625               && C4::Context->userenv->{flags} % 2 != 1
626               && C4::Context->userenv->{branch}
627               && $line->{branchcode}
628               && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
629         push @results, $line;
630     }
631     return @results;
632 }
633
634 =head2 GetSerials
635
636 ($totalissues,@serials) = GetSerials($subscriptionid);
637 this function gets every serial not arrived for a given subscription
638 as well as the number of issues registered in the database (all types)
639 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
640
641 FIXME: We should return \@serials.
642
643 =cut
644
645 sub GetSerials {
646     my ( $subscriptionid, $count ) = @_;
647     my $dbh = C4::Context->dbh;
648
649     # status = 2 is "arrived"
650     my $counter = 0;
651     $count = 5 unless ($count);
652     my @serials;
653     my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
654                         FROM   serial
655                         WHERE  subscriptionid = ? AND status NOT IN (2,4,5) 
656                         ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
657     my $sth = $dbh->prepare($query);
658     $sth->execute($subscriptionid);
659
660     while ( my $line = $sth->fetchrow_hashref ) {
661         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
662         for my $datefield ( qw( planneddate publisheddate) ) {
663             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
664                 $line->{$datefield} = format_date( $line->{$datefield});
665             } else {
666                 $line->{$datefield} = q{};
667             }
668         }
669         push @serials, $line;
670     }
671
672     # OK, now add the last 5 issues arrives/missing
673     $query = "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
674        FROM     serial
675        WHERE    subscriptionid = ?
676        AND      (status in (2,4,5))
677        ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
678       ";
679     $sth = $dbh->prepare($query);
680     $sth->execute($subscriptionid);
681     while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
682         $counter++;
683         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
684         for my $datefield ( qw( planneddate publisheddate) ) {
685             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
686                 $line->{$datefield} = format_date( $line->{$datefield});
687             } else {
688                 $line->{$datefield} = q{};
689             }
690         }
691
692         push @serials, $line;
693     }
694
695     $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
696     $sth   = $dbh->prepare($query);
697     $sth->execute($subscriptionid);
698     my ($totalissues) = $sth->fetchrow;
699     return ( $totalissues, @serials );
700 }
701
702 =head2 GetSerials2
703
704 @serials = GetSerials2($subscriptionid,$status);
705 this function returns every serial waited for a given subscription
706 as well as the number of issues registered in the database (all types)
707 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
708
709 =cut
710
711 sub GetSerials2 {
712     my ( $subscription, $status ) = @_;
713     my $dbh   = C4::Context->dbh;
714     my $query = qq|
715                  SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
716                  FROM     serial 
717                  WHERE    subscriptionid=$subscription AND status IN ($status)
718                  ORDER BY publisheddate,serialid DESC
719                     |;
720     $debug and warn "GetSerials2 query: $query";
721     my $sth = $dbh->prepare($query);
722     $sth->execute;
723     my @serials;
724
725     while ( my $line = $sth->fetchrow_hashref ) {
726         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
727         $line->{"planneddate"}                = format_date( $line->{"planneddate"} );
728         $line->{"publisheddate"}              = format_date( $line->{"publisheddate"} );
729         push @serials, $line;
730     }
731     return @serials;
732 }
733
734 =head2 GetLatestSerials
735
736 \@serials = GetLatestSerials($subscriptionid,$limit)
737 get the $limit's latest serials arrived or missing for a given subscription
738 return :
739 a ref to an array which contains all of the latest serials stored into a hash.
740
741 =cut
742
743 sub GetLatestSerials {
744     my ( $subscriptionid, $limit ) = @_;
745     my $dbh = C4::Context->dbh;
746
747     # status = 2 is "arrived"
748     my $strsth = "SELECT   serialid,serialseq, status, planneddate, notes
749                         FROM     serial
750                         WHERE    subscriptionid = ?
751                         AND      (status =2 or status=4)
752                         ORDER BY planneddate DESC LIMIT 0,$limit
753                 ";
754     my $sth = $dbh->prepare($strsth);
755     $sth->execute($subscriptionid);
756     my @serials;
757     while ( my $line = $sth->fetchrow_hashref ) {
758         $line->{ "status" . $line->{status} } = 1;                        # fills a "statusX" value, used for template status select list
759         $line->{"planneddate"} = format_date( $line->{"planneddate"} );
760         push @serials, $line;
761     }
762
763     return \@serials;
764 }
765
766 =head2 GetDistributedTo
767
768 $distributedto=GetDistributedTo($subscriptionid)
769 This function returns the field distributedto for the subscription matching subscriptionid
770
771 =cut
772
773 sub GetDistributedTo {
774     my $dbh = C4::Context->dbh;
775     my $distributedto;
776     my $subscriptionid = @_;
777     my $query          = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
778     my $sth            = $dbh->prepare($query);
779     $sth->execute($subscriptionid);
780     return ($distributedto) = $sth->fetchrow;
781 }
782
783 =head2 GetNextSeq
784
785 GetNextSeq($val)
786 $val is a hashref containing all the attributes of the table 'subscription'
787 This function get the next issue for the subscription given on input arg
788 return:
789 a list containing all the input params updated.
790
791 =cut
792
793 # sub GetNextSeq {
794 #     my ($val) =@_;
795 #     my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
796 #     $calculated = $val->{numberingmethod};
797 # # calculate the (expected) value of the next issue recieved.
798 #     $newlastvalue1 = $val->{lastvalue1};
799 # # check if we have to increase the new value.
800 #     $newinnerloop1 = $val->{innerloop1}+1;
801 #     $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
802 #     $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
803 #     $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
804 #     $calculated =~ s/\{X\}/$newlastvalue1/g;
805 #
806 #     $newlastvalue2 = $val->{lastvalue2};
807 # # check if we have to increase the new value.
808 #     $newinnerloop2 = $val->{innerloop2}+1;
809 #     $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
810 #     $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
811 #     $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
812 #     $calculated =~ s/\{Y\}/$newlastvalue2/g;
813 #
814 #     $newlastvalue3 = $val->{lastvalue3};
815 # # check if we have to increase the new value.
816 #     $newinnerloop3 = $val->{innerloop3}+1;
817 #     $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
818 #     $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
819 #     $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
820 #     $calculated =~ s/\{Z\}/$newlastvalue3/g;
821 #     return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
822 # }
823
824 sub GetNextSeq {
825     my ($val) = @_;
826     my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
827     my $pattern          = $val->{numberpattern};
828     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
829     my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
830     $calculated    = $val->{numberingmethod};
831     $newlastvalue1 = $val->{lastvalue1};
832     $newlastvalue2 = $val->{lastvalue2};
833     $newlastvalue3 = $val->{lastvalue3};
834     $newlastvalue1 = $val->{lastvalue1};
835
836     # check if we have to increase the new value.
837     $newinnerloop1 = $val->{innerloop1} + 1;
838     $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
839     $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 );    # <1 to be true when 0 or empty.
840     $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} );    # reset counter if needed.
841     $calculated =~ s/\{X\}/$newlastvalue1/g;
842
843     $newlastvalue2 = $val->{lastvalue2};
844
845     # check if we have to increase the new value.
846     $newinnerloop2 = $val->{innerloop2} + 1;
847     $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
848     $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 );                         # <1 to be true when 0 or empty.
849     $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} );    # reset counter if needed.
850     if ( $pattern == 6 ) {
851         if ( $val->{hemisphere} == 2 ) {
852             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
853             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
854         } else {
855             my $newlastvalue2seq = $seasons[$newlastvalue2];
856             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
857         }
858     } else {
859         $calculated =~ s/\{Y\}/$newlastvalue2/g;
860     }
861
862     $newlastvalue3 = $val->{lastvalue3};
863
864     # check if we have to increase the new value.
865     $newinnerloop3 = $val->{innerloop3} + 1;
866     $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
867     $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 );    # <1 to be true when 0 or empty.
868     $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} );    # reset counter if needed.
869     $calculated =~ s/\{Z\}/$newlastvalue3/g;
870
871     return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
872 }
873
874 =head2 GetSeq
875
876 $calculated = GetSeq($val)
877 $val is a hashref containing all the attributes of the table 'subscription'
878 this function transforms {X},{Y},{Z} to 150,0,0 for example.
879 return:
880 the sequence in integer format
881
882 =cut
883
884 sub GetSeq {
885     my ($val) = @_;
886     my $pattern = $val->{numberpattern};
887     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
888     my @southern_seasons = ( '',        'Summer', 'Autumn', 'Winter', 'Spring' );
889     my $calculated       = $val->{numberingmethod};
890     my $x                = $val->{'lastvalue1'};
891     $calculated =~ s/\{X\}/$x/g;
892     my $newlastvalue2 = $val->{'lastvalue2'};
893
894     if ( $pattern == 6 ) {
895         if ( $val->{hemisphere} == 2 ) {
896             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
897             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
898         } else {
899             my $newlastvalue2seq = $seasons[$newlastvalue2];
900             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
901         }
902     } else {
903         $calculated =~ s/\{Y\}/$newlastvalue2/g;
904     }
905     my $z = $val->{'lastvalue3'};
906     $calculated =~ s/\{Z\}/$z/g;
907     return $calculated;
908 }
909
910 =head2 GetExpirationDate
911
912 $sensddate = GetExpirationDate($subscriptionid, [$startdate])
913
914 this function return the next expiration date for a subscription given on input args.
915
916 return
917 the enddate or undef
918
919 =cut
920
921 sub GetExpirationDate {
922     my ( $subscriptionid, $startdate ) = @_;
923     my $dbh          = C4::Context->dbh;
924     my $subscription = GetSubscription($subscriptionid);
925     my $enddate;
926
927     # we don't do the same test if the subscription is based on X numbers or on X weeks/months
928     $enddate = $startdate || $subscription->{startdate};
929     my @date = split( /-/, $enddate );
930     return if ( scalar(@date) != 3 || not check_date(@date) );
931     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
932
933         # If Not Irregular
934         if ( my $length = $subscription->{numberlength} ) {
935
936             #calculate the date of the last issue.
937             for ( my $i = 1 ; $i <= $length ; $i++ ) {
938                 $enddate = GetNextDate( $enddate, $subscription );
939             }
940         } elsif ( $subscription->{monthlength} ) {
941             if ( $$subscription{startdate} ) {
942                 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
943                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
944             }
945         } elsif ( $subscription->{weeklength} ) {
946             if ( $$subscription{startdate} ) {
947                 my @date = split( /-/, $subscription->{startdate} );
948                 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
949                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
950             }
951         }
952         return $enddate;
953     } else {
954         return;
955     }
956 }
957
958 =head2 CountSubscriptionFromBiblionumber
959
960 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
961 this returns a count of the subscriptions for a given biblionumber
962 return :
963 the number of subscriptions
964
965 =cut
966
967 sub CountSubscriptionFromBiblionumber {
968     my ($biblionumber) = @_;
969     my $dbh            = C4::Context->dbh;
970     my $query          = "SELECT count(*) FROM subscription WHERE biblionumber=?";
971     my $sth            = $dbh->prepare($query);
972     $sth->execute($biblionumber);
973     my $subscriptionsnumber = $sth->fetchrow;
974     return $subscriptionsnumber;
975 }
976
977 =head2 ModSubscriptionHistory
978
979 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
980
981 this function modifies the history of a subscription. Put your new values on input arg.
982 returns the number of rows affected
983
984 =cut
985
986 sub ModSubscriptionHistory {
987     my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
988     my $dbh   = C4::Context->dbh;
989     my $query = "UPDATE subscriptionhistory 
990                     SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
991                     WHERE subscriptionid=?
992                 ";
993     my $sth = $dbh->prepare($query);
994     $recievedlist =~ s/^; //;
995     $missinglist  =~ s/^; //;
996     $opacnote     =~ s/^; //;
997     $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
998     return $sth->rows;
999 }
1000
1001 =head2 ModSerialStatus
1002
1003 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1004
1005 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1006 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1007
1008 =cut
1009
1010 sub ModSerialStatus {
1011     my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1012
1013     #It is a usual serial
1014     # 1st, get previous status :
1015     my $dbh   = C4::Context->dbh;
1016     my $query = "SELECT subscriptionid,status FROM serial WHERE  serialid=?";
1017     my $sth   = $dbh->prepare($query);
1018     $sth->execute($serialid);
1019     my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1020
1021     # change status & update subscriptionhistory
1022     my $val;
1023     if ( $status == 6 ) {
1024         DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1025     }
1026     else {
1027         my $query =
1028 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE  serialid = ?';
1029         $sth = $dbh->prepare($query);
1030         $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1031         $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1032         $sth   = $dbh->prepare($query);
1033         $sth->execute($subscriptionid);
1034         my $val = $sth->fetchrow_hashref;
1035         unless ( $val->{manualhistory} ) {
1036             $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE  subscriptionid=?";
1037             $sth   = $dbh->prepare($query);
1038             $sth->execute($subscriptionid);
1039             my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1040             if ( $status == 2 ) {
1041
1042                 $recievedlist .= "; $serialseq"
1043                   unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1044             }
1045
1046             #         warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1047             $missinglist .= "; $serialseq"
1048               if ( $status == 4
1049                 and not index( "$missinglist", "$serialseq" ) >= 0 );
1050             $missinglist .= "; not issued $serialseq"
1051               if ( $status == 5
1052                 and index( "$missinglist", "$serialseq" ) >= 0 );
1053             $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE  subscriptionid=?";
1054             $sth   = $dbh->prepare($query);
1055             $recievedlist =~ s/^; //;
1056             $missinglist  =~ s/^; //;
1057             $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1058         }
1059     }
1060
1061     # create new waited entry if needed (ie : was a "waited" and has changed)
1062     if ( $oldstatus == 1 && $status != 1 ) {
1063         my $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1064         $sth = $dbh->prepare($query);
1065         $sth->execute($subscriptionid);
1066         my $val = $sth->fetchrow_hashref;
1067
1068         # next issue number
1069         my (
1070             $newserialseq,  $newlastvalue1, $newlastvalue2, $newlastvalue3,
1071             $newinnerloop1, $newinnerloop2, $newinnerloop3
1072         ) = GetNextSeq($val);
1073
1074         # next date (calculated from actual date & frequency parameters)
1075         my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1076         NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1077         $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1078                     WHERE  subscriptionid = ?";
1079         $sth = $dbh->prepare($query);
1080         $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1081
1082 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1083         if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1084             SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1085         }
1086     }
1087     return;
1088 }
1089
1090 =head2 GetNextExpected
1091
1092 $nextexpected = GetNextExpected($subscriptionid)
1093
1094 Get the planneddate for the current expected issue of the subscription.
1095
1096 returns a hashref:
1097
1098 $nextexepected = {
1099     serialid => int
1100     planneddate => C4::Dates object
1101     }
1102
1103 =cut
1104
1105 sub GetNextExpected($) {
1106     my ($subscriptionid) = @_;
1107     my $dbh              = C4::Context->dbh;
1108     my $sth              = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1109
1110     # Each subscription has only one 'expected' issue, with serial.status==1.
1111     $sth->execute( $subscriptionid, 1 );
1112     my ( $nextissue ) = $sth->fetchrow_hashref;
1113     if( !$nextissue){
1114          $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid  = ? ORDER BY planneddate DESC LIMIT 1');
1115          $sth->execute( $subscriptionid );  
1116          $nextissue = $sth->fetchrow_hashref;       
1117     }
1118     if (!defined $nextissue->{planneddate}) {
1119         # or should this default to 1st Jan ???
1120         $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1121     }
1122     $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1123     return $nextissue;
1124
1125 }
1126
1127 =head2 ModNextExpected
1128
1129 ModNextExpected($subscriptionid,$date)
1130
1131 Update the planneddate for the current expected issue of the subscription.
1132 This will modify all future prediction results.  
1133
1134 C<$date> is a C4::Dates object.
1135
1136 returns 0
1137
1138 =cut
1139
1140 sub ModNextExpected($$) {
1141     my ( $subscriptionid, $date ) = @_;
1142     my $dbh = C4::Context->dbh;
1143
1144     #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1145     my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1146
1147     # Each subscription has only one 'expected' issue, with serial.status==1.
1148     $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1149     return 0;
1150
1151 }
1152
1153 =head2 ModSubscription
1154
1155 this function modifies a subscription. Put all new values on input args.
1156 returns the number of rows affected
1157
1158 =cut
1159
1160 sub ModSubscription {
1161     my ($auser,           $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $startdate,   $periodicity,   $firstacquidate,
1162         $dow,             $irregularity,    $numberpattern,     $numberlength,     $weeklength,    $monthlength, $add1,          $every1,
1163         $whenmorethan1,   $setto1,          $lastvalue1,        $innerloop1,       $add2,          $every2,      $whenmorethan2, $setto2,
1164         $lastvalue2,      $innerloop2,      $add3,              $every3,           $whenmorethan3, $setto3,      $lastvalue3,    $innerloop3,
1165         $numberingmethod, $status,          $biblionumber,      $callnumber,       $notes,         $letter,      $hemisphere,    $manualhistory,
1166         $internalnotes,   $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,    $enddate,       $subscriptionid
1167     ) = @_;
1168
1169     #     warn $irregularity;
1170     my $dbh   = C4::Context->dbh;
1171     my $query = "UPDATE subscription
1172                     SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1173                         periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1174                         add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1175                         add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1176                         add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1177                         numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?, 
1178                                                 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1179                                                 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1180                                                 ,enddate=?
1181                     WHERE subscriptionid = ?";
1182
1183     #warn "query :".$query;
1184     my $sth = $dbh->prepare($query);
1185     $sth->execute(
1186         $auser,           $branchcode,     $aqbooksellerid, $cost,
1187         $aqbudgetid,      $startdate,      $periodicity,    $firstacquidate,
1188         $dow,             "$irregularity", $numberpattern,  $numberlength,
1189         $weeklength,      $monthlength,    $add1,           $every1,
1190         $whenmorethan1,   $setto1,         $lastvalue1,     $innerloop1,
1191         $add2,            $every2,         $whenmorethan2,  $setto2,
1192         $lastvalue2,      $innerloop2,     $add3,           $every3,
1193         $whenmorethan3,   $setto3,         $lastvalue3,     $innerloop3,
1194         $numberingmethod, $status,         $biblionumber,   $callnumber,
1195         $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1196         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1197         $graceperiod,   $location,        $enddate,           $subscriptionid
1198     );
1199     my $rows = $sth->rows;
1200
1201     logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1202     return $rows;
1203 }
1204
1205 =head2 NewSubscription
1206
1207 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1208     $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1209     $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1210     $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1211     $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1212     $numberingmethod, $status, $notes, $serialsadditems,
1213     $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1214
1215 Create a new subscription with value given on input args.
1216
1217 return :
1218 the id of this new subscription
1219
1220 =cut
1221
1222 sub NewSubscription {
1223     my ($auser,         $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $biblionumber, $startdate,       $periodicity,
1224         $dow,           $numberlength,    $weeklength,        $monthlength,      $add1,          $every1,       $whenmorethan1,   $setto1,
1225         $lastvalue1,    $innerloop1,      $add2,              $every2,           $whenmorethan2, $setto2,       $lastvalue2,      $innerloop2,
1226         $add3,          $every3,          $whenmorethan3,     $setto3,           $lastvalue3,    $innerloop3,   $numberingmethod, $status,
1227         $notes,         $letter,          $firstacquidate,    $irregularity,     $numberpattern, $callnumber,   $hemisphere,      $manualhistory,
1228         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,     $enddate
1229     ) = @_;
1230     my $dbh = C4::Context->dbh;
1231
1232     #save subscription (insert into database)
1233     my $query = qq|
1234         INSERT INTO subscription
1235             (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1236             startdate,periodicity,dow,numberlength,weeklength,monthlength,
1237             add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1238             add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1239             add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1240             numberingmethod, status, notes, letter,firstacquidate,irregularity,
1241             numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1242             staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1243         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1244         |;
1245     my $sth = $dbh->prepare($query);
1246     $sth->execute(
1247         $auser,         $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $biblionumber, $startdate,       $periodicity,
1248         $dow,           $numberlength,    $weeklength,        $monthlength,      $add1,          $every1,       $whenmorethan1,   $setto1,
1249         $lastvalue1,    $innerloop1,      $add2,              $every2,           $whenmorethan2, $setto2,       $lastvalue2,      $innerloop2,
1250         $add3,          $every3,          $whenmorethan3,     $setto3,           $lastvalue3,    $innerloop3,   $numberingmethod, "$status",
1251         $notes,         $letter,          $firstacquidate,    $irregularity,     $numberpattern, $callnumber,   $hemisphere,      $manualhistory,
1252         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,     $enddate
1253     );
1254
1255     #then create the 1st waited number
1256     my $subscriptionid = $dbh->{'mysql_insertid'};
1257     $query = qq(
1258         INSERT INTO subscriptionhistory
1259             (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
1260         VALUES (?,?,?,?,?)
1261         );
1262     $sth = $dbh->prepare($query);
1263     $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1264
1265     # reread subscription to get a hash (for calculation of the 1st issue number)
1266     $query = qq(
1267         SELECT *
1268         FROM   subscription
1269         WHERE  subscriptionid = ?
1270     );
1271     $sth = $dbh->prepare($query);
1272     $sth->execute($subscriptionid);
1273     my $val = $sth->fetchrow_hashref;
1274
1275     # calculate issue number
1276     my $serialseq = GetSeq($val);
1277     $query = qq|
1278         INSERT INTO serial
1279             (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1280         VALUES (?,?,?,?,?,?)
1281     |;
1282     $sth = $dbh->prepare($query);
1283     $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1284
1285     logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1286
1287     #set serial flag on biblio if not already set.
1288     my ( $null, ($bib) ) = GetBiblio($biblionumber);
1289     if ( !$bib->{'serial'} ) {
1290         my $record = GetMarcBiblio($biblionumber);
1291         my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1292         if ($tag) {
1293             eval { $record->field($tag)->update( $subf => 1 ); };
1294         }
1295         ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1296     }
1297     return $subscriptionid;
1298 }
1299
1300 =head2 ReNewSubscription
1301
1302 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1303
1304 this function renew a subscription with values given on input args.
1305
1306 =cut
1307
1308 sub ReNewSubscription {
1309     my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1310     my $dbh          = C4::Context->dbh;
1311     my $subscription = GetSubscription($subscriptionid);
1312     my $query        = qq|
1313          SELECT *
1314          FROM   biblio 
1315          LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1316          WHERE    biblio.biblionumber=?
1317      |;
1318     my $sth = $dbh->prepare($query);
1319     $sth->execute( $subscription->{biblionumber} );
1320     my $biblio = $sth->fetchrow_hashref;
1321
1322     if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1323
1324         NewSuggestion(
1325             {   'suggestedby'   => $user,
1326                 'title'         => $subscription->{bibliotitle},
1327                 'author'        => $biblio->{author},
1328                 'publishercode' => $biblio->{publishercode},
1329                 'note'          => $biblio->{note},
1330                 'biblionumber'  => $subscription->{biblionumber}
1331             }
1332         );
1333     }
1334
1335     # renew subscription
1336     $query = qq|
1337         UPDATE subscription
1338         SET    startdate=?,numberlength=?,weeklength=?,monthlength=?
1339         WHERE  subscriptionid=?
1340     |;
1341     $sth = $dbh->prepare($query);
1342     $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1343     my $enddate = GetExpirationDate($subscriptionid);
1344         $debug && warn "enddate :$enddate";
1345     $query = qq|
1346         UPDATE subscription
1347         SET    enddate=?
1348         WHERE  subscriptionid=?
1349     |;
1350     $sth = $dbh->prepare($query);
1351     $sth->execute( $enddate, $subscriptionid );
1352     $query = qq|
1353         UPDATE subscriptionhistory
1354         SET    histenddate=?
1355         WHERE  subscriptionid=?
1356     |;
1357     $sth = $dbh->prepare($query);
1358     $sth->execute( $enddate, $subscriptionid );
1359
1360     logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1361     return;
1362 }
1363
1364 =head2 NewIssue
1365
1366 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate,  $notes)
1367
1368 Create a new issue stored on the database.
1369 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1370 returns the serial id
1371
1372 =cut
1373
1374 sub NewIssue {
1375     my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1376     ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1377
1378     my $dbh   = C4::Context->dbh;
1379     my $query = qq|
1380         INSERT INTO serial
1381             (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1382         VALUES (?,?,?,?,?,?,?)
1383     |;
1384     my $sth = $dbh->prepare($query);
1385     $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1386     my $serialid = $dbh->{'mysql_insertid'};
1387     $query = qq|
1388         SELECT missinglist,recievedlist
1389         FROM   subscriptionhistory
1390         WHERE  subscriptionid=?
1391     |;
1392     $sth = $dbh->prepare($query);
1393     $sth->execute($subscriptionid);
1394     my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1395
1396     if ( $status == 2 ) {
1397       ### TODO Add a feature that improves recognition and description.
1398       ### As such count (serialseq) i.e. : N18,2(N19),N20
1399       ### Would use substr and index But be careful to previous presence of ()
1400         $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1401     }
1402     if ( $status == 4 ) {
1403         $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1404     }
1405     $query = qq|
1406         UPDATE subscriptionhistory
1407         SET    recievedlist=?, missinglist=?
1408         WHERE  subscriptionid=?
1409     |;
1410     $sth = $dbh->prepare($query);
1411     $recievedlist =~ s/^; //;
1412     $missinglist  =~ s/^; //;
1413     $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1414     return $serialid;
1415 }
1416
1417 =head2 ItemizeSerials
1418
1419 ItemizeSerials($serialid, $info);
1420 $info is a hashref containing  barcode branch, itemcallnumber, status, location
1421 $serialid the serialid
1422 return :
1423 1 if the itemize is a succes.
1424 0 and @error otherwise. @error containts the list of errors found.
1425
1426 =cut
1427
1428 sub ItemizeSerials {
1429     my ( $serialid, $info ) = @_;
1430     my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1431
1432     my $dbh   = C4::Context->dbh;
1433     my $query = qq|
1434         SELECT *
1435         FROM   serial
1436         WHERE  serialid=?
1437     |;
1438     my $sth = $dbh->prepare($query);
1439     $sth->execute($serialid);
1440     my $data = $sth->fetchrow_hashref;
1441     if ( C4::Context->preference("RoutingSerials") ) {
1442
1443         # check for existing biblioitem relating to serial issue
1444         my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1445         my $bibitemno = 0;
1446         for ( my $i = 0 ; $i < $count ; $i++ ) {
1447             if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1448                 $bibitemno = $results[$i]->{'biblioitemnumber'};
1449                 last;
1450             }
1451         }
1452         if ( $bibitemno == 0 ) {
1453             my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1454             $sth->execute( $data->{'biblionumber'} );
1455             my $biblioitem = $sth->fetchrow_hashref;
1456             $biblioitem->{'volumedate'}  = $data->{planneddate};
1457             $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1458             $biblioitem->{'dewey'}       = $info->{itemcallnumber};
1459         }
1460     }
1461
1462     my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1463     if ( $info->{barcode} ) {
1464         my @errors;
1465         my $exists = itemdata( $info->{'barcode'} );
1466         push @errors, "barcode_not_unique" if ($exists);
1467         unless ($exists) {
1468             my $marcrecord = MARC::Record->new();
1469             my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1470             my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1471             $marcrecord->insert_fields_ordered($newField);
1472             if ( $info->{branch} ) {
1473                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1474
1475                 #warn "items.homebranch : $tag , $subfield";
1476                 if ( $marcrecord->field($tag) ) {
1477                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1478                 } else {
1479                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1480                     $marcrecord->insert_fields_ordered($newField);
1481                 }
1482                 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1483
1484                 #warn "items.holdingbranch : $tag , $subfield";
1485                 if ( $marcrecord->field($tag) ) {
1486                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1487                 } else {
1488                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1489                     $marcrecord->insert_fields_ordered($newField);
1490                 }
1491             }
1492             if ( $info->{itemcallnumber} ) {
1493                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1494
1495                 if ( $marcrecord->field($tag) ) {
1496                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1497                 } else {
1498                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1499                     $marcrecord->insert_fields_ordered($newField);
1500                 }
1501             }
1502             if ( $info->{notes} ) {
1503                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1504
1505                 if ( $marcrecord->field($tag) ) {
1506                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1507                 } else {
1508                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1509                     $marcrecord->insert_fields_ordered($newField);
1510                 }
1511             }
1512             if ( $info->{location} ) {
1513                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1514
1515                 if ( $marcrecord->field($tag) ) {
1516                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1517                 } else {
1518                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1519                     $marcrecord->insert_fields_ordered($newField);
1520                 }
1521             }
1522             if ( $info->{status} ) {
1523                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1524
1525                 if ( $marcrecord->field($tag) ) {
1526                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1527                 } else {
1528                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1529                     $marcrecord->insert_fields_ordered($newField);
1530                 }
1531             }
1532             if ( C4::Context->preference("RoutingSerials") ) {
1533                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1534                 if ( $marcrecord->field($tag) ) {
1535                     $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1536                 } else {
1537                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1538                     $marcrecord->insert_fields_ordered($newField);
1539                 }
1540             }
1541             AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1542             return 1;
1543         }
1544         return ( 0, @errors );
1545     }
1546 }
1547
1548 =head2 HasSubscriptionStrictlyExpired
1549
1550 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1551
1552 the subscription has stricly expired when today > the end subscription date 
1553
1554 return :
1555 1 if true, 0 if false, -1 if the expiration date is not set.
1556
1557 =cut
1558
1559 sub HasSubscriptionStrictlyExpired {
1560
1561     # Getting end of subscription date
1562     my ($subscriptionid) = @_;
1563     my $dbh              = C4::Context->dbh;
1564     my $subscription     = GetSubscription($subscriptionid);
1565     my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1566
1567     # If the expiration date is set
1568     if ( $expirationdate != 0 ) {
1569         my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1570
1571         # Getting today's date
1572         my ( $nowyear, $nowmonth, $nowday ) = Today();
1573
1574         # if today's date > expiration date, then the subscription has stricly expired
1575         if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1576             return 1;
1577         } else {
1578             return 0;
1579         }
1580     } else {
1581
1582         # There are some cases where the expiration date is not set
1583         # As we can't determine if the subscription has expired on a date-basis,
1584         # we return -1;
1585         return -1;
1586     }
1587 }
1588
1589 =head2 HasSubscriptionExpired
1590
1591 $has_expired = HasSubscriptionExpired($subscriptionid)
1592
1593 the subscription has expired when the next issue to arrive is out of subscription limit.
1594
1595 return :
1596 0 if the subscription has not expired
1597 1 if the subscription has expired
1598 2 if has subscription does not have a valid expiration date set
1599
1600 =cut
1601
1602 sub HasSubscriptionExpired {
1603     my ($subscriptionid) = @_;
1604     my $dbh              = C4::Context->dbh;
1605     my $subscription     = GetSubscription($subscriptionid);
1606     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1607         my $expirationdate = $subscription->{enddate};
1608         if (!defined $expirationdate) {
1609             $expirationdate = q{};
1610         }
1611         my $query          = qq|
1612             SELECT max(planneddate)
1613             FROM   serial
1614             WHERE  subscriptionid=?
1615       |;
1616         my $sth = $dbh->prepare($query);
1617         $sth->execute($subscriptionid);
1618         my ($res) = $sth->fetchrow;
1619         return 0 unless $res;
1620         my @res                   = split( /-/, $res );
1621         my @endofsubscriptiondate = split( /-/, $expirationdate );
1622         return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1623         return 1
1624           if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1625             || ( !$res ) );
1626         return 0;
1627     } else {
1628         if ( $subscription->{'numberlength'} ) {
1629             my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1630             return 1 if ( $countreceived > $subscription->{'numberlength'} );
1631             return 0;
1632         } else {
1633             return 0;
1634         }
1635     }
1636     return 0;    # Notice that you'll never get here.
1637 }
1638
1639 =head2 SetDistributedto
1640
1641 SetDistributedto($distributedto,$subscriptionid);
1642 This function update the value of distributedto for a subscription given on input arg.
1643
1644 =cut
1645
1646 sub SetDistributedto {
1647     my ( $distributedto, $subscriptionid ) = @_;
1648     my $dbh   = C4::Context->dbh;
1649     my $query = qq|
1650         UPDATE subscription
1651         SET    distributedto=?
1652         WHERE  subscriptionid=?
1653     |;
1654     my $sth = $dbh->prepare($query);
1655     $sth->execute( $distributedto, $subscriptionid );
1656     return;
1657 }
1658
1659 =head2 DelSubscription
1660
1661 DelSubscription($subscriptionid)
1662 this function deletes subscription which has $subscriptionid as id.
1663
1664 =cut
1665
1666 sub DelSubscription {
1667     my ($subscriptionid) = @_;
1668     my $dbh = C4::Context->dbh;
1669     $subscriptionid = $dbh->quote($subscriptionid);
1670     $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1671     $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1672     $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1673
1674     logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1675 }
1676
1677 =head2 DelIssue
1678
1679 DelIssue($serialseq,$subscriptionid)
1680 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1681
1682 returns the number of rows affected
1683
1684 =cut
1685
1686 sub DelIssue {
1687     my ($dataissue) = @_;
1688     my $dbh = C4::Context->dbh;
1689     ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1690
1691     my $query = qq|
1692         DELETE FROM serial
1693         WHERE       serialid= ?
1694         AND         subscriptionid= ?
1695     |;
1696     my $mainsth = $dbh->prepare($query);
1697     $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1698
1699     #Delete element from subscription history
1700     $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1701     my $sth = $dbh->prepare($query);
1702     $sth->execute( $dataissue->{'subscriptionid'} );
1703     my $val = $sth->fetchrow_hashref;
1704     unless ( $val->{manualhistory} ) {
1705         my $query = qq|
1706           SELECT * FROM subscriptionhistory
1707           WHERE       subscriptionid= ?
1708       |;
1709         my $sth = $dbh->prepare($query);
1710         $sth->execute( $dataissue->{'subscriptionid'} );
1711         my $data      = $sth->fetchrow_hashref;
1712         my $serialseq = $dataissue->{'serialseq'};
1713         $data->{'missinglist'}  =~ s/\b$serialseq\b//;
1714         $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1715         my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1716         $sth = $dbh->prepare($strsth);
1717         $sth->execute( $dataissue->{'subscriptionid'} );
1718     }
1719
1720     return $mainsth->rows;
1721 }
1722
1723 =head2 GetLateOrMissingIssues
1724
1725 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1726
1727 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1728
1729 return :
1730 the issuelist as an array of hash refs. Each element of this array contains 
1731 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1732
1733 =cut
1734
1735 sub GetLateOrMissingIssues {
1736     my ( $supplierid, $serialid, $order ) = @_;
1737     my $dbh = C4::Context->dbh;
1738     my $sth;
1739     my $byserial = '';
1740     if ($serialid) {
1741         $byserial = "and serialid = " . $serialid;
1742     }
1743     if ($order) {
1744         $order .= ", title";
1745     } else {
1746         $order = "title";
1747     }
1748     if ($supplierid) {
1749         $sth = $dbh->prepare(
1750             "SELECT
1751                 serialid,      aqbooksellerid,        name,
1752                 biblio.title,  planneddate,           serialseq,
1753                 serial.status, serial.subscriptionid, claimdate
1754             FROM      serial 
1755                 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
1756                 LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
1757                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1758                 WHERE subscription.subscriptionid = serial.subscriptionid 
1759                 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1760                 AND subscription.aqbooksellerid=$supplierid
1761                 $byserial
1762                 ORDER BY $order"
1763         );
1764     } else {
1765         $sth = $dbh->prepare(
1766             "SELECT 
1767             serialid,      aqbooksellerid,         name,
1768             biblio.title,  planneddate,           serialseq,
1769             serial.status, serial.subscriptionid, claimdate
1770             FROM serial 
1771                 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid 
1772                 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1773                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1774                 WHERE subscription.subscriptionid = serial.subscriptionid 
1775                         AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1776                 $byserial
1777                 ORDER BY $order"
1778         );
1779     }
1780     $sth->execute;
1781     my @issuelist;
1782     while ( my $line = $sth->fetchrow_hashref ) {
1783
1784         if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1785             $line->{planneddate} = format_date( $line->{planneddate} );
1786         }
1787         if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1788             $line->{claimdate}   = format_date( $line->{claimdate} );
1789         }
1790         $line->{"status".$line->{status}}   = 1;
1791         push @issuelist, $line;
1792     }
1793     return @issuelist;
1794 }
1795
1796 =head2 removeMissingIssue
1797
1798 removeMissingIssue($subscriptionid)
1799
1800 this function removes an issue from being part of the missing string in 
1801 subscriptionlist.missinglist column
1802
1803 called when a missing issue is found from the serials-recieve.pl file
1804
1805 =cut
1806
1807 sub removeMissingIssue {
1808     my ( $sequence, $subscriptionid ) = @_;
1809     my $dbh = C4::Context->dbh;
1810     my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1811     $sth->execute($subscriptionid);
1812     my $data              = $sth->fetchrow_hashref;
1813     my $missinglist       = $data->{'missinglist'};
1814     my $missinglistbefore = $missinglist;
1815
1816     # warn $missinglist." before";
1817     $missinglist =~ s/($sequence)//;
1818
1819     # warn $missinglist." after";
1820     if ( $missinglist ne $missinglistbefore ) {
1821         $missinglist =~ s/\|\s\|/\|/g;
1822         $missinglist =~ s/^\| //g;
1823         $missinglist =~ s/\|$//g;
1824         my $sth2 = $dbh->prepare(
1825             "UPDATE subscriptionhistory
1826                     SET missinglist = ?
1827                     WHERE subscriptionid = ?"
1828         );
1829         $sth2->execute( $missinglist, $subscriptionid );
1830     }
1831     return;
1832 }
1833
1834 =head2 updateClaim
1835
1836 &updateClaim($serialid)
1837
1838 this function updates the time when a claim is issued for late/missing items
1839
1840 called from claims.pl file
1841
1842 =cut
1843
1844 sub updateClaim {
1845     my ($serialid) = @_;
1846     my $dbh        = C4::Context->dbh;
1847     my $sth        = $dbh->prepare(
1848         "UPDATE serial SET claimdate = now()
1849                 WHERE serialid = ?
1850         "
1851     );
1852     $sth->execute($serialid);
1853     return;
1854 }
1855
1856 =head2 getsupplierbyserialid
1857
1858 $result = getsupplierbyserialid($serialid)
1859
1860 this function is used to find the supplier id given a serial id
1861
1862 return :
1863 hashref containing serialid, subscriptionid, and aqbooksellerid
1864
1865 =cut
1866
1867 sub getsupplierbyserialid {
1868     my ($serialid) = @_;
1869     my $dbh        = C4::Context->dbh;
1870     my $sth        = $dbh->prepare(
1871         "SELECT serialid, serial.subscriptionid, aqbooksellerid
1872          FROM serial 
1873             LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1874             WHERE serialid = ?
1875         "
1876     );
1877     $sth->execute($serialid);
1878     my $line   = $sth->fetchrow_hashref;
1879     my $result = $line->{'aqbooksellerid'};
1880     return $result;
1881 }
1882
1883 =head2 check_routing
1884
1885 $result = &check_routing($subscriptionid)
1886
1887 this function checks to see if a serial has a routing list and returns the count of routingid
1888 used to show either an 'add' or 'edit' link
1889
1890 =cut
1891
1892 sub check_routing {
1893     my ($subscriptionid) = @_;
1894     my $dbh              = C4::Context->dbh;
1895     my $sth              = $dbh->prepare(
1896         "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist 
1897                               ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1898                               WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1899                               "
1900     );
1901     $sth->execute($subscriptionid);
1902     my $line   = $sth->fetchrow_hashref;
1903     my $result = $line->{'routingids'};
1904     return $result;
1905 }
1906
1907 =head2 addroutingmember
1908
1909 addroutingmember($borrowernumber,$subscriptionid)
1910
1911 this function takes a borrowernumber and subscriptionid and adds the member to the
1912 routing list for that serial subscription and gives them a rank on the list
1913 of either 1 or highest current rank + 1
1914
1915 =cut
1916
1917 sub addroutingmember {
1918     my ( $borrowernumber, $subscriptionid ) = @_;
1919     my $rank;
1920     my $dbh = C4::Context->dbh;
1921     my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1922     $sth->execute($subscriptionid);
1923     while ( my $line = $sth->fetchrow_hashref ) {
1924         if ( $line->{'rank'} > 0 ) {
1925             $rank = $line->{'rank'} + 1;
1926         } else {
1927             $rank = 1;
1928         }
1929     }
1930     $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1931     $sth->execute( $subscriptionid, $borrowernumber, $rank );
1932 }
1933
1934 =head2 reorder_members
1935
1936 reorder_members($subscriptionid,$routingid,$rank)
1937
1938 this function is used to reorder the routing list
1939
1940 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1941 - it gets all members on list puts their routingid's into an array
1942 - removes the one in the array that is $routingid
1943 - then reinjects $routingid at point indicated by $rank
1944 - then update the database with the routingids in the new order
1945
1946 =cut
1947
1948 sub reorder_members {
1949     my ( $subscriptionid, $routingid, $rank ) = @_;
1950     my $dbh = C4::Context->dbh;
1951     my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1952     $sth->execute($subscriptionid);
1953     my @result;
1954     while ( my $line = $sth->fetchrow_hashref ) {
1955         push( @result, $line->{'routingid'} );
1956     }
1957
1958     # To find the matching index
1959     my $i;
1960     my $key = -1;    # to allow for 0 being a valid response
1961     for ( $i = 0 ; $i < @result ; $i++ ) {
1962         if ( $routingid == $result[$i] ) {
1963             $key = $i;    # save the index
1964             last;
1965         }
1966     }
1967
1968     # if index exists in array then move it to new position
1969     if ( $key > -1 && $rank > 0 ) {
1970         my $new_rank = $rank - 1;                       # $new_rank is what you want the new index to be in the array
1971         my $moving_item = splice( @result, $key, 1 );
1972         splice( @result, $new_rank, 0, $moving_item );
1973     }
1974     for ( my $j = 0 ; $j < @result ; $j++ ) {
1975         my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1976         $sth->execute;
1977     }
1978     return;
1979 }
1980
1981 =head2 delroutingmember
1982
1983 delroutingmember($routingid,$subscriptionid)
1984
1985 this function either deletes one member from routing list if $routingid exists otherwise
1986 deletes all members from the routing list
1987
1988 =cut
1989
1990 sub delroutingmember {
1991
1992     # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
1993     my ( $routingid, $subscriptionid ) = @_;
1994     my $dbh = C4::Context->dbh;
1995     if ($routingid) {
1996         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
1997         $sth->execute($routingid);
1998         reorder_members( $subscriptionid, $routingid );
1999     } else {
2000         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2001         $sth->execute($subscriptionid);
2002     }
2003     return;
2004 }
2005
2006 =head2 getroutinglist
2007
2008 ($count,@routinglist) = getroutinglist($subscriptionid)
2009
2010 this gets the info from the subscriptionroutinglist for $subscriptionid
2011
2012 return :
2013 a count of the number of members on routinglist
2014 the routinglist as an array. Each element of the array contains a hash_ref containing
2015 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2016
2017 =cut
2018
2019 sub getroutinglist {
2020     my ($subscriptionid) = @_;
2021     my $dbh              = C4::Context->dbh;
2022     my $sth              = $dbh->prepare(
2023         "SELECT routingid, borrowernumber, ranking, biblionumber 
2024             FROM subscription 
2025             JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2026             WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2027                               "
2028     );
2029     $sth->execute($subscriptionid);
2030     my @routinglist;
2031     my $count = 0;
2032     while ( my $line = $sth->fetchrow_hashref ) {
2033         $count++;
2034         push( @routinglist, $line );
2035     }
2036     return ( $count, @routinglist );
2037 }
2038
2039 =head2 countissuesfrom
2040
2041 $result = countissuesfrom($subscriptionid,$startdate)
2042
2043 Returns a count of serial rows matching the given subsctiptionid
2044 with published date greater than startdate
2045
2046 =cut
2047
2048 sub countissuesfrom {
2049     my ( $subscriptionid, $startdate ) = @_;
2050     my $dbh   = C4::Context->dbh;
2051     my $query = qq|
2052             SELECT count(*)
2053             FROM   serial
2054             WHERE  subscriptionid=?
2055             AND serial.publisheddate>?
2056         |;
2057     my $sth = $dbh->prepare($query);
2058     $sth->execute( $subscriptionid, $startdate );
2059     my ($countreceived) = $sth->fetchrow;
2060     return $countreceived;
2061 }
2062
2063 =head2 CountIssues
2064
2065 $result = CountIssues($subscriptionid)
2066
2067 Returns a count of serial rows matching the given subsctiptionid
2068
2069 =cut
2070
2071 sub CountIssues {
2072     my ($subscriptionid) = @_;
2073     my $dbh              = C4::Context->dbh;
2074     my $query            = qq|
2075             SELECT count(*)
2076             FROM   serial
2077             WHERE  subscriptionid=?
2078         |;
2079     my $sth = $dbh->prepare($query);
2080     $sth->execute($subscriptionid);
2081     my ($countreceived) = $sth->fetchrow;
2082     return $countreceived;
2083 }
2084
2085 =head2 HasItems
2086
2087 $result = HasItems($subscriptionid)
2088
2089 returns a count of items from serial matching the subscriptionid
2090
2091 =cut
2092
2093 sub HasItems {
2094     my ($subscriptionid) = @_;
2095     my $dbh              = C4::Context->dbh;
2096     my $query = q|
2097             SELECT COUNT(serialitems.itemnumber)
2098             FROM   serial 
2099                         LEFT JOIN serialitems USING(serialid)
2100             WHERE  subscriptionid=? AND serialitems.serialid IS NOT NULL
2101         |;
2102     my $sth=$dbh->prepare($query);
2103     $sth->execute($subscriptionid);
2104     my ($countitems)=$sth->fetchrow_array();
2105     return $countitems;  
2106 }
2107
2108 =head2 abouttoexpire
2109
2110 $result = abouttoexpire($subscriptionid)
2111
2112 this function alerts you to the penultimate issue for a serial subscription
2113
2114 returns 1 - if this is the penultimate issue
2115 returns 0 - if not
2116
2117 =cut
2118
2119 sub abouttoexpire {
2120     my ($subscriptionid) = @_;
2121     my $dbh              = C4::Context->dbh;
2122     my $subscription     = GetSubscription($subscriptionid);
2123     my $per = $subscription->{'periodicity'};
2124     if ($per && $per % 16 > 0){
2125         my $expirationdate   = GetExpirationDate($subscriptionid);
2126         my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2127         my @res;
2128         if (defined $res) {
2129             @res=split (/-/,$res);
2130             @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2131         } else { # default an undefined value
2132             @res=Date::Calc::Today;
2133         }
2134         my @endofsubscriptiondate=split(/-/,$expirationdate);
2135         my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 0, 0, 0);
2136         my @datebeforeend;
2137         @datebeforeend = Add_Delta_Days(  $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2138             - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2139         return 1 if ( @res &&
2140             (@datebeforeend &&
2141                 Delta_Days($res[0],$res[1],$res[2],
2142                     $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2143             (@endofsubscriptiondate &&
2144                 Delta_Days($res[0],$res[1],$res[2],
2145                     $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2146         return 0;
2147     } elsif ($subscription->{numberlength}>0) {
2148         return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2149     }
2150     return 0;
2151 }
2152
2153 sub in_array {    # used in next sub down
2154     my ( $val, @elements ) = @_;
2155     foreach my $elem (@elements) {
2156         if ( $val == $elem ) {
2157             return 1;
2158         }
2159     }
2160     return 0;
2161 }
2162
2163 =head2 GetNextDate
2164
2165 $resultdate = GetNextDate($planneddate,$subscription)
2166
2167 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2168 exists an irregularity
2169 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be 
2170 skipped then the returned date will be 2007-05-10
2171
2172 return :
2173 $resultdate - then next date in the sequence
2174
2175 Return 0 if periodicity==0
2176
2177 =cut
2178
2179 sub GetNextDate(@) {
2180     my ( $planneddate, $subscription ) = @_;
2181     my @irreg = split( /\,/, $subscription->{irregularity} );
2182
2183     #date supposed to be in ISO.
2184
2185     my ( $year, $month, $day ) = split( /-/, $planneddate );
2186     $month = 1 unless ($month);
2187     $day   = 1 unless ($day);
2188     my @resultdate;
2189
2190     #       warn "DOW $dayofweek";
2191     if ( $subscription->{periodicity} % 16 == 0 ) {    # 'without regularity' || 'irregular'
2192         return 0;
2193     }
2194
2195     #   daily : n / week
2196     #   Since we're interpreting irregularity here as which days of the week to skip an issue,
2197     #   renaming this pattern from 1/day to " n / week ".
2198     if ( $subscription->{periodicity} == 1 ) {
2199         my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2200         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2201         else {
2202             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2203                 $dayofweek = 0 if ( $dayofweek == 7 );
2204                 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2205                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2206                     $dayofweek++;
2207                 }
2208             }
2209             @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2210         }
2211     }
2212
2213     #   1  week
2214     if ( $subscription->{periodicity} == 2 ) {
2215         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2216         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2217         else {
2218             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2219
2220                 #FIXME: if two consecutive irreg, do we only skip one?
2221                 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2222                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2223                     $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2224                 }
2225             }
2226             @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2227         }
2228     }
2229
2230     #   1 / 2 weeks
2231     if ( $subscription->{periodicity} == 3 ) {
2232         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2233         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2234         else {
2235             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2236                 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2237                     ### BUGFIX was previously +1 ^
2238                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2239                     $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2240                 }
2241             }
2242             @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2243         }
2244     }
2245
2246     #   1 / 3 weeks
2247     if ( $subscription->{periodicity} == 4 ) {
2248         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2249         if ($@) { warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2250         else {
2251             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2252                 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2253                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2254                     $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2255                 }
2256             }
2257             @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2258         }
2259     }
2260     my $tmpmonth = $month;
2261     if ( $year && $month && $day ) {
2262         if ( $subscription->{periodicity} == 5 ) {
2263             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2264                 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2265                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2266                     $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2267                 }
2268             }
2269             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2270         }
2271         if ( $subscription->{periodicity} == 6 ) {
2272             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2273                 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2274                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2275                     $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2276                 }
2277             }
2278             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2279         }
2280         if ( $subscription->{periodicity} == 7 ) {
2281             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2282                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2283                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2284                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2285                 }
2286             }
2287             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2288         }
2289         if ( $subscription->{periodicity} == 8 ) {
2290             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2291                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2292                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2293                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2294                 }
2295             }
2296             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2297         }
2298         if ( $subscription->{periodicity} == 9 ) {
2299             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2300                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2301                     ### BUFIX Seems to need more Than One ?
2302                     ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2303                     $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2304                 }
2305             }
2306             @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2307         }
2308         if ( $subscription->{periodicity} == 10 ) {
2309             @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2310         }
2311         if ( $subscription->{periodicity} == 11 ) {
2312             @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2313         }
2314     }
2315     my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2316
2317     return "$resultdate";
2318 }
2319
2320 =head2 itemdata
2321
2322   $item = itemdata($barcode);
2323
2324 Looks up the item with the given barcode, and returns a
2325 reference-to-hash containing information about that item. The keys of
2326 the hash are the fields from the C<items> and C<biblioitems> tables in
2327 the Koha database.
2328
2329 =cut
2330
2331 #'
2332 sub itemdata {
2333     my ($barcode) = @_;
2334     my $dbh       = C4::Context->dbh;
2335     my $sth       = $dbh->prepare(
2336         "Select * from items LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber 
2337         WHERE barcode=?"
2338     );
2339     $sth->execute($barcode);
2340     my $data = $sth->fetchrow_hashref;
2341     $sth->finish;
2342     return ($data);
2343 }
2344
2345 1;
2346 __END__
2347
2348 =head1 AUTHOR
2349
2350 Koha Development Team <http://koha-community.org/>
2351
2352 =cut