Updating perlcriticrc to allow Modern::Perl to suffice instead of use warnings; and...
[koha.git] / C4 / Serials.pm
1 package C4::Serials;
2
3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2010 Biblibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 use warnings;
23 use C4::Dates qw(format_date format_date_in_iso);
24 use Date::Calc qw(:all);
25 use POSIX qw(strftime);
26 use C4::Suggestions;
27 use C4::Koha;
28 use C4::Biblio;
29 use C4::Branch;
30 use C4::Items;
31 use C4::Search;
32 use C4::Letters;
33 use C4::Log;    # logaction
34 use C4::Debug;
35
36 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
37
38 BEGIN {
39     $VERSION = 3.01;    # set version for version checking
40     require Exporter;
41     @ISA    = qw(Exporter);
42     @EXPORT = qw(
43       &NewSubscription    &ModSubscription    &DelSubscription    &GetSubscriptions
44       &GetSubscription    &CountSubscriptionFromBiblionumber      &GetSubscriptionsFromBiblionumber
45       &GetFullSubscriptionsFromBiblionumber   &GetFullSubscription &ModSubscriptionHistory
46       &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
47
48       &GetNextSeq         &NewIssue           &ItemizeSerials    &GetSerials
49       &GetLatestSerials   &ModSerialStatus    &GetNextDate       &GetSerials2
50       &ReNewSubscription  &GetLateIssues      &GetLateOrMissingIssues
51       &GetSerialInformation                   &AddItem2Serial
52       &PrepareSerialsData &GetNextExpected    &ModNextExpected
53
54       &UpdateClaimdateIssues
55       &GetSuppliersWithLateIssues             &getsupplierbyserialid
56       &GetDistributedTo   &SetDistributedTo
57       &getroutinglist     &delroutingmember   &addroutingmember
58       &reorder_members
59       &check_routing &updateClaim &removeMissingIssue
60       &CountIssues
61       HasItems
62
63     );
64 }
65
66 =head1 NAME
67
68 C4::Serials - Serials Module Functions
69
70 =head1 SYNOPSIS
71
72   use C4::Serials;
73
74 =head1 DESCRIPTION
75
76 Functions for handling subscriptions, claims routing etc.
77
78
79 =head1 SUBROUTINES
80
81 =head2 GetSuppliersWithLateIssues
82
83 $supplierlist = GetSuppliersWithLateIssues()
84
85 this function get all suppliers with late issues.
86
87 return :
88 an array_ref of suppliers each entry is a hash_ref containing id and name
89 the array is in name order
90
91 =cut
92
93 sub GetSuppliersWithLateIssues {
94     my $dbh   = C4::Context->dbh;
95     my $query = qq|
96         SELECT DISTINCT id, name
97     FROM            subscription
98     LEFT JOIN       serial ON serial.subscriptionid=subscription.subscriptionid
99     LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
100     WHERE id > 0 AND ((planneddate < now() AND serial.status=1) OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
101     return $dbh->selectall_arrayref($query, { Slice => {} });
102 }
103
104 =head2 GetLateIssues
105
106 @issuelist = GetLateIssues($supplierid)
107
108 this function selects late issues from the database
109
110 return :
111 the issuelist as an array. Each element of this array contains a hashi_ref containing
112 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
113
114 =cut
115
116 sub GetLateIssues {
117     my ($supplierid) = @_;
118     my $dbh = C4::Context->dbh;
119     my $sth;
120     if ($supplierid) {
121         my $query = qq|
122             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
123             FROM       subscription
124             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
125             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
126             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
127             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
128             AND        subscription.aqbooksellerid=?
129             ORDER BY   title
130         |;
131         $sth = $dbh->prepare($query);
132         $sth->execute($supplierid);
133     } else {
134         my $query = qq|
135             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
136             FROM       subscription
137             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
138             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
139             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
140             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
141             ORDER BY   title
142         |;
143         $sth = $dbh->prepare($query);
144         $sth->execute;
145     }
146     my @issuelist;
147     my $last_title;
148     my $odd   = 0;
149     while ( my $line = $sth->fetchrow_hashref ) {
150         $odd++ unless $line->{title} eq $last_title;
151         $line->{title} = "" if $line->{title} eq $last_title;
152         $last_title = $line->{title} if ( $line->{title} );
153         $line->{planneddate} = format_date( $line->{planneddate} );
154         push @issuelist, $line;
155     }
156     return @issuelist;
157 }
158
159 =head2 GetSubscriptionHistoryFromSubscriptionId
160
161 $sth = GetSubscriptionHistoryFromSubscriptionId()
162 this function prepares the SQL request and returns the statement handle
163 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
164
165 =cut
166
167 sub GetSubscriptionHistoryFromSubscriptionId() {
168     my $dbh   = C4::Context->dbh;
169     my $query = qq|
170         SELECT *
171         FROM   subscriptionhistory
172         WHERE  subscriptionid = ?
173     |;
174     return $dbh->prepare($query);
175 }
176
177 =head2 GetSerialStatusFromSerialId
178
179 $sth = GetSerialStatusFromSerialId();
180 this function returns a statement handle
181 After this function, don't forget to execute it by using $sth->execute($serialid)
182 return :
183 $sth = $dbh->prepare($query).
184
185 =cut
186
187 sub GetSerialStatusFromSerialId() {
188     my $dbh   = C4::Context->dbh;
189     my $query = qq|
190         SELECT status
191         FROM   serial
192         WHERE  serialid = ?
193     |;
194     return $dbh->prepare($query);
195 }
196
197 =head2 GetSerialInformation
198
199
200 $data = GetSerialInformation($serialid);
201 returns a hash_ref containing :
202   items : items marcrecord (can be an array)
203   serial table field
204   subscription table field
205   + information about subscription expiration
206
207 =cut
208
209 sub GetSerialInformation {
210     my ($serialid) = @_;
211     my $dbh        = C4::Context->dbh;
212     my $query      = qq|
213         SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
214     if (   C4::Context->preference('IndependantBranches')
215         && C4::Context->userenv
216         && C4::Context->userenv->{'flags'} != 1
217         && C4::Context->userenv->{'branch'} ) {
218         $query .= "
219       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
220     }
221     $query .= qq|             
222         FROM   serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
223         WHERE  serialid = ?
224     |;
225     my $rq = $dbh->prepare($query);
226     $rq->execute($serialid);
227     my $data = $rq->fetchrow_hashref;
228
229     # create item information if we have serialsadditems for this subscription
230     if ( $data->{'serialsadditems'} ) {
231         my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
232         $queryitem->execute($serialid);
233         my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
234         if ( scalar(@$itemnumbers) > 0 ) {
235             foreach my $itemnum (@$itemnumbers) {
236
237                 #It is ASSUMED that GetMarcItem ALWAYS WORK...
238                 #Maybe GetMarcItem should return values on failure
239                 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
240                 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
241                 $itemprocessed->{'itemnumber'}   = $itemnum->[0];
242                 $itemprocessed->{'itemid'}       = $itemnum->[0];
243                 $itemprocessed->{'serialid'}     = $serialid;
244                 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
245                 push @{ $data->{'items'} }, $itemprocessed;
246             }
247         } else {
248             my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
249             $itemprocessed->{'itemid'}       = "N$serialid";
250             $itemprocessed->{'serialid'}     = $serialid;
251             $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
252             $itemprocessed->{'countitems'}   = 0;
253             push @{ $data->{'items'} }, $itemprocessed;
254         }
255     }
256     $data->{ "status" . $data->{'serstatus'} } = 1;
257     $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
258     $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
259     return $data;
260 }
261
262 =head2 AddItem2Serial
263
264 $rows = AddItem2Serial($serialid,$itemnumber);
265 Adds an itemnumber to Serial record
266 returns the number of rows affected
267
268 =cut
269
270 sub AddItem2Serial {
271     my ( $serialid, $itemnumber ) = @_;
272     my $dbh = C4::Context->dbh;
273     my $rq  = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
274     $rq->execute( $serialid, $itemnumber );
275     return $rq->rows;
276 }
277
278 =head2 UpdateClaimdateIssues
279
280 UpdateClaimdateIssues($serialids,[$date]);
281
282 Update Claimdate for issues in @$serialids list with date $date
283 (Take Today if none)
284
285 =cut
286
287 sub UpdateClaimdateIssues {
288     my ( $serialids, $date ) = @_;
289     my $dbh = C4::Context->dbh;
290     $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
291     my $query = "
292         UPDATE serial SET claimdate = ?, status = 7
293         WHERE  serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
294     my $rq = $dbh->prepare($query);
295     $rq->execute($date, @$serialids);
296     return $rq->rows;
297 }
298
299 =head2 GetSubscription
300
301 $subs = GetSubscription($subscriptionid)
302 this function returns the subscription which has $subscriptionid as id.
303 return :
304 a hashref. This hash containts
305 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
306
307 =cut
308
309 sub GetSubscription {
310     my ($subscriptionid) = @_;
311     my $dbh              = C4::Context->dbh;
312     my $query            = qq(
313         SELECT  subscription.*,
314                 subscriptionhistory.*,
315                 aqbooksellers.name AS aqbooksellername,
316                 biblio.title AS bibliotitle,
317                 subscription.biblionumber as bibnum);
318     if (   C4::Context->preference('IndependantBranches')
319         && C4::Context->userenv
320         && C4::Context->userenv->{'flags'} != 1
321         && C4::Context->userenv->{'branch'} ) {
322         $query .= "
323       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
324     }
325     $query .= qq(             
326        FROM subscription
327        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
328        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
329        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
330        WHERE subscription.subscriptionid = ?
331     );
332
333     #     if (C4::Context->preference('IndependantBranches') &&
334     #         C4::Context->userenv &&
335     #         C4::Context->userenv->{'flags'} != 1){
336     # #       $debug and warn "flags: ".C4::Context->userenv->{'flags'};
337     #       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
338     #     }
339     $debug and warn "query : $query\nsubsid :$subscriptionid";
340     my $sth = $dbh->prepare($query);
341     $sth->execute($subscriptionid);
342     return $sth->fetchrow_hashref;
343 }
344
345 =head2 GetFullSubscription
346
347    $array_ref = GetFullSubscription($subscriptionid)
348    this function reads the serial table.
349
350 =cut
351
352 sub GetFullSubscription {
353     my ($subscriptionid) = @_;
354     my $dbh              = C4::Context->dbh;
355     my $query            = qq|
356   SELECT    serial.serialid,
357             serial.serialseq,
358             serial.planneddate, 
359             serial.publisheddate, 
360             serial.status, 
361             serial.notes as notes,
362             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
363             aqbooksellers.name as aqbooksellername,
364             biblio.title as bibliotitle,
365             subscription.branchcode AS branchcode,
366             subscription.subscriptionid AS subscriptionid |;
367     if (   C4::Context->preference('IndependantBranches')
368         && C4::Context->userenv
369         && C4::Context->userenv->{'flags'} != 1
370         && C4::Context->userenv->{'branch'} ) {
371         $query .= "
372       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
373     }
374     $query .= qq|
375   FROM      serial 
376   LEFT JOIN subscription ON 
377           (serial.subscriptionid=subscription.subscriptionid )
378   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
379   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
380   WHERE     serial.subscriptionid = ? 
381   ORDER BY year DESC,
382           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
383           serial.subscriptionid
384           |;
385     $debug and warn "GetFullSubscription query: $query";
386     my $sth = $dbh->prepare($query);
387     $sth->execute($subscriptionid);
388     return $sth->fetchall_arrayref( {} );
389 }
390
391 =head2 PrepareSerialsData
392
393    $array_ref = PrepareSerialsData($serialinfomation)
394    where serialinformation is a hashref array
395
396 =cut
397
398 sub PrepareSerialsData {
399     my ($lines) = @_;
400     my %tmpresults;
401     my $year;
402     my @res;
403     my $startdate;
404     my $aqbooksellername;
405     my $bibliotitle;
406     my @loopissues;
407     my $first;
408     my $previousnote = "";
409
410     foreach my $subs (@{$lines}) {
411         for my $datefield ( qw(publisheddate planneddate) ) {
412             # handle both undef and undef returned as 0000-00-00
413             if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
414                 $subs->{$datefield} = 'XXX';
415             }
416             else {
417                 $subs->{$datefield} = format_date( $subs->{$datefield}  );
418             }
419         }
420         $subs->{'branchname'} = GetBranchName( $subs->{'branchcode'} );
421         $subs->{ "status" . $subs->{'status'} } = 1;
422         $subs->{"checked"}                      = $subs->{'status'} =~ /1|3|4|7/;
423
424         if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
425             $year = $subs->{'year'};
426         } else {
427             $year = "manage";
428         }
429         if ( $tmpresults{$year} ) {
430             push @{ $tmpresults{$year}->{'serials'} }, $subs;
431         } else {
432             $tmpresults{$year} = {
433                 'year'             => $year,
434                 'aqbooksellername' => $subs->{'aqbooksellername'},
435                 'bibliotitle'      => $subs->{'bibliotitle'},
436                 'serials'          => [$subs],
437                 'first'            => $first,
438             };
439         }
440     }
441     foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
442         push @res, $tmpresults{$key};
443     }
444     return \@res;
445 }
446
447 =head2 GetSubscriptionsFromBiblionumber
448
449 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
450 this function get the subscription list. it reads the subscription table.
451 return :
452 reference to an array of subscriptions which have the biblionumber given on input arg.
453 each element of this array is a hashref containing
454 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
455
456 =cut
457
458 sub GetSubscriptionsFromBiblionumber {
459     my ($biblionumber) = @_;
460     my $dbh            = C4::Context->dbh;
461     my $query          = qq(
462         SELECT subscription.*,
463                branches.branchname,
464                subscriptionhistory.*,
465                aqbooksellers.name AS aqbooksellername,
466                biblio.title AS bibliotitle
467        FROM subscription
468        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
469        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
470        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
471        LEFT JOIN branches ON branches.branchcode=subscription.branchcode
472        WHERE subscription.biblionumber = ?
473     );
474     my $sth = $dbh->prepare($query);
475     $sth->execute($biblionumber);
476     my @res;
477     while ( my $subs = $sth->fetchrow_hashref ) {
478         $subs->{startdate}     = format_date( $subs->{startdate} );
479         $subs->{histstartdate} = format_date( $subs->{histstartdate} );
480         $subs->{histenddate}   = format_date( $subs->{histenddate} );
481         $subs->{opacnote}     =~ s/\n/\<br\/\>/g;
482         $subs->{missinglist}  =~ s/\n/\<br\/\>/g;
483         $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
484         $subs->{ "periodicity" . $subs->{periodicity} }     = 1;
485         $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
486         $subs->{ "status" . $subs->{'status'} }             = 1;
487         $subs->{'cannotedit'} =
488           (      C4::Context->preference('IndependantBranches')
489               && C4::Context->userenv
490               && C4::Context->userenv->{flags} % 2 != 1
491               && C4::Context->userenv->{branch}
492               && $subs->{branchcode}
493               && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
494
495         if ( $subs->{enddate} eq '0000-00-00' ) {
496             $subs->{enddate} = '';
497         } else {
498             $subs->{enddate} = format_date( $subs->{enddate} );
499         }
500         $subs->{'abouttoexpire'}       = abouttoexpire( $subs->{'subscriptionid'} );
501         $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
502         push @res, $subs;
503     }
504     return \@res;
505 }
506
507 =head2 GetFullSubscriptionsFromBiblionumber
508
509    $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
510    this function reads the serial table.
511
512 =cut
513
514 sub GetFullSubscriptionsFromBiblionumber {
515     my ($biblionumber) = @_;
516     my $dbh            = C4::Context->dbh;
517     my $query          = qq|
518   SELECT    serial.serialid,
519             serial.serialseq,
520             serial.planneddate, 
521             serial.publisheddate, 
522             serial.status, 
523             serial.notes as notes,
524             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
525             biblio.title as bibliotitle,
526             subscription.branchcode AS branchcode,
527             subscription.subscriptionid AS subscriptionid|;
528     if (   C4::Context->preference('IndependantBranches')
529         && C4::Context->userenv
530         && C4::Context->userenv->{'flags'} != 1
531         && C4::Context->userenv->{'branch'} ) {
532         $query .= "
533       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
534     }
535
536     $query .= qq|      
537   FROM      serial 
538   LEFT JOIN subscription ON 
539           (serial.subscriptionid=subscription.subscriptionid)
540   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
541   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
542   WHERE     subscription.biblionumber = ? 
543   ORDER BY year DESC,
544           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
545           serial.subscriptionid
546           |;
547     my $sth = $dbh->prepare($query);
548     $sth->execute($biblionumber);
549     return $sth->fetchall_arrayref( {} );
550 }
551
552 =head2 GetSubscriptions
553
554 @results = GetSubscriptions($title,$ISSN,$biblionumber);
555 this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
556 return:
557 a table of hashref. Each hash containt the subscription.
558
559 =cut
560
561 sub GetSubscriptions {
562     my ( $string, $issn, $biblionumber ) = @_;
563
564     #return unless $title or $ISSN or $biblionumber;
565     my $dbh = C4::Context->dbh;
566     my $sth;
567     my $sql = qq(
568             SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
569             FROM   subscription
570             LEFT JOIN subscriptionhistory USING(subscriptionid)
571             LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
572             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
573     );
574     my @bind_params;
575     my $sqlwhere;
576     if ($biblionumber) {
577         $sqlwhere = "   WHERE biblio.biblionumber=?";
578         push @bind_params, $biblionumber;
579     }
580     if ($string) {
581         my @sqlstrings;
582         my @strings_to_search;
583         @strings_to_search = map { "%$_%" } split( / /, $string );
584         foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
585             push @bind_params, @strings_to_search;
586             my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
587             $debug && warn "$tmpstring";
588             $tmpstring =~ s/^AND //;
589             push @sqlstrings, $tmpstring;
590         }
591         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
592     }
593     if ($issn) {
594         my @sqlstrings;
595         my @strings_to_search;
596         @strings_to_search = map { "%$_%" } split( / /, $issn );
597         foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
598             push @bind_params, @strings_to_search;
599             my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
600             $debug && warn "$tmpstring";
601             $tmpstring =~ s/^OR //;
602             push @sqlstrings, $tmpstring;
603         }
604         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
605     }
606     $sql .= "$sqlwhere ORDER BY title";
607     $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
608     $sth = $dbh->prepare($sql);
609     $sth->execute(@bind_params);
610     my @results;
611     my $previousbiblio = "";
612     my $odd           = 1;
613
614     while ( my $line = $sth->fetchrow_hashref ) {
615         $line->{'cannotedit'} =
616           (      C4::Context->preference('IndependantBranches')
617               && C4::Context->userenv
618               && C4::Context->userenv->{flags} % 2 != 1
619               && C4::Context->userenv->{branch}
620               && $line->{branchcode}
621               && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
622         push @results, $line;
623     }
624     return @results;
625 }
626
627 =head2 GetSerials
628
629 ($totalissues,@serials) = GetSerials($subscriptionid);
630 this function gets every serial not arrived for a given subscription
631 as well as the number of issues registered in the database (all types)
632 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
633
634 FIXME: We should return \@serials.
635
636 =cut
637
638 sub GetSerials {
639     my ( $subscriptionid, $count ) = @_;
640     my $dbh = C4::Context->dbh;
641
642     # status = 2 is "arrived"
643     my $counter = 0;
644     $count = 5 unless ($count);
645     my @serials;
646     my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
647                         FROM   serial
648                         WHERE  subscriptionid = ? AND status NOT IN (2,4,5) 
649                         ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
650     my $sth = $dbh->prepare($query);
651     $sth->execute($subscriptionid);
652
653     while ( my $line = $sth->fetchrow_hashref ) {
654         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
655         for my $datefield ( qw( planneddate publisheddate) ) {
656             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
657                 $line->{$datefield} = format_date( $line->{$datefield});
658             } else {
659                 $line->{$datefield} = q{};
660             }
661         }
662         push @serials, $line;
663     }
664
665     # OK, now add the last 5 issues arrives/missing
666     $query = "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
667        FROM     serial
668        WHERE    subscriptionid = ?
669        AND      (status in (2,4,5))
670        ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
671       ";
672     $sth = $dbh->prepare($query);
673     $sth->execute($subscriptionid);
674     while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
675         $counter++;
676         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
677         for my $datefield ( qw( planneddate publisheddate) ) {
678             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
679                 $line->{$datefield} = format_date( $line->{$datefield});
680             } else {
681                 $line->{$datefield} = q{};
682             }
683         }
684
685         push @serials, $line;
686     }
687
688     $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
689     $sth   = $dbh->prepare($query);
690     $sth->execute($subscriptionid);
691     my ($totalissues) = $sth->fetchrow;
692     return ( $totalissues, @serials );
693 }
694
695 =head2 GetSerials2
696
697 @serials = GetSerials2($subscriptionid,$status);
698 this function returns every serial waited for a given subscription
699 as well as the number of issues registered in the database (all types)
700 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
701
702 =cut
703
704 sub GetSerials2 {
705     my ( $subscription, $status ) = @_;
706     my $dbh   = C4::Context->dbh;
707     my $query = qq|
708                  SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
709                  FROM     serial 
710                  WHERE    subscriptionid=$subscription AND status IN ($status)
711                  ORDER BY publisheddate,serialid DESC
712                     |;
713     $debug and warn "GetSerials2 query: $query";
714     my $sth = $dbh->prepare($query);
715     $sth->execute;
716     my @serials;
717
718     while ( my $line = $sth->fetchrow_hashref ) {
719         $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
720         # Format dates for display
721         for my $datefield ( qw( planneddate publisheddate ) ) {
722             if ($line->{$datefield} =~m/^00/) {
723                 $line->{$datefield} = q{};
724             }
725             else {
726                 $line->{$datefield} = format_date( $line->{$datefield} );
727             }
728         }
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 $enddate = 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     my $subscriptionid = $dbh->{'mysql_insertid'};
1256     unless ($enddate){
1257        $enddate = GetExpirationDate($subscriptionid,$startdate);
1258         $query = q|
1259             UPDATE subscription
1260             SET    enddate=?
1261             WHERE  subscriptionid=?
1262         |;
1263         $sth = $dbh->prepare($query);
1264         $sth->execute( $enddate, $subscriptionid );
1265     }
1266     #then create the 1st waited number
1267     $query = qq(
1268         INSERT INTO subscriptionhistory
1269             (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
1270         VALUES (?,?,?,?,?)
1271         );
1272     $sth = $dbh->prepare($query);
1273     $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1274
1275     # reread subscription to get a hash (for calculation of the 1st issue number)
1276     $query = qq(
1277         SELECT *
1278         FROM   subscription
1279         WHERE  subscriptionid = ?
1280     );
1281     $sth = $dbh->prepare($query);
1282     $sth->execute($subscriptionid);
1283     my $val = $sth->fetchrow_hashref;
1284
1285     # calculate issue number
1286     my $serialseq = GetSeq($val);
1287     $query = qq|
1288         INSERT INTO serial
1289             (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1290         VALUES (?,?,?,?,?,?)
1291     |;
1292     $sth = $dbh->prepare($query);
1293     $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1294
1295     logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1296
1297     #set serial flag on biblio if not already set.
1298     my ( $null, ($bib) ) = GetBiblio($biblionumber);
1299     if ( !$bib->{'serial'} ) {
1300         my $record = GetMarcBiblio($biblionumber);
1301         my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1302         if ($tag) {
1303             eval { $record->field($tag)->update( $subf => 1 ); };
1304         }
1305         ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1306     }
1307     return $subscriptionid;
1308 }
1309
1310 =head2 ReNewSubscription
1311
1312 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1313
1314 this function renew a subscription with values given on input args.
1315
1316 =cut
1317
1318 sub ReNewSubscription {
1319     my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1320     my $dbh          = C4::Context->dbh;
1321     my $subscription = GetSubscription($subscriptionid);
1322     my $query        = qq|
1323          SELECT *
1324          FROM   biblio 
1325          LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1326          WHERE    biblio.biblionumber=?
1327      |;
1328     my $sth = $dbh->prepare($query);
1329     $sth->execute( $subscription->{biblionumber} );
1330     my $biblio = $sth->fetchrow_hashref;
1331
1332     if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1333
1334         NewSuggestion(
1335             {   'suggestedby'   => $user,
1336                 'title'         => $subscription->{bibliotitle},
1337                 'author'        => $biblio->{author},
1338                 'publishercode' => $biblio->{publishercode},
1339                 'note'          => $biblio->{note},
1340                 'biblionumber'  => $subscription->{biblionumber}
1341             }
1342         );
1343     }
1344
1345     # renew subscription
1346     $query = qq|
1347         UPDATE subscription
1348         SET    startdate=?,numberlength=?,weeklength=?,monthlength=?
1349         WHERE  subscriptionid=?
1350     |;
1351     $sth = $dbh->prepare($query);
1352     $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1353     my $enddate = GetExpirationDate($subscriptionid);
1354         $debug && warn "enddate :$enddate";
1355     $query = qq|
1356         UPDATE subscription
1357         SET    enddate=?
1358         WHERE  subscriptionid=?
1359     |;
1360     $sth = $dbh->prepare($query);
1361     $sth->execute( $enddate, $subscriptionid );
1362     $query = qq|
1363         UPDATE subscriptionhistory
1364         SET    histenddate=?
1365         WHERE  subscriptionid=?
1366     |;
1367     $sth = $dbh->prepare($query);
1368     $sth->execute( $enddate, $subscriptionid );
1369
1370     logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1371     return;
1372 }
1373
1374 =head2 NewIssue
1375
1376 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate,  $notes)
1377
1378 Create a new issue stored on the database.
1379 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1380 returns the serial id
1381
1382 =cut
1383
1384 sub NewIssue {
1385     my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1386     ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1387
1388     my $dbh   = C4::Context->dbh;
1389     my $query = qq|
1390         INSERT INTO serial
1391             (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1392         VALUES (?,?,?,?,?,?,?)
1393     |;
1394     my $sth = $dbh->prepare($query);
1395     $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1396     my $serialid = $dbh->{'mysql_insertid'};
1397     $query = qq|
1398         SELECT missinglist,recievedlist
1399         FROM   subscriptionhistory
1400         WHERE  subscriptionid=?
1401     |;
1402     $sth = $dbh->prepare($query);
1403     $sth->execute($subscriptionid);
1404     my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1405
1406     if ( $status == 2 ) {
1407       ### TODO Add a feature that improves recognition and description.
1408       ### As such count (serialseq) i.e. : N18,2(N19),N20
1409       ### Would use substr and index But be careful to previous presence of ()
1410         $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1411     }
1412     if ( $status == 4 ) {
1413         $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1414     }
1415     $query = qq|
1416         UPDATE subscriptionhistory
1417         SET    recievedlist=?, missinglist=?
1418         WHERE  subscriptionid=?
1419     |;
1420     $sth = $dbh->prepare($query);
1421     $recievedlist =~ s/^; //;
1422     $missinglist  =~ s/^; //;
1423     $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1424     return $serialid;
1425 }
1426
1427 =head2 ItemizeSerials
1428
1429 ItemizeSerials($serialid, $info);
1430 $info is a hashref containing  barcode branch, itemcallnumber, status, location
1431 $serialid the serialid
1432 return :
1433 1 if the itemize is a succes.
1434 0 and @error otherwise. @error containts the list of errors found.
1435
1436 =cut
1437
1438 sub ItemizeSerials {
1439     my ( $serialid, $info ) = @_;
1440     my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1441
1442     my $dbh   = C4::Context->dbh;
1443     my $query = qq|
1444         SELECT *
1445         FROM   serial
1446         WHERE  serialid=?
1447     |;
1448     my $sth = $dbh->prepare($query);
1449     $sth->execute($serialid);
1450     my $data = $sth->fetchrow_hashref;
1451     if ( C4::Context->preference("RoutingSerials") ) {
1452
1453         # check for existing biblioitem relating to serial issue
1454         my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1455         my $bibitemno = 0;
1456         for ( my $i = 0 ; $i < $count ; $i++ ) {
1457             if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1458                 $bibitemno = $results[$i]->{'biblioitemnumber'};
1459                 last;
1460             }
1461         }
1462         if ( $bibitemno == 0 ) {
1463             my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1464             $sth->execute( $data->{'biblionumber'} );
1465             my $biblioitem = $sth->fetchrow_hashref;
1466             $biblioitem->{'volumedate'}  = $data->{planneddate};
1467             $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1468             $biblioitem->{'dewey'}       = $info->{itemcallnumber};
1469         }
1470     }
1471
1472     my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1473     if ( $info->{barcode} ) {
1474         my @errors;
1475         if ( is_barcode_in_use( $info->{barcode} ) ) {
1476             push @errors, 'barcode_not_unique';
1477         } else {
1478             my $marcrecord = MARC::Record->new();
1479             my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1480             my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1481             $marcrecord->insert_fields_ordered($newField);
1482             if ( $info->{branch} ) {
1483                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1484
1485                 #warn "items.homebranch : $tag , $subfield";
1486                 if ( $marcrecord->field($tag) ) {
1487                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1488                 } else {
1489                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1490                     $marcrecord->insert_fields_ordered($newField);
1491                 }
1492                 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1493
1494                 #warn "items.holdingbranch : $tag , $subfield";
1495                 if ( $marcrecord->field($tag) ) {
1496                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1497                 } else {
1498                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1499                     $marcrecord->insert_fields_ordered($newField);
1500                 }
1501             }
1502             if ( $info->{itemcallnumber} ) {
1503                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1504
1505                 if ( $marcrecord->field($tag) ) {
1506                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1507                 } else {
1508                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1509                     $marcrecord->insert_fields_ordered($newField);
1510                 }
1511             }
1512             if ( $info->{notes} ) {
1513                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1514
1515                 if ( $marcrecord->field($tag) ) {
1516                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1517                 } else {
1518                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1519                     $marcrecord->insert_fields_ordered($newField);
1520                 }
1521             }
1522             if ( $info->{location} ) {
1523                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1524
1525                 if ( $marcrecord->field($tag) ) {
1526                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1527                 } else {
1528                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1529                     $marcrecord->insert_fields_ordered($newField);
1530                 }
1531             }
1532             if ( $info->{status} ) {
1533                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1534
1535                 if ( $marcrecord->field($tag) ) {
1536                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1537                 } else {
1538                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1539                     $marcrecord->insert_fields_ordered($newField);
1540                 }
1541             }
1542             if ( C4::Context->preference("RoutingSerials") ) {
1543                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1544                 if ( $marcrecord->field($tag) ) {
1545                     $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1546                 } else {
1547                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1548                     $marcrecord->insert_fields_ordered($newField);
1549                 }
1550             }
1551             AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1552             return 1;
1553         }
1554         return ( 0, @errors );
1555     }
1556 }
1557
1558 =head2 HasSubscriptionStrictlyExpired
1559
1560 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1561
1562 the subscription has stricly expired when today > the end subscription date 
1563
1564 return :
1565 1 if true, 0 if false, -1 if the expiration date is not set.
1566
1567 =cut
1568
1569 sub HasSubscriptionStrictlyExpired {
1570
1571     # Getting end of subscription date
1572     my ($subscriptionid) = @_;
1573     my $dbh              = C4::Context->dbh;
1574     my $subscription     = GetSubscription($subscriptionid);
1575     my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1576
1577     # If the expiration date is set
1578     if ( $expirationdate != 0 ) {
1579         my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1580
1581         # Getting today's date
1582         my ( $nowyear, $nowmonth, $nowday ) = Today();
1583
1584         # if today's date > expiration date, then the subscription has stricly expired
1585         if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1586             return 1;
1587         } else {
1588             return 0;
1589         }
1590     } else {
1591
1592         # There are some cases where the expiration date is not set
1593         # As we can't determine if the subscription has expired on a date-basis,
1594         # we return -1;
1595         return -1;
1596     }
1597 }
1598
1599 =head2 HasSubscriptionExpired
1600
1601 $has_expired = HasSubscriptionExpired($subscriptionid)
1602
1603 the subscription has expired when the next issue to arrive is out of subscription limit.
1604
1605 return :
1606 0 if the subscription has not expired
1607 1 if the subscription has expired
1608 2 if has subscription does not have a valid expiration date set
1609
1610 =cut
1611
1612 sub HasSubscriptionExpired {
1613     my ($subscriptionid) = @_;
1614     my $dbh              = C4::Context->dbh;
1615     my $subscription     = GetSubscription($subscriptionid);
1616     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1617         my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1618         if (!defined $expirationdate) {
1619             $expirationdate = q{};
1620         }
1621         my $query          = qq|
1622             SELECT max(planneddate)
1623             FROM   serial
1624             WHERE  subscriptionid=?
1625       |;
1626         my $sth = $dbh->prepare($query);
1627         $sth->execute($subscriptionid);
1628         my ($res) = $sth->fetchrow;
1629         if (!$res || $res=~m/^0000/) {
1630             return 0;
1631         }
1632         my @res                   = split( /-/, $res );
1633         my @endofsubscriptiondate = split( /-/, $expirationdate );
1634         return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1635         return 1
1636           if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1637             || ( !$res ) );
1638         return 0;
1639     } else {
1640         if ( $subscription->{'numberlength'} ) {
1641             my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1642             return 1 if ( $countreceived > $subscription->{'numberlength'} );
1643             return 0;
1644         } else {
1645             return 0;
1646         }
1647     }
1648     return 0;    # Notice that you'll never get here.
1649 }
1650
1651 =head2 SetDistributedto
1652
1653 SetDistributedto($distributedto,$subscriptionid);
1654 This function update the value of distributedto for a subscription given on input arg.
1655
1656 =cut
1657
1658 sub SetDistributedto {
1659     my ( $distributedto, $subscriptionid ) = @_;
1660     my $dbh   = C4::Context->dbh;
1661     my $query = qq|
1662         UPDATE subscription
1663         SET    distributedto=?
1664         WHERE  subscriptionid=?
1665     |;
1666     my $sth = $dbh->prepare($query);
1667     $sth->execute( $distributedto, $subscriptionid );
1668     return;
1669 }
1670
1671 =head2 DelSubscription
1672
1673 DelSubscription($subscriptionid)
1674 this function deletes subscription which has $subscriptionid as id.
1675
1676 =cut
1677
1678 sub DelSubscription {
1679     my ($subscriptionid) = @_;
1680     my $dbh = C4::Context->dbh;
1681     $subscriptionid = $dbh->quote($subscriptionid);
1682     $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1683     $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1684     $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1685
1686     logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1687 }
1688
1689 =head2 DelIssue
1690
1691 DelIssue($serialseq,$subscriptionid)
1692 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1693
1694 returns the number of rows affected
1695
1696 =cut
1697
1698 sub DelIssue {
1699     my ($dataissue) = @_;
1700     my $dbh = C4::Context->dbh;
1701     ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1702
1703     my $query = qq|
1704         DELETE FROM serial
1705         WHERE       serialid= ?
1706         AND         subscriptionid= ?
1707     |;
1708     my $mainsth = $dbh->prepare($query);
1709     $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1710
1711     #Delete element from subscription history
1712     $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1713     my $sth = $dbh->prepare($query);
1714     $sth->execute( $dataissue->{'subscriptionid'} );
1715     my $val = $sth->fetchrow_hashref;
1716     unless ( $val->{manualhistory} ) {
1717         my $query = qq|
1718           SELECT * FROM subscriptionhistory
1719           WHERE       subscriptionid= ?
1720       |;
1721         my $sth = $dbh->prepare($query);
1722         $sth->execute( $dataissue->{'subscriptionid'} );
1723         my $data      = $sth->fetchrow_hashref;
1724         my $serialseq = $dataissue->{'serialseq'};
1725         $data->{'missinglist'}  =~ s/\b$serialseq\b//;
1726         $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1727         my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1728         $sth = $dbh->prepare($strsth);
1729         $sth->execute( $dataissue->{'subscriptionid'} );
1730     }
1731
1732     return $mainsth->rows;
1733 }
1734
1735 =head2 GetLateOrMissingIssues
1736
1737 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1738
1739 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1740
1741 return :
1742 the issuelist as an array of hash refs. Each element of this array contains 
1743 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1744
1745 =cut
1746
1747 sub GetLateOrMissingIssues {
1748     my ( $supplierid, $serialid, $order ) = @_;
1749     my $dbh = C4::Context->dbh;
1750     my $sth;
1751     my $byserial = '';
1752     if ($serialid) {
1753         $byserial = "and serialid = " . $serialid;
1754     }
1755     if ($order) {
1756         $order .= ", title";
1757     } else {
1758         $order = "title";
1759     }
1760     if ($supplierid) {
1761         $sth = $dbh->prepare(
1762             "SELECT
1763                 serialid,      aqbooksellerid,        name,
1764                 biblio.title,  planneddate,           serialseq,
1765                 serial.status, serial.subscriptionid, claimdate,
1766                 subscription.branchcode
1767             FROM      serial 
1768                 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
1769                 LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
1770                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1771                 WHERE subscription.subscriptionid = serial.subscriptionid 
1772                 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1773                 AND subscription.aqbooksellerid=$supplierid
1774                 $byserial
1775                 ORDER BY $order"
1776         );
1777     } else {
1778         $sth = $dbh->prepare(
1779             "SELECT 
1780             serialid,      aqbooksellerid,         name,
1781             biblio.title,  planneddate,           serialseq,
1782                 serial.status, serial.subscriptionid, claimdate,
1783                 subscription.branchcode
1784             FROM serial 
1785                 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid 
1786                 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1787                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1788                 WHERE subscription.subscriptionid = serial.subscriptionid 
1789                         AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1790                 $byserial
1791                 ORDER BY $order"
1792         );
1793     }
1794     $sth->execute;
1795     my @issuelist;
1796     while ( my $line = $sth->fetchrow_hashref ) {
1797
1798         if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1799             $line->{planneddate} = format_date( $line->{planneddate} );
1800         }
1801         if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1802             $line->{claimdate}   = format_date( $line->{claimdate} );
1803         }
1804         $line->{"status".$line->{status}}   = 1;
1805         push @issuelist, $line;
1806     }
1807     return @issuelist;
1808 }
1809
1810 =head2 removeMissingIssue
1811
1812 removeMissingIssue($subscriptionid)
1813
1814 this function removes an issue from being part of the missing string in 
1815 subscriptionlist.missinglist column
1816
1817 called when a missing issue is found from the serials-recieve.pl file
1818
1819 =cut
1820
1821 sub removeMissingIssue {
1822     my ( $sequence, $subscriptionid ) = @_;
1823     my $dbh = C4::Context->dbh;
1824     my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1825     $sth->execute($subscriptionid);
1826     my $data              = $sth->fetchrow_hashref;
1827     my $missinglist       = $data->{'missinglist'};
1828     my $missinglistbefore = $missinglist;
1829
1830     # warn $missinglist." before";
1831     $missinglist =~ s/($sequence)//;
1832
1833     # warn $missinglist." after";
1834     if ( $missinglist ne $missinglistbefore ) {
1835         $missinglist =~ s/\|\s\|/\|/g;
1836         $missinglist =~ s/^\| //g;
1837         $missinglist =~ s/\|$//g;
1838         my $sth2 = $dbh->prepare(
1839             "UPDATE subscriptionhistory
1840                     SET missinglist = ?
1841                     WHERE subscriptionid = ?"
1842         );
1843         $sth2->execute( $missinglist, $subscriptionid );
1844     }
1845     return;
1846 }
1847
1848 =head2 updateClaim
1849
1850 &updateClaim($serialid)
1851
1852 this function updates the time when a claim is issued for late/missing items
1853
1854 called from claims.pl file
1855
1856 =cut
1857
1858 sub updateClaim {
1859     my ($serialid) = @_;
1860     my $dbh        = C4::Context->dbh;
1861     my $sth        = $dbh->prepare(
1862         "UPDATE serial SET claimdate = now()
1863                 WHERE serialid = ?
1864         "
1865     );
1866     $sth->execute($serialid);
1867     return;
1868 }
1869
1870 =head2 getsupplierbyserialid
1871
1872 $result = getsupplierbyserialid($serialid)
1873
1874 this function is used to find the supplier id given a serial id
1875
1876 return :
1877 hashref containing serialid, subscriptionid, and aqbooksellerid
1878
1879 =cut
1880
1881 sub getsupplierbyserialid {
1882     my ($serialid) = @_;
1883     my $dbh        = C4::Context->dbh;
1884     my $sth        = $dbh->prepare(
1885         "SELECT serialid, serial.subscriptionid, aqbooksellerid
1886          FROM serial 
1887             LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1888             WHERE serialid = ?
1889         "
1890     );
1891     $sth->execute($serialid);
1892     my $line   = $sth->fetchrow_hashref;
1893     my $result = $line->{'aqbooksellerid'};
1894     return $result;
1895 }
1896
1897 =head2 check_routing
1898
1899 $result = &check_routing($subscriptionid)
1900
1901 this function checks to see if a serial has a routing list and returns the count of routingid
1902 used to show either an 'add' or 'edit' link
1903
1904 =cut
1905
1906 sub check_routing {
1907     my ($subscriptionid) = @_;
1908     my $dbh              = C4::Context->dbh;
1909     my $sth              = $dbh->prepare(
1910         "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist 
1911                               ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1912                               WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1913                               "
1914     );
1915     $sth->execute($subscriptionid);
1916     my $line   = $sth->fetchrow_hashref;
1917     my $result = $line->{'routingids'};
1918     return $result;
1919 }
1920
1921 =head2 addroutingmember
1922
1923 addroutingmember($borrowernumber,$subscriptionid)
1924
1925 this function takes a borrowernumber and subscriptionid and adds the member to the
1926 routing list for that serial subscription and gives them a rank on the list
1927 of either 1 or highest current rank + 1
1928
1929 =cut
1930
1931 sub addroutingmember {
1932     my ( $borrowernumber, $subscriptionid ) = @_;
1933     my $rank;
1934     my $dbh = C4::Context->dbh;
1935     my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1936     $sth->execute($subscriptionid);
1937     while ( my $line = $sth->fetchrow_hashref ) {
1938         if ( $line->{'rank'} > 0 ) {
1939             $rank = $line->{'rank'} + 1;
1940         } else {
1941             $rank = 1;
1942         }
1943     }
1944     $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1945     $sth->execute( $subscriptionid, $borrowernumber, $rank );
1946 }
1947
1948 =head2 reorder_members
1949
1950 reorder_members($subscriptionid,$routingid,$rank)
1951
1952 this function is used to reorder the routing list
1953
1954 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1955 - it gets all members on list puts their routingid's into an array
1956 - removes the one in the array that is $routingid
1957 - then reinjects $routingid at point indicated by $rank
1958 - then update the database with the routingids in the new order
1959
1960 =cut
1961
1962 sub reorder_members {
1963     my ( $subscriptionid, $routingid, $rank ) = @_;
1964     my $dbh = C4::Context->dbh;
1965     my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1966     $sth->execute($subscriptionid);
1967     my @result;
1968     while ( my $line = $sth->fetchrow_hashref ) {
1969         push( @result, $line->{'routingid'} );
1970     }
1971
1972     # To find the matching index
1973     my $i;
1974     my $key = -1;    # to allow for 0 being a valid response
1975     for ( $i = 0 ; $i < @result ; $i++ ) {
1976         if ( $routingid == $result[$i] ) {
1977             $key = $i;    # save the index
1978             last;
1979         }
1980     }
1981
1982     # if index exists in array then move it to new position
1983     if ( $key > -1 && $rank > 0 ) {
1984         my $new_rank = $rank - 1;                       # $new_rank is what you want the new index to be in the array
1985         my $moving_item = splice( @result, $key, 1 );
1986         splice( @result, $new_rank, 0, $moving_item );
1987     }
1988     for ( my $j = 0 ; $j < @result ; $j++ ) {
1989         my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1990         $sth->execute;
1991     }
1992     return;
1993 }
1994
1995 =head2 delroutingmember
1996
1997 delroutingmember($routingid,$subscriptionid)
1998
1999 this function either deletes one member from routing list if $routingid exists otherwise
2000 deletes all members from the routing list
2001
2002 =cut
2003
2004 sub delroutingmember {
2005
2006     # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2007     my ( $routingid, $subscriptionid ) = @_;
2008     my $dbh = C4::Context->dbh;
2009     if ($routingid) {
2010         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2011         $sth->execute($routingid);
2012         reorder_members( $subscriptionid, $routingid );
2013     } else {
2014         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2015         $sth->execute($subscriptionid);
2016     }
2017     return;
2018 }
2019
2020 =head2 getroutinglist
2021
2022 @routinglist = getroutinglist($subscriptionid)
2023
2024 this gets the info from the subscriptionroutinglist for $subscriptionid
2025
2026 return :
2027 the routinglist as an array. Each element of the array contains a hash_ref containing
2028 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2029
2030 =cut
2031
2032 sub getroutinglist {
2033     my ($subscriptionid) = @_;
2034     my $dbh              = C4::Context->dbh;
2035     my $sth              = $dbh->prepare(
2036         'SELECT routingid, borrowernumber, ranking, biblionumber
2037             FROM subscription 
2038             JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2039             WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2040     );
2041     $sth->execute($subscriptionid);
2042     my $routinglist = $sth->fetchall_arrayref({});
2043     return @{$routinglist};
2044 }
2045
2046 =head2 countissuesfrom
2047
2048 $result = countissuesfrom($subscriptionid,$startdate)
2049
2050 Returns a count of serial rows matching the given subsctiptionid
2051 with published date greater than startdate
2052
2053 =cut
2054
2055 sub countissuesfrom {
2056     my ( $subscriptionid, $startdate ) = @_;
2057     my $dbh   = C4::Context->dbh;
2058     my $query = qq|
2059             SELECT count(*)
2060             FROM   serial
2061             WHERE  subscriptionid=?
2062             AND serial.publisheddate>?
2063         |;
2064     my $sth = $dbh->prepare($query);
2065     $sth->execute( $subscriptionid, $startdate );
2066     my ($countreceived) = $sth->fetchrow;
2067     return $countreceived;
2068 }
2069
2070 =head2 CountIssues
2071
2072 $result = CountIssues($subscriptionid)
2073
2074 Returns a count of serial rows matching the given subsctiptionid
2075
2076 =cut
2077
2078 sub CountIssues {
2079     my ($subscriptionid) = @_;
2080     my $dbh              = C4::Context->dbh;
2081     my $query            = qq|
2082             SELECT count(*)
2083             FROM   serial
2084             WHERE  subscriptionid=?
2085         |;
2086     my $sth = $dbh->prepare($query);
2087     $sth->execute($subscriptionid);
2088     my ($countreceived) = $sth->fetchrow;
2089     return $countreceived;
2090 }
2091
2092 =head2 HasItems
2093
2094 $result = HasItems($subscriptionid)
2095
2096 returns a count of items from serial matching the subscriptionid
2097
2098 =cut
2099
2100 sub HasItems {
2101     my ($subscriptionid) = @_;
2102     my $dbh              = C4::Context->dbh;
2103     my $query = q|
2104             SELECT COUNT(serialitems.itemnumber)
2105             FROM   serial 
2106                         LEFT JOIN serialitems USING(serialid)
2107             WHERE  subscriptionid=? AND serialitems.serialid IS NOT NULL
2108         |;
2109     my $sth=$dbh->prepare($query);
2110     $sth->execute($subscriptionid);
2111     my ($countitems)=$sth->fetchrow_array();
2112     return $countitems;  
2113 }
2114
2115 =head2 abouttoexpire
2116
2117 $result = abouttoexpire($subscriptionid)
2118
2119 this function alerts you to the penultimate issue for a serial subscription
2120
2121 returns 1 - if this is the penultimate issue
2122 returns 0 - if not
2123
2124 =cut
2125
2126 sub abouttoexpire {
2127     my ($subscriptionid) = @_;
2128     my $dbh              = C4::Context->dbh;
2129     my $subscription     = GetSubscription($subscriptionid);
2130     my $per = $subscription->{'periodicity'};
2131     if ($per && $per % 16 > 0){
2132         my $expirationdate   = GetExpirationDate($subscriptionid);
2133         my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2134         my @res;
2135         if (defined $res) {
2136             @res=split (/-/,$res);
2137             @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2138         } else { # default an undefined value
2139             @res=Date::Calc::Today;
2140         }
2141         my @endofsubscriptiondate=split(/-/,$expirationdate);
2142         my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2143         my @datebeforeend;
2144         @datebeforeend = Add_Delta_Days(  $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2145             - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2146         return 1 if ( @res &&
2147             (@datebeforeend &&
2148                 Delta_Days($res[0],$res[1],$res[2],
2149                     $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2150             (@endofsubscriptiondate &&
2151                 Delta_Days($res[0],$res[1],$res[2],
2152                     $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2153         return 0;
2154     } elsif ($subscription->{numberlength}>0) {
2155         return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2156     }
2157     return 0;
2158 }
2159
2160 sub in_array {    # used in next sub down
2161     my ( $val, @elements ) = @_;
2162     foreach my $elem (@elements) {
2163         if ( $val == $elem ) {
2164             return 1;
2165         }
2166     }
2167     return 0;
2168 }
2169
2170 =head2 GetNextDate
2171
2172 $resultdate = GetNextDate($planneddate,$subscription)
2173
2174 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2175 exists an irregularity
2176 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be 
2177 skipped then the returned date will be 2007-05-10
2178
2179 return :
2180 $resultdate - then next date in the sequence
2181
2182 Return 0 if periodicity==0
2183
2184 =cut
2185
2186 sub GetNextDate(@) {
2187     my ( $planneddate, $subscription ) = @_;
2188     my @irreg = split( /\,/, $subscription->{irregularity} );
2189
2190     #date supposed to be in ISO.
2191
2192     my ( $year, $month, $day ) = split( /-/, $planneddate );
2193     $month = 1 unless ($month);
2194     $day   = 1 unless ($day);
2195     my @resultdate;
2196
2197     #       warn "DOW $dayofweek";
2198     if ( $subscription->{periodicity} % 16 == 0 ) {    # 'without regularity' || 'irregular'
2199         return 0;
2200     }
2201
2202     #   daily : n / week
2203     #   Since we're interpreting irregularity here as which days of the week to skip an issue,
2204     #   renaming this pattern from 1/day to " n / week ".
2205     if ( $subscription->{periodicity} == 1 ) {
2206         my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2207         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2208         else {
2209             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2210                 $dayofweek = 0 if ( $dayofweek == 7 );
2211                 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2212                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2213                     $dayofweek++;
2214                 }
2215             }
2216             @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2217         }
2218     }
2219
2220     #   1  week
2221     if ( $subscription->{periodicity} == 2 ) {
2222         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2223         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2224         else {
2225             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2226
2227                 #FIXME: if two consecutive irreg, do we only skip one?
2228                 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2229                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2230                     $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2231                 }
2232             }
2233             @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2234         }
2235     }
2236
2237     #   1 / 2 weeks
2238     if ( $subscription->{periodicity} == 3 ) {
2239         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2240         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2241         else {
2242             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2243                 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2244                     ### BUGFIX was previously +1 ^
2245                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2246                     $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2247                 }
2248             }
2249             @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2250         }
2251     }
2252
2253     #   1 / 3 weeks
2254     if ( $subscription->{periodicity} == 4 ) {
2255         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2256         if ($@) { warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2257         else {
2258             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2259                 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2260                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2261                     $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2262                 }
2263             }
2264             @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2265         }
2266     }
2267     my $tmpmonth = $month;
2268     if ( $year && $month && $day ) {
2269         if ( $subscription->{periodicity} == 5 ) {
2270             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2271                 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2272                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2273                     $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2274                 }
2275             }
2276             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2277         }
2278         if ( $subscription->{periodicity} == 6 ) {
2279             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2280                 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2281                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2282                     $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2283                 }
2284             }
2285             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2286         }
2287         if ( $subscription->{periodicity} == 7 ) {
2288             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2289                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2290                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2291                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2292                 }
2293             }
2294             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2295         }
2296         if ( $subscription->{periodicity} == 8 ) {
2297             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2298                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2299                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2300                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2301                 }
2302             }
2303             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2304         }
2305         if ( $subscription->{periodicity} == 13 ) {
2306             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2307                 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2308                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2309                     $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2310                 }
2311             }
2312             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2313         }
2314         if ( $subscription->{periodicity} == 9 ) {
2315             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2316                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2317                     ### BUFIX Seems to need more Than One ?
2318                     ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2319                     $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2320                 }
2321             }
2322             @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2323         }
2324         if ( $subscription->{periodicity} == 10 ) {
2325             @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2326         }
2327         if ( $subscription->{periodicity} == 11 ) {
2328             @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2329         }
2330     }
2331     my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2332
2333     return "$resultdate";
2334 }
2335
2336 =head2 is_barcode_in_use
2337
2338 Returns number of occurence of the barcode in the items table
2339 Can be used as a boolean test of whether the barcode has
2340 been deployed as yet
2341
2342 =cut
2343
2344 sub is_barcode_in_use {
2345     my $barcode = shift;
2346     my $dbh       = C4::Context->dbh;
2347     my $occurences = $dbh->selectall_arrayref(
2348         'SELECT itemnumber from items where barcode = ?',
2349         {}, $barcode
2350
2351     );
2352
2353     return @{$occurences};
2354 }
2355
2356 1;
2357 __END__
2358
2359 =head1 AUTHOR
2360
2361 Koha Development Team <http://koha-community.org/>
2362
2363 =cut