Bug 2616: Remove unnecessary 'use HTML::Template' calls
[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         if ( $previousbiblio eq $line->{biblionumber} ) {
616             $line->{title} = "";
617             $line->{issn}  = "";
618         } else {
619             $previousbiblio = $line->{biblionumber};
620             $odd           = -$odd;
621         }
622         $line->{toggle} = 1 if $odd == 1;
623         $line->{'cannotedit'} =
624           (      C4::Context->preference('IndependantBranches')
625               && C4::Context->userenv
626               && C4::Context->userenv->{flags} % 2 != 1
627               && C4::Context->userenv->{branch}
628               && $line->{branchcode}
629               && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
630         push @results, $line;
631     }
632     return @results;
633 }
634
635 =head2 GetSerials
636
637 ($totalissues,@serials) = GetSerials($subscriptionid);
638 this function gets every serial not arrived for a given subscription
639 as well as the number of issues registered in the database (all types)
640 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
641
642 FIXME: We should return \@serials.
643
644 =cut
645
646 sub GetSerials {
647     my ( $subscriptionid, $count ) = @_;
648     my $dbh = C4::Context->dbh;
649
650     # status = 2 is "arrived"
651     my $counter = 0;
652     $count = 5 unless ($count);
653     my @serials;
654     my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
655                         FROM   serial
656                         WHERE  subscriptionid = ? AND status NOT IN (2,4,5) 
657                         ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
658     my $sth = $dbh->prepare($query);
659     $sth->execute($subscriptionid);
660
661     while ( my $line = $sth->fetchrow_hashref ) {
662         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
663         for my $datefield ( qw( planneddate publisheddate) ) {
664             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
665                 $line->{$datefield} = format_date( $line->{$datefield});
666             } else {
667                 $line->{$datefield} = q{};
668             }
669         }
670         push @serials, $line;
671     }
672
673     # OK, now add the last 5 issues arrives/missing
674     $query = "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
675        FROM     serial
676        WHERE    subscriptionid = ?
677        AND      (status in (2,4,5))
678        ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
679       ";
680     $sth = $dbh->prepare($query);
681     $sth->execute($subscriptionid);
682     while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
683         $counter++;
684         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
685         for my $datefield ( qw( planneddate publisheddate) ) {
686             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
687                 $line->{$datefield} = format_date( $line->{$datefield});
688             } else {
689                 $line->{$datefield} = q{};
690             }
691         }
692
693         push @serials, $line;
694     }
695
696     $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
697     $sth   = $dbh->prepare($query);
698     $sth->execute($subscriptionid);
699     my ($totalissues) = $sth->fetchrow;
700     return ( $totalissues, @serials );
701 }
702
703 =head2 GetSerials2
704
705 @serials = GetSerials2($subscriptionid,$status);
706 this function returns every serial waited for a given subscription
707 as well as the number of issues registered in the database (all types)
708 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
709
710 =cut
711
712 sub GetSerials2 {
713     my ( $subscription, $status ) = @_;
714     my $dbh   = C4::Context->dbh;
715     my $query = qq|
716                  SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
717                  FROM     serial 
718                  WHERE    subscriptionid=$subscription AND status IN ($status)
719                  ORDER BY publisheddate,serialid DESC
720                     |;
721     $debug and warn "GetSerials2 query: $query";
722     my $sth = $dbh->prepare($query);
723     $sth->execute;
724     my @serials;
725
726     while ( my $line = $sth->fetchrow_hashref ) {
727         $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
728         # Format dates for display
729         for my $datefield ( qw( planneddate publisheddate ) ) {
730             if ($line->{$datefield} =~m/^00/) {
731                 $line->{$datefield} = q{};
732             }
733             else {
734                 $line->{$datefield} = format_date( $line->{$datefield} );
735             }
736         }
737         push @serials, $line;
738     }
739     return @serials;
740 }
741
742 =head2 GetLatestSerials
743
744 \@serials = GetLatestSerials($subscriptionid,$limit)
745 get the $limit's latest serials arrived or missing for a given subscription
746 return :
747 a ref to an array which contains all of the latest serials stored into a hash.
748
749 =cut
750
751 sub GetLatestSerials {
752     my ( $subscriptionid, $limit ) = @_;
753     my $dbh = C4::Context->dbh;
754
755     # status = 2 is "arrived"
756     my $strsth = "SELECT   serialid,serialseq, status, planneddate, notes
757                         FROM     serial
758                         WHERE    subscriptionid = ?
759                         AND      (status =2 or status=4)
760                         ORDER BY planneddate DESC LIMIT 0,$limit
761                 ";
762     my $sth = $dbh->prepare($strsth);
763     $sth->execute($subscriptionid);
764     my @serials;
765     while ( my $line = $sth->fetchrow_hashref ) {
766         $line->{ "status" . $line->{status} } = 1;                        # fills a "statusX" value, used for template status select list
767         $line->{"planneddate"} = format_date( $line->{"planneddate"} );
768         push @serials, $line;
769     }
770
771     return \@serials;
772 }
773
774 =head2 GetDistributedTo
775
776 $distributedto=GetDistributedTo($subscriptionid)
777 This function returns the field distributedto for the subscription matching subscriptionid
778
779 =cut
780
781 sub GetDistributedTo {
782     my $dbh = C4::Context->dbh;
783     my $distributedto;
784     my $subscriptionid = @_;
785     my $query          = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
786     my $sth            = $dbh->prepare($query);
787     $sth->execute($subscriptionid);
788     return ($distributedto) = $sth->fetchrow;
789 }
790
791 =head2 GetNextSeq
792
793 GetNextSeq($val)
794 $val is a hashref containing all the attributes of the table 'subscription'
795 This function get the next issue for the subscription given on input arg
796 return:
797 a list containing all the input params updated.
798
799 =cut
800
801 # sub GetNextSeq {
802 #     my ($val) =@_;
803 #     my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
804 #     $calculated = $val->{numberingmethod};
805 # # calculate the (expected) value of the next issue recieved.
806 #     $newlastvalue1 = $val->{lastvalue1};
807 # # check if we have to increase the new value.
808 #     $newinnerloop1 = $val->{innerloop1}+1;
809 #     $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
810 #     $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
811 #     $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
812 #     $calculated =~ s/\{X\}/$newlastvalue1/g;
813 #
814 #     $newlastvalue2 = $val->{lastvalue2};
815 # # check if we have to increase the new value.
816 #     $newinnerloop2 = $val->{innerloop2}+1;
817 #     $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
818 #     $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
819 #     $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
820 #     $calculated =~ s/\{Y\}/$newlastvalue2/g;
821 #
822 #     $newlastvalue3 = $val->{lastvalue3};
823 # # check if we have to increase the new value.
824 #     $newinnerloop3 = $val->{innerloop3}+1;
825 #     $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
826 #     $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
827 #     $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
828 #     $calculated =~ s/\{Z\}/$newlastvalue3/g;
829 #     return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
830 # }
831
832 sub GetNextSeq {
833     my ($val) = @_;
834     my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
835     my $pattern          = $val->{numberpattern};
836     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
837     my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
838     $calculated    = $val->{numberingmethod};
839     $newlastvalue1 = $val->{lastvalue1};
840     $newlastvalue2 = $val->{lastvalue2};
841     $newlastvalue3 = $val->{lastvalue3};
842     $newlastvalue1 = $val->{lastvalue1};
843
844     # check if we have to increase the new value.
845     $newinnerloop1 = $val->{innerloop1} + 1;
846     $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
847     $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 );    # <1 to be true when 0 or empty.
848     $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} );    # reset counter if needed.
849     $calculated =~ s/\{X\}/$newlastvalue1/g;
850
851     $newlastvalue2 = $val->{lastvalue2};
852
853     # check if we have to increase the new value.
854     $newinnerloop2 = $val->{innerloop2} + 1;
855     $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
856     $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 );                         # <1 to be true when 0 or empty.
857     $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} );    # reset counter if needed.
858     if ( $pattern == 6 ) {
859         if ( $val->{hemisphere} == 2 ) {
860             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
861             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
862         } else {
863             my $newlastvalue2seq = $seasons[$newlastvalue2];
864             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
865         }
866     } else {
867         $calculated =~ s/\{Y\}/$newlastvalue2/g;
868     }
869
870     $newlastvalue3 = $val->{lastvalue3};
871
872     # check if we have to increase the new value.
873     $newinnerloop3 = $val->{innerloop3} + 1;
874     $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
875     $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 );    # <1 to be true when 0 or empty.
876     $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} );    # reset counter if needed.
877     $calculated =~ s/\{Z\}/$newlastvalue3/g;
878
879     return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
880 }
881
882 =head2 GetSeq
883
884 $calculated = GetSeq($val)
885 $val is a hashref containing all the attributes of the table 'subscription'
886 this function transforms {X},{Y},{Z} to 150,0,0 for example.
887 return:
888 the sequence in integer format
889
890 =cut
891
892 sub GetSeq {
893     my ($val) = @_;
894     my $pattern = $val->{numberpattern};
895     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
896     my @southern_seasons = ( '',        'Summer', 'Autumn', 'Winter', 'Spring' );
897     my $calculated       = $val->{numberingmethod};
898     my $x                = $val->{'lastvalue1'};
899     $calculated =~ s/\{X\}/$x/g;
900     my $newlastvalue2 = $val->{'lastvalue2'};
901
902     if ( $pattern == 6 ) {
903         if ( $val->{hemisphere} == 2 ) {
904             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
905             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
906         } else {
907             my $newlastvalue2seq = $seasons[$newlastvalue2];
908             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
909         }
910     } else {
911         $calculated =~ s/\{Y\}/$newlastvalue2/g;
912     }
913     my $z = $val->{'lastvalue3'};
914     $calculated =~ s/\{Z\}/$z/g;
915     return $calculated;
916 }
917
918 =head2 GetExpirationDate
919
920 $enddate = GetExpirationDate($subscriptionid, [$startdate])
921
922 this function return the next expiration date for a subscription given on input args.
923
924 return
925 the enddate or undef
926
927 =cut
928
929 sub GetExpirationDate {
930     my ( $subscriptionid, $startdate ) = @_;
931     my $dbh          = C4::Context->dbh;
932     my $subscription = GetSubscription($subscriptionid);
933     my $enddate;
934
935     # we don't do the same test if the subscription is based on X numbers or on X weeks/months
936     $enddate = $startdate || $subscription->{startdate};
937     my @date = split( /-/, $enddate );
938     return if ( scalar(@date) != 3 || not check_date(@date) );
939     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
940
941         # If Not Irregular
942         if ( my $length = $subscription->{numberlength} ) {
943
944             #calculate the date of the last issue.
945             for ( my $i = 1 ; $i <= $length ; $i++ ) {
946                 $enddate = GetNextDate( $enddate, $subscription );
947             }
948         } elsif ( $subscription->{monthlength} ) {
949             if ( $$subscription{startdate} ) {
950                 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
951                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
952             }
953         } elsif ( $subscription->{weeklength} ) {
954             if ( $$subscription{startdate} ) {
955                 my @date = split( /-/, $subscription->{startdate} );
956                 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
957                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
958             }
959         }
960         return $enddate;
961     } else {
962         return;
963     }
964 }
965
966 =head2 CountSubscriptionFromBiblionumber
967
968 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
969 this returns a count of the subscriptions for a given biblionumber
970 return :
971 the number of subscriptions
972
973 =cut
974
975 sub CountSubscriptionFromBiblionumber {
976     my ($biblionumber) = @_;
977     my $dbh            = C4::Context->dbh;
978     my $query          = "SELECT count(*) FROM subscription WHERE biblionumber=?";
979     my $sth            = $dbh->prepare($query);
980     $sth->execute($biblionumber);
981     my $subscriptionsnumber = $sth->fetchrow;
982     return $subscriptionsnumber;
983 }
984
985 =head2 ModSubscriptionHistory
986
987 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
988
989 this function modifies the history of a subscription. Put your new values on input arg.
990 returns the number of rows affected
991
992 =cut
993
994 sub ModSubscriptionHistory {
995     my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
996     my $dbh   = C4::Context->dbh;
997     my $query = "UPDATE subscriptionhistory 
998                     SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
999                     WHERE subscriptionid=?
1000                 ";
1001     my $sth = $dbh->prepare($query);
1002     $recievedlist =~ s/^; //;
1003     $missinglist  =~ s/^; //;
1004     $opacnote     =~ s/^; //;
1005     $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1006     return $sth->rows;
1007 }
1008
1009 =head2 ModSerialStatus
1010
1011 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1012
1013 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1014 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1015
1016 =cut
1017
1018 sub ModSerialStatus {
1019     my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1020
1021     #It is a usual serial
1022     # 1st, get previous status :
1023     my $dbh   = C4::Context->dbh;
1024     my $query = "SELECT subscriptionid,status FROM serial WHERE  serialid=?";
1025     my $sth   = $dbh->prepare($query);
1026     $sth->execute($serialid);
1027     my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1028
1029     # change status & update subscriptionhistory
1030     my $val;
1031     if ( $status == 6 ) {
1032         DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1033     }
1034     else {
1035         my $query =
1036 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE  serialid = ?';
1037         $sth = $dbh->prepare($query);
1038         $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1039         $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1040         $sth   = $dbh->prepare($query);
1041         $sth->execute($subscriptionid);
1042         my $val = $sth->fetchrow_hashref;
1043         unless ( $val->{manualhistory} ) {
1044             $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE  subscriptionid=?";
1045             $sth   = $dbh->prepare($query);
1046             $sth->execute($subscriptionid);
1047             my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1048             if ( $status == 2 ) {
1049
1050                 $recievedlist .= "; $serialseq"
1051                   unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1052             }
1053
1054             #         warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1055             $missinglist .= "; $serialseq"
1056               if ( $status == 4
1057                 and not index( "$missinglist", "$serialseq" ) >= 0 );
1058             $missinglist .= "; not issued $serialseq"
1059               if ( $status == 5
1060                 and index( "$missinglist", "$serialseq" ) >= 0 );
1061             $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE  subscriptionid=?";
1062             $sth   = $dbh->prepare($query);
1063             $recievedlist =~ s/^; //;
1064             $missinglist  =~ s/^; //;
1065             $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1066         }
1067     }
1068
1069     # create new waited entry if needed (ie : was a "waited" and has changed)
1070     if ( $oldstatus == 1 && $status != 1 ) {
1071         my $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1072         $sth = $dbh->prepare($query);
1073         $sth->execute($subscriptionid);
1074         my $val = $sth->fetchrow_hashref;
1075
1076         # next issue number
1077         my (
1078             $newserialseq,  $newlastvalue1, $newlastvalue2, $newlastvalue3,
1079             $newinnerloop1, $newinnerloop2, $newinnerloop3
1080         ) = GetNextSeq($val);
1081
1082         # next date (calculated from actual date & frequency parameters)
1083         my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1084         NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1085         $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1086                     WHERE  subscriptionid = ?";
1087         $sth = $dbh->prepare($query);
1088         $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1089
1090 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1091         if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1092             SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1093         }
1094     }
1095     return;
1096 }
1097
1098 =head2 GetNextExpected
1099
1100 $nextexpected = GetNextExpected($subscriptionid)
1101
1102 Get the planneddate for the current expected issue of the subscription.
1103
1104 returns a hashref:
1105
1106 $nextexepected = {
1107     serialid => int
1108     planneddate => C4::Dates object
1109     }
1110
1111 =cut
1112
1113 sub GetNextExpected($) {
1114     my ($subscriptionid) = @_;
1115     my $dbh              = C4::Context->dbh;
1116     my $sth              = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1117
1118     # Each subscription has only one 'expected' issue, with serial.status==1.
1119     $sth->execute( $subscriptionid, 1 );
1120     my ( $nextissue ) = $sth->fetchrow_hashref;
1121     if( !$nextissue){
1122          $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid  = ? ORDER BY planneddate DESC LIMIT 1');
1123          $sth->execute( $subscriptionid );  
1124          $nextissue = $sth->fetchrow_hashref;       
1125     }
1126     if (!defined $nextissue->{planneddate}) {
1127         # or should this default to 1st Jan ???
1128         $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1129     }
1130     $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1131     return $nextissue;
1132
1133 }
1134
1135 =head2 ModNextExpected
1136
1137 ModNextExpected($subscriptionid,$date)
1138
1139 Update the planneddate for the current expected issue of the subscription.
1140 This will modify all future prediction results.  
1141
1142 C<$date> is a C4::Dates object.
1143
1144 returns 0
1145
1146 =cut
1147
1148 sub ModNextExpected($$) {
1149     my ( $subscriptionid, $date ) = @_;
1150     my $dbh = C4::Context->dbh;
1151
1152     #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1153     my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1154
1155     # Each subscription has only one 'expected' issue, with serial.status==1.
1156     $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1157     return 0;
1158
1159 }
1160
1161 =head2 ModSubscription
1162
1163 this function modifies a subscription. Put all new values on input args.
1164 returns the number of rows affected
1165
1166 =cut
1167
1168 sub ModSubscription {
1169     my ($auser,           $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $startdate,   $periodicity,   $firstacquidate,
1170         $dow,             $irregularity,    $numberpattern,     $numberlength,     $weeklength,    $monthlength, $add1,          $every1,
1171         $whenmorethan1,   $setto1,          $lastvalue1,        $innerloop1,       $add2,          $every2,      $whenmorethan2, $setto2,
1172         $lastvalue2,      $innerloop2,      $add3,              $every3,           $whenmorethan3, $setto3,      $lastvalue3,    $innerloop3,
1173         $numberingmethod, $status,          $biblionumber,      $callnumber,       $notes,         $letter,      $hemisphere,    $manualhistory,
1174         $internalnotes,   $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,    $enddate,       $subscriptionid
1175     ) = @_;
1176
1177     #     warn $irregularity;
1178     my $dbh   = C4::Context->dbh;
1179     my $query = "UPDATE subscription
1180                     SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1181                         periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1182                         add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1183                         add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1184                         add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1185                         numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?, 
1186                                                 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1187                                                 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1188                                                 ,enddate=?
1189                     WHERE subscriptionid = ?";
1190
1191     #warn "query :".$query;
1192     my $sth = $dbh->prepare($query);
1193     $sth->execute(
1194         $auser,           $branchcode,     $aqbooksellerid, $cost,
1195         $aqbudgetid,      $startdate,      $periodicity,    $firstacquidate,
1196         $dow,             "$irregularity", $numberpattern,  $numberlength,
1197         $weeklength,      $monthlength,    $add1,           $every1,
1198         $whenmorethan1,   $setto1,         $lastvalue1,     $innerloop1,
1199         $add2,            $every2,         $whenmorethan2,  $setto2,
1200         $lastvalue2,      $innerloop2,     $add3,           $every3,
1201         $whenmorethan3,   $setto3,         $lastvalue3,     $innerloop3,
1202         $numberingmethod, $status,         $biblionumber,   $callnumber,
1203         $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1204         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1205         $graceperiod,   $location,        $enddate,           $subscriptionid
1206     );
1207     my $rows = $sth->rows;
1208
1209     logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1210     return $rows;
1211 }
1212
1213 =head2 NewSubscription
1214
1215 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1216     $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1217     $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1218     $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1219     $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1220     $numberingmethod, $status, $notes, $serialsadditems,
1221     $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1222
1223 Create a new subscription with value given on input args.
1224
1225 return :
1226 the id of this new subscription
1227
1228 =cut
1229
1230 sub NewSubscription {
1231     my ($auser,         $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $biblionumber, $startdate,       $periodicity,
1232         $dow,           $numberlength,    $weeklength,        $monthlength,      $add1,          $every1,       $whenmorethan1,   $setto1,
1233         $lastvalue1,    $innerloop1,      $add2,              $every2,           $whenmorethan2, $setto2,       $lastvalue2,      $innerloop2,
1234         $add3,          $every3,          $whenmorethan3,     $setto3,           $lastvalue3,    $innerloop3,   $numberingmethod, $status,
1235         $notes,         $letter,          $firstacquidate,    $irregularity,     $numberpattern, $callnumber,   $hemisphere,      $manualhistory,
1236         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,     $enddate
1237     ) = @_;
1238     my $dbh = C4::Context->dbh;
1239
1240     #save subscription (insert into database)
1241     my $query = qq|
1242         INSERT INTO subscription
1243             (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1244             startdate,periodicity,dow,numberlength,weeklength,monthlength,
1245             add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1246             add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1247             add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1248             numberingmethod, status, notes, letter,firstacquidate,irregularity,
1249             numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1250             staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1251         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1252         |;
1253     my $sth = $dbh->prepare($query);
1254     $sth->execute(
1255         $auser,         $branchcode,      $aqbooksellerid,    $cost,             $aqbudgetid,    $biblionumber, $startdate,       $periodicity,
1256         $dow,           $numberlength,    $weeklength,        $monthlength,      $add1,          $every1,       $whenmorethan1,   $setto1,
1257         $lastvalue1,    $innerloop1,      $add2,              $every2,           $whenmorethan2, $setto2,       $lastvalue2,      $innerloop2,
1258         $add3,          $every3,          $whenmorethan3,     $setto3,           $lastvalue3,    $innerloop3,   $numberingmethod, "$status",
1259         $notes,         $letter,          $firstacquidate,    $irregularity,     $numberpattern, $callnumber,   $hemisphere,      $manualhistory,
1260         $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,   $location,     $enddate
1261     );
1262
1263     my $subscriptionid = $dbh->{'mysql_insertid'};
1264     unless ($enddate){
1265        $enddate = GetExpirationDate($subscriptionid,$startdate);
1266         $query = q|
1267             UPDATE subscription
1268             SET    enddate=?
1269             WHERE  subscriptionid=?
1270         |;
1271         $sth = $dbh->prepare($query);
1272         $sth->execute( $enddate, $subscriptionid );
1273     }
1274     #then create the 1st waited number
1275     $query = qq(
1276         INSERT INTO subscriptionhistory
1277             (biblionumber, subscriptionid, histstartdate,  opacnote, librariannote)
1278         VALUES (?,?,?,?,?)
1279         );
1280     $sth = $dbh->prepare($query);
1281     $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1282
1283     # reread subscription to get a hash (for calculation of the 1st issue number)
1284     $query = qq(
1285         SELECT *
1286         FROM   subscription
1287         WHERE  subscriptionid = ?
1288     );
1289     $sth = $dbh->prepare($query);
1290     $sth->execute($subscriptionid);
1291     my $val = $sth->fetchrow_hashref;
1292
1293     # calculate issue number
1294     my $serialseq = GetSeq($val);
1295     $query = qq|
1296         INSERT INTO serial
1297             (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1298         VALUES (?,?,?,?,?,?)
1299     |;
1300     $sth = $dbh->prepare($query);
1301     $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1302
1303     logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1304
1305     #set serial flag on biblio if not already set.
1306     my ( $null, ($bib) ) = GetBiblio($biblionumber);
1307     if ( !$bib->{'serial'} ) {
1308         my $record = GetMarcBiblio($biblionumber);
1309         my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1310         if ($tag) {
1311             eval { $record->field($tag)->update( $subf => 1 ); };
1312         }
1313         ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1314     }
1315     return $subscriptionid;
1316 }
1317
1318 =head2 ReNewSubscription
1319
1320 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1321
1322 this function renew a subscription with values given on input args.
1323
1324 =cut
1325
1326 sub ReNewSubscription {
1327     my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1328     my $dbh          = C4::Context->dbh;
1329     my $subscription = GetSubscription($subscriptionid);
1330     my $query        = qq|
1331          SELECT *
1332          FROM   biblio 
1333          LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1334          WHERE    biblio.biblionumber=?
1335      |;
1336     my $sth = $dbh->prepare($query);
1337     $sth->execute( $subscription->{biblionumber} );
1338     my $biblio = $sth->fetchrow_hashref;
1339
1340     if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1341
1342         NewSuggestion(
1343             {   'suggestedby'   => $user,
1344                 'title'         => $subscription->{bibliotitle},
1345                 'author'        => $biblio->{author},
1346                 'publishercode' => $biblio->{publishercode},
1347                 'note'          => $biblio->{note},
1348                 'biblionumber'  => $subscription->{biblionumber}
1349             }
1350         );
1351     }
1352
1353     # renew subscription
1354     $query = qq|
1355         UPDATE subscription
1356         SET    startdate=?,numberlength=?,weeklength=?,monthlength=?
1357         WHERE  subscriptionid=?
1358     |;
1359     $sth = $dbh->prepare($query);
1360     $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1361     my $enddate = GetExpirationDate($subscriptionid);
1362         $debug && warn "enddate :$enddate";
1363     $query = qq|
1364         UPDATE subscription
1365         SET    enddate=?
1366         WHERE  subscriptionid=?
1367     |;
1368     $sth = $dbh->prepare($query);
1369     $sth->execute( $enddate, $subscriptionid );
1370     $query = qq|
1371         UPDATE subscriptionhistory
1372         SET    histenddate=?
1373         WHERE  subscriptionid=?
1374     |;
1375     $sth = $dbh->prepare($query);
1376     $sth->execute( $enddate, $subscriptionid );
1377
1378     logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1379     return;
1380 }
1381
1382 =head2 NewIssue
1383
1384 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate,  $notes)
1385
1386 Create a new issue stored on the database.
1387 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1388 returns the serial id
1389
1390 =cut
1391
1392 sub NewIssue {
1393     my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1394     ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1395
1396     my $dbh   = C4::Context->dbh;
1397     my $query = qq|
1398         INSERT INTO serial
1399             (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1400         VALUES (?,?,?,?,?,?,?)
1401     |;
1402     my $sth = $dbh->prepare($query);
1403     $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1404     my $serialid = $dbh->{'mysql_insertid'};
1405     $query = qq|
1406         SELECT missinglist,recievedlist
1407         FROM   subscriptionhistory
1408         WHERE  subscriptionid=?
1409     |;
1410     $sth = $dbh->prepare($query);
1411     $sth->execute($subscriptionid);
1412     my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1413
1414     if ( $status == 2 ) {
1415       ### TODO Add a feature that improves recognition and description.
1416       ### As such count (serialseq) i.e. : N18,2(N19),N20
1417       ### Would use substr and index But be careful to previous presence of ()
1418         $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1419     }
1420     if ( $status == 4 ) {
1421         $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1422     }
1423     $query = qq|
1424         UPDATE subscriptionhistory
1425         SET    recievedlist=?, missinglist=?
1426         WHERE  subscriptionid=?
1427     |;
1428     $sth = $dbh->prepare($query);
1429     $recievedlist =~ s/^; //;
1430     $missinglist  =~ s/^; //;
1431     $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1432     return $serialid;
1433 }
1434
1435 =head2 ItemizeSerials
1436
1437 ItemizeSerials($serialid, $info);
1438 $info is a hashref containing  barcode branch, itemcallnumber, status, location
1439 $serialid the serialid
1440 return :
1441 1 if the itemize is a succes.
1442 0 and @error otherwise. @error containts the list of errors found.
1443
1444 =cut
1445
1446 sub ItemizeSerials {
1447     my ( $serialid, $info ) = @_;
1448     my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1449
1450     my $dbh   = C4::Context->dbh;
1451     my $query = qq|
1452         SELECT *
1453         FROM   serial
1454         WHERE  serialid=?
1455     |;
1456     my $sth = $dbh->prepare($query);
1457     $sth->execute($serialid);
1458     my $data = $sth->fetchrow_hashref;
1459     if ( C4::Context->preference("RoutingSerials") ) {
1460
1461         # check for existing biblioitem relating to serial issue
1462         my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1463         my $bibitemno = 0;
1464         for ( my $i = 0 ; $i < $count ; $i++ ) {
1465             if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1466                 $bibitemno = $results[$i]->{'biblioitemnumber'};
1467                 last;
1468             }
1469         }
1470         if ( $bibitemno == 0 ) {
1471             my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1472             $sth->execute( $data->{'biblionumber'} );
1473             my $biblioitem = $sth->fetchrow_hashref;
1474             $biblioitem->{'volumedate'}  = $data->{planneddate};
1475             $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1476             $biblioitem->{'dewey'}       = $info->{itemcallnumber};
1477         }
1478     }
1479
1480     my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1481     if ( $info->{barcode} ) {
1482         my @errors;
1483         if ( is_barcode_in_use( $info->{barcode} ) ) {
1484             push @errors, 'barcode_not_unique';
1485         } else {
1486             my $marcrecord = MARC::Record->new();
1487             my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1488             my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1489             $marcrecord->insert_fields_ordered($newField);
1490             if ( $info->{branch} ) {
1491                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1492
1493                 #warn "items.homebranch : $tag , $subfield";
1494                 if ( $marcrecord->field($tag) ) {
1495                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1496                 } else {
1497                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1498                     $marcrecord->insert_fields_ordered($newField);
1499                 }
1500                 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1501
1502                 #warn "items.holdingbranch : $tag , $subfield";
1503                 if ( $marcrecord->field($tag) ) {
1504                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1505                 } else {
1506                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1507                     $marcrecord->insert_fields_ordered($newField);
1508                 }
1509             }
1510             if ( $info->{itemcallnumber} ) {
1511                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1512
1513                 if ( $marcrecord->field($tag) ) {
1514                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1515                 } else {
1516                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1517                     $marcrecord->insert_fields_ordered($newField);
1518                 }
1519             }
1520             if ( $info->{notes} ) {
1521                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1522
1523                 if ( $marcrecord->field($tag) ) {
1524                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1525                 } else {
1526                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1527                     $marcrecord->insert_fields_ordered($newField);
1528                 }
1529             }
1530             if ( $info->{location} ) {
1531                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1532
1533                 if ( $marcrecord->field($tag) ) {
1534                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1535                 } else {
1536                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1537                     $marcrecord->insert_fields_ordered($newField);
1538                 }
1539             }
1540             if ( $info->{status} ) {
1541                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1542
1543                 if ( $marcrecord->field($tag) ) {
1544                     $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1545                 } else {
1546                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1547                     $marcrecord->insert_fields_ordered($newField);
1548                 }
1549             }
1550             if ( C4::Context->preference("RoutingSerials") ) {
1551                 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1552                 if ( $marcrecord->field($tag) ) {
1553                     $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1554                 } else {
1555                     my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1556                     $marcrecord->insert_fields_ordered($newField);
1557                 }
1558             }
1559             AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1560             return 1;
1561         }
1562         return ( 0, @errors );
1563     }
1564 }
1565
1566 =head2 HasSubscriptionStrictlyExpired
1567
1568 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1569
1570 the subscription has stricly expired when today > the end subscription date 
1571
1572 return :
1573 1 if true, 0 if false, -1 if the expiration date is not set.
1574
1575 =cut
1576
1577 sub HasSubscriptionStrictlyExpired {
1578
1579     # Getting end of subscription date
1580     my ($subscriptionid) = @_;
1581     my $dbh              = C4::Context->dbh;
1582     my $subscription     = GetSubscription($subscriptionid);
1583     my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1584
1585     # If the expiration date is set
1586     if ( $expirationdate != 0 ) {
1587         my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1588
1589         # Getting today's date
1590         my ( $nowyear, $nowmonth, $nowday ) = Today();
1591
1592         # if today's date > expiration date, then the subscription has stricly expired
1593         if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1594             return 1;
1595         } else {
1596             return 0;
1597         }
1598     } else {
1599
1600         # There are some cases where the expiration date is not set
1601         # As we can't determine if the subscription has expired on a date-basis,
1602         # we return -1;
1603         return -1;
1604     }
1605 }
1606
1607 =head2 HasSubscriptionExpired
1608
1609 $has_expired = HasSubscriptionExpired($subscriptionid)
1610
1611 the subscription has expired when the next issue to arrive is out of subscription limit.
1612
1613 return :
1614 0 if the subscription has not expired
1615 1 if the subscription has expired
1616 2 if has subscription does not have a valid expiration date set
1617
1618 =cut
1619
1620 sub HasSubscriptionExpired {
1621     my ($subscriptionid) = @_;
1622     my $dbh              = C4::Context->dbh;
1623     my $subscription     = GetSubscription($subscriptionid);
1624     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1625         my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1626         if (!defined $expirationdate) {
1627             $expirationdate = q{};
1628         }
1629         my $query          = qq|
1630             SELECT max(planneddate)
1631             FROM   serial
1632             WHERE  subscriptionid=?
1633       |;
1634         my $sth = $dbh->prepare($query);
1635         $sth->execute($subscriptionid);
1636         my ($res) = $sth->fetchrow;
1637         if (!$res || $res=~m/^0000/) {
1638             return 0;
1639         }
1640         my @res                   = split( /-/, $res );
1641         my @endofsubscriptiondate = split( /-/, $expirationdate );
1642         return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1643         return 1
1644           if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1645             || ( !$res ) );
1646         return 0;
1647     } else {
1648         if ( $subscription->{'numberlength'} ) {
1649             my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1650             return 1 if ( $countreceived > $subscription->{'numberlength'} );
1651             return 0;
1652         } else {
1653             return 0;
1654         }
1655     }
1656     return 0;    # Notice that you'll never get here.
1657 }
1658
1659 =head2 SetDistributedto
1660
1661 SetDistributedto($distributedto,$subscriptionid);
1662 This function update the value of distributedto for a subscription given on input arg.
1663
1664 =cut
1665
1666 sub SetDistributedto {
1667     my ( $distributedto, $subscriptionid ) = @_;
1668     my $dbh   = C4::Context->dbh;
1669     my $query = qq|
1670         UPDATE subscription
1671         SET    distributedto=?
1672         WHERE  subscriptionid=?
1673     |;
1674     my $sth = $dbh->prepare($query);
1675     $sth->execute( $distributedto, $subscriptionid );
1676     return;
1677 }
1678
1679 =head2 DelSubscription
1680
1681 DelSubscription($subscriptionid)
1682 this function deletes subscription which has $subscriptionid as id.
1683
1684 =cut
1685
1686 sub DelSubscription {
1687     my ($subscriptionid) = @_;
1688     my $dbh = C4::Context->dbh;
1689     $subscriptionid = $dbh->quote($subscriptionid);
1690     $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1691     $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1692     $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1693
1694     logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1695 }
1696
1697 =head2 DelIssue
1698
1699 DelIssue($serialseq,$subscriptionid)
1700 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1701
1702 returns the number of rows affected
1703
1704 =cut
1705
1706 sub DelIssue {
1707     my ($dataissue) = @_;
1708     my $dbh = C4::Context->dbh;
1709     ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1710
1711     my $query = qq|
1712         DELETE FROM serial
1713         WHERE       serialid= ?
1714         AND         subscriptionid= ?
1715     |;
1716     my $mainsth = $dbh->prepare($query);
1717     $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1718
1719     #Delete element from subscription history
1720     $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1721     my $sth = $dbh->prepare($query);
1722     $sth->execute( $dataissue->{'subscriptionid'} );
1723     my $val = $sth->fetchrow_hashref;
1724     unless ( $val->{manualhistory} ) {
1725         my $query = qq|
1726           SELECT * FROM subscriptionhistory
1727           WHERE       subscriptionid= ?
1728       |;
1729         my $sth = $dbh->prepare($query);
1730         $sth->execute( $dataissue->{'subscriptionid'} );
1731         my $data      = $sth->fetchrow_hashref;
1732         my $serialseq = $dataissue->{'serialseq'};
1733         $data->{'missinglist'}  =~ s/\b$serialseq\b//;
1734         $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1735         my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1736         $sth = $dbh->prepare($strsth);
1737         $sth->execute( $dataissue->{'subscriptionid'} );
1738     }
1739
1740     return $mainsth->rows;
1741 }
1742
1743 =head2 GetLateOrMissingIssues
1744
1745 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1746
1747 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1748
1749 return :
1750 the issuelist as an array of hash refs. Each element of this array contains 
1751 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1752
1753 =cut
1754
1755 sub GetLateOrMissingIssues {
1756     my ( $supplierid, $serialid, $order ) = @_;
1757     my $dbh = C4::Context->dbh;
1758     my $sth;
1759     my $byserial = '';
1760     if ($serialid) {
1761         $byserial = "and serialid = " . $serialid;
1762     }
1763     if ($order) {
1764         $order .= ", title";
1765     } else {
1766         $order = "title";
1767     }
1768     if ($supplierid) {
1769         $sth = $dbh->prepare(
1770             "SELECT
1771                 serialid,      aqbooksellerid,        name,
1772                 biblio.title,  planneddate,           serialseq,
1773                 serial.status, serial.subscriptionid, claimdate,
1774                 subscription.branchcode
1775             FROM      serial 
1776                 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
1777                 LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
1778                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1779                 WHERE subscription.subscriptionid = serial.subscriptionid 
1780                 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1781                 AND subscription.aqbooksellerid=$supplierid
1782                 $byserial
1783                 ORDER BY $order"
1784         );
1785     } else {
1786         $sth = $dbh->prepare(
1787             "SELECT 
1788             serialid,      aqbooksellerid,         name,
1789             biblio.title,  planneddate,           serialseq,
1790                 serial.status, serial.subscriptionid, claimdate,
1791                 subscription.branchcode
1792             FROM serial 
1793                 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid 
1794                 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1795                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1796                 WHERE subscription.subscriptionid = serial.subscriptionid 
1797                         AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1798                 $byserial
1799                 ORDER BY $order"
1800         );
1801     }
1802     $sth->execute;
1803     my @issuelist;
1804     while ( my $line = $sth->fetchrow_hashref ) {
1805
1806         if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1807             $line->{planneddate} = format_date( $line->{planneddate} );
1808         }
1809         if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1810             $line->{claimdate}   = format_date( $line->{claimdate} );
1811         }
1812         $line->{"status".$line->{status}}   = 1;
1813         push @issuelist, $line;
1814     }
1815     return @issuelist;
1816 }
1817
1818 =head2 removeMissingIssue
1819
1820 removeMissingIssue($subscriptionid)
1821
1822 this function removes an issue from being part of the missing string in 
1823 subscriptionlist.missinglist column
1824
1825 called when a missing issue is found from the serials-recieve.pl file
1826
1827 =cut
1828
1829 sub removeMissingIssue {
1830     my ( $sequence, $subscriptionid ) = @_;
1831     my $dbh = C4::Context->dbh;
1832     my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1833     $sth->execute($subscriptionid);
1834     my $data              = $sth->fetchrow_hashref;
1835     my $missinglist       = $data->{'missinglist'};
1836     my $missinglistbefore = $missinglist;
1837
1838     # warn $missinglist." before";
1839     $missinglist =~ s/($sequence)//;
1840
1841     # warn $missinglist." after";
1842     if ( $missinglist ne $missinglistbefore ) {
1843         $missinglist =~ s/\|\s\|/\|/g;
1844         $missinglist =~ s/^\| //g;
1845         $missinglist =~ s/\|$//g;
1846         my $sth2 = $dbh->prepare(
1847             "UPDATE subscriptionhistory
1848                     SET missinglist = ?
1849                     WHERE subscriptionid = ?"
1850         );
1851         $sth2->execute( $missinglist, $subscriptionid );
1852     }
1853     return;
1854 }
1855
1856 =head2 updateClaim
1857
1858 &updateClaim($serialid)
1859
1860 this function updates the time when a claim is issued for late/missing items
1861
1862 called from claims.pl file
1863
1864 =cut
1865
1866 sub updateClaim {
1867     my ($serialid) = @_;
1868     my $dbh        = C4::Context->dbh;
1869     my $sth        = $dbh->prepare(
1870         "UPDATE serial SET claimdate = now()
1871                 WHERE serialid = ?
1872         "
1873     );
1874     $sth->execute($serialid);
1875     return;
1876 }
1877
1878 =head2 getsupplierbyserialid
1879
1880 $result = getsupplierbyserialid($serialid)
1881
1882 this function is used to find the supplier id given a serial id
1883
1884 return :
1885 hashref containing serialid, subscriptionid, and aqbooksellerid
1886
1887 =cut
1888
1889 sub getsupplierbyserialid {
1890     my ($serialid) = @_;
1891     my $dbh        = C4::Context->dbh;
1892     my $sth        = $dbh->prepare(
1893         "SELECT serialid, serial.subscriptionid, aqbooksellerid
1894          FROM serial 
1895             LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1896             WHERE serialid = ?
1897         "
1898     );
1899     $sth->execute($serialid);
1900     my $line   = $sth->fetchrow_hashref;
1901     my $result = $line->{'aqbooksellerid'};
1902     return $result;
1903 }
1904
1905 =head2 check_routing
1906
1907 $result = &check_routing($subscriptionid)
1908
1909 this function checks to see if a serial has a routing list and returns the count of routingid
1910 used to show either an 'add' or 'edit' link
1911
1912 =cut
1913
1914 sub check_routing {
1915     my ($subscriptionid) = @_;
1916     my $dbh              = C4::Context->dbh;
1917     my $sth              = $dbh->prepare(
1918         "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist 
1919                               ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1920                               WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1921                               "
1922     );
1923     $sth->execute($subscriptionid);
1924     my $line   = $sth->fetchrow_hashref;
1925     my $result = $line->{'routingids'};
1926     return $result;
1927 }
1928
1929 =head2 addroutingmember
1930
1931 addroutingmember($borrowernumber,$subscriptionid)
1932
1933 this function takes a borrowernumber and subscriptionid and adds the member to the
1934 routing list for that serial subscription and gives them a rank on the list
1935 of either 1 or highest current rank + 1
1936
1937 =cut
1938
1939 sub addroutingmember {
1940     my ( $borrowernumber, $subscriptionid ) = @_;
1941     my $rank;
1942     my $dbh = C4::Context->dbh;
1943     my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1944     $sth->execute($subscriptionid);
1945     while ( my $line = $sth->fetchrow_hashref ) {
1946         if ( $line->{'rank'} > 0 ) {
1947             $rank = $line->{'rank'} + 1;
1948         } else {
1949             $rank = 1;
1950         }
1951     }
1952     $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1953     $sth->execute( $subscriptionid, $borrowernumber, $rank );
1954 }
1955
1956 =head2 reorder_members
1957
1958 reorder_members($subscriptionid,$routingid,$rank)
1959
1960 this function is used to reorder the routing list
1961
1962 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1963 - it gets all members on list puts their routingid's into an array
1964 - removes the one in the array that is $routingid
1965 - then reinjects $routingid at point indicated by $rank
1966 - then update the database with the routingids in the new order
1967
1968 =cut
1969
1970 sub reorder_members {
1971     my ( $subscriptionid, $routingid, $rank ) = @_;
1972     my $dbh = C4::Context->dbh;
1973     my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1974     $sth->execute($subscriptionid);
1975     my @result;
1976     while ( my $line = $sth->fetchrow_hashref ) {
1977         push( @result, $line->{'routingid'} );
1978     }
1979
1980     # To find the matching index
1981     my $i;
1982     my $key = -1;    # to allow for 0 being a valid response
1983     for ( $i = 0 ; $i < @result ; $i++ ) {
1984         if ( $routingid == $result[$i] ) {
1985             $key = $i;    # save the index
1986             last;
1987         }
1988     }
1989
1990     # if index exists in array then move it to new position
1991     if ( $key > -1 && $rank > 0 ) {
1992         my $new_rank = $rank - 1;                       # $new_rank is what you want the new index to be in the array
1993         my $moving_item = splice( @result, $key, 1 );
1994         splice( @result, $new_rank, 0, $moving_item );
1995     }
1996     for ( my $j = 0 ; $j < @result ; $j++ ) {
1997         my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1998         $sth->execute;
1999     }
2000     return;
2001 }
2002
2003 =head2 delroutingmember
2004
2005 delroutingmember($routingid,$subscriptionid)
2006
2007 this function either deletes one member from routing list if $routingid exists otherwise
2008 deletes all members from the routing list
2009
2010 =cut
2011
2012 sub delroutingmember {
2013
2014     # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2015     my ( $routingid, $subscriptionid ) = @_;
2016     my $dbh = C4::Context->dbh;
2017     if ($routingid) {
2018         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2019         $sth->execute($routingid);
2020         reorder_members( $subscriptionid, $routingid );
2021     } else {
2022         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2023         $sth->execute($subscriptionid);
2024     }
2025     return;
2026 }
2027
2028 =head2 getroutinglist
2029
2030 ($count,@routinglist) = getroutinglist($subscriptionid)
2031
2032 this gets the info from the subscriptionroutinglist for $subscriptionid
2033
2034 return :
2035 a count of the number of members on routinglist
2036 the routinglist as an array. Each element of the array contains a hash_ref containing
2037 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2038
2039 =cut
2040
2041 sub getroutinglist {
2042     my ($subscriptionid) = @_;
2043     my $dbh              = C4::Context->dbh;
2044     my $sth              = $dbh->prepare(
2045         "SELECT routingid, borrowernumber, ranking, biblionumber 
2046             FROM subscription 
2047             JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2048             WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2049                               "
2050     );
2051     $sth->execute($subscriptionid);
2052     my @routinglist;
2053     my $count = 0;
2054     while ( my $line = $sth->fetchrow_hashref ) {
2055         $count++;
2056         push( @routinglist, $line );
2057     }
2058     return ( $count, @routinglist );
2059 }
2060
2061 =head2 countissuesfrom
2062
2063 $result = countissuesfrom($subscriptionid,$startdate)
2064
2065 Returns a count of serial rows matching the given subsctiptionid
2066 with published date greater than startdate
2067
2068 =cut
2069
2070 sub countissuesfrom {
2071     my ( $subscriptionid, $startdate ) = @_;
2072     my $dbh   = C4::Context->dbh;
2073     my $query = qq|
2074             SELECT count(*)
2075             FROM   serial
2076             WHERE  subscriptionid=?
2077             AND serial.publisheddate>?
2078         |;
2079     my $sth = $dbh->prepare($query);
2080     $sth->execute( $subscriptionid, $startdate );
2081     my ($countreceived) = $sth->fetchrow;
2082     return $countreceived;
2083 }
2084
2085 =head2 CountIssues
2086
2087 $result = CountIssues($subscriptionid)
2088
2089 Returns a count of serial rows matching the given subsctiptionid
2090
2091 =cut
2092
2093 sub CountIssues {
2094     my ($subscriptionid) = @_;
2095     my $dbh              = C4::Context->dbh;
2096     my $query            = qq|
2097             SELECT count(*)
2098             FROM   serial
2099             WHERE  subscriptionid=?
2100         |;
2101     my $sth = $dbh->prepare($query);
2102     $sth->execute($subscriptionid);
2103     my ($countreceived) = $sth->fetchrow;
2104     return $countreceived;
2105 }
2106
2107 =head2 HasItems
2108
2109 $result = HasItems($subscriptionid)
2110
2111 returns a count of items from serial matching the subscriptionid
2112
2113 =cut
2114
2115 sub HasItems {
2116     my ($subscriptionid) = @_;
2117     my $dbh              = C4::Context->dbh;
2118     my $query = q|
2119             SELECT COUNT(serialitems.itemnumber)
2120             FROM   serial 
2121                         LEFT JOIN serialitems USING(serialid)
2122             WHERE  subscriptionid=? AND serialitems.serialid IS NOT NULL
2123         |;
2124     my $sth=$dbh->prepare($query);
2125     $sth->execute($subscriptionid);
2126     my ($countitems)=$sth->fetchrow_array();
2127     return $countitems;  
2128 }
2129
2130 =head2 abouttoexpire
2131
2132 $result = abouttoexpire($subscriptionid)
2133
2134 this function alerts you to the penultimate issue for a serial subscription
2135
2136 returns 1 - if this is the penultimate issue
2137 returns 0 - if not
2138
2139 =cut
2140
2141 sub abouttoexpire {
2142     my ($subscriptionid) = @_;
2143     my $dbh              = C4::Context->dbh;
2144     my $subscription     = GetSubscription($subscriptionid);
2145     my $per = $subscription->{'periodicity'};
2146     if ($per && $per % 16 > 0){
2147         my $expirationdate   = GetExpirationDate($subscriptionid);
2148         my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2149         my @res;
2150         if (defined $res) {
2151             @res=split (/-/,$res);
2152             @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2153         } else { # default an undefined value
2154             @res=Date::Calc::Today;
2155         }
2156         my @endofsubscriptiondate=split(/-/,$expirationdate);
2157         my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2158         my @datebeforeend;
2159         @datebeforeend = Add_Delta_Days(  $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2160             - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2161         return 1 if ( @res &&
2162             (@datebeforeend &&
2163                 Delta_Days($res[0],$res[1],$res[2],
2164                     $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2165             (@endofsubscriptiondate &&
2166                 Delta_Days($res[0],$res[1],$res[2],
2167                     $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2168         return 0;
2169     } elsif ($subscription->{numberlength}>0) {
2170         return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2171     }
2172     return 0;
2173 }
2174
2175 sub in_array {    # used in next sub down
2176     my ( $val, @elements ) = @_;
2177     foreach my $elem (@elements) {
2178         if ( $val == $elem ) {
2179             return 1;
2180         }
2181     }
2182     return 0;
2183 }
2184
2185 =head2 GetNextDate
2186
2187 $resultdate = GetNextDate($planneddate,$subscription)
2188
2189 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2190 exists an irregularity
2191 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be 
2192 skipped then the returned date will be 2007-05-10
2193
2194 return :
2195 $resultdate - then next date in the sequence
2196
2197 Return 0 if periodicity==0
2198
2199 =cut
2200
2201 sub GetNextDate(@) {
2202     my ( $planneddate, $subscription ) = @_;
2203     my @irreg = split( /\,/, $subscription->{irregularity} );
2204
2205     #date supposed to be in ISO.
2206
2207     my ( $year, $month, $day ) = split( /-/, $planneddate );
2208     $month = 1 unless ($month);
2209     $day   = 1 unless ($day);
2210     my @resultdate;
2211
2212     #       warn "DOW $dayofweek";
2213     if ( $subscription->{periodicity} % 16 == 0 ) {    # 'without regularity' || 'irregular'
2214         return 0;
2215     }
2216
2217     #   daily : n / week
2218     #   Since we're interpreting irregularity here as which days of the week to skip an issue,
2219     #   renaming this pattern from 1/day to " n / week ".
2220     if ( $subscription->{periodicity} == 1 ) {
2221         my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2222         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2223         else {
2224             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2225                 $dayofweek = 0 if ( $dayofweek == 7 );
2226                 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2227                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2228                     $dayofweek++;
2229                 }
2230             }
2231             @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2232         }
2233     }
2234
2235     #   1  week
2236     if ( $subscription->{periodicity} == 2 ) {
2237         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2238         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2239         else {
2240             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2241
2242                 #FIXME: if two consecutive irreg, do we only skip one?
2243                 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2244                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2245                     $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2246                 }
2247             }
2248             @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2249         }
2250     }
2251
2252     #   1 / 2 weeks
2253     if ( $subscription->{periodicity} == 3 ) {
2254         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2255         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2256         else {
2257             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2258                 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2259                     ### BUGFIX was previously +1 ^
2260                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2261                     $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2262                 }
2263             }
2264             @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2265         }
2266     }
2267
2268     #   1 / 3 weeks
2269     if ( $subscription->{periodicity} == 4 ) {
2270         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2271         if ($@) { warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2272         else {
2273             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2274                 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2275                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2276                     $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2277                 }
2278             }
2279             @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2280         }
2281     }
2282     my $tmpmonth = $month;
2283     if ( $year && $month && $day ) {
2284         if ( $subscription->{periodicity} == 5 ) {
2285             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2286                 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2287                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2288                     $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2289                 }
2290             }
2291             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2292         }
2293         if ( $subscription->{periodicity} == 6 ) {
2294             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2295                 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2296                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2297                     $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2298                 }
2299             }
2300             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2301         }
2302         if ( $subscription->{periodicity} == 7 ) {
2303             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2304                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2305                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2306                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2307                 }
2308             }
2309             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2310         }
2311         if ( $subscription->{periodicity} == 8 ) {
2312             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2313                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2314                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2315                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2316                 }
2317             }
2318             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2319         }
2320         if ( $subscription->{periodicity} == 13 ) {
2321             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2322                 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2323                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2324                     $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2325                 }
2326             }
2327             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2328         }
2329         if ( $subscription->{periodicity} == 9 ) {
2330             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2331                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2332                     ### BUFIX Seems to need more Than One ?
2333                     ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2334                     $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2335                 }
2336             }
2337             @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2338         }
2339         if ( $subscription->{periodicity} == 10 ) {
2340             @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2341         }
2342         if ( $subscription->{periodicity} == 11 ) {
2343             @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2344         }
2345     }
2346     my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2347
2348     return "$resultdate";
2349 }
2350
2351 =head2 is_barcode_in_use
2352
2353 Returns number of occurence of the barcode in the items table
2354 Can be used as a boolean test of whether the barcode has
2355 been deployed as yet
2356
2357 =cut
2358
2359 sub is_barcode_in_use {
2360     my $barcode = shift;
2361     my $dbh       = C4::Context->dbh;
2362     my $occurences = $dbh->selectall_arrayref(
2363         'SELECT itemnumber from items where barcode = ?',
2364         {}, $barcode
2365
2366     );
2367
2368     return @{$occurences};
2369 }
2370
2371 1;
2372 __END__
2373
2374 =head1 AUTHOR
2375
2376 Koha Development Team <http://koha-community.org/>
2377
2378 =cut