Merge remote-tracking branch 'origin/new/bug_8408'
[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::Biblio;
27 use C4::Log;    # logaction
28 use C4::Debug;
29
30 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
31
32 BEGIN {
33     $VERSION = 3.07.00.049;    # set version for version checking
34     require Exporter;
35     @ISA    = qw(Exporter);
36     @EXPORT = qw(
37       &NewSubscription    &ModSubscription    &DelSubscription    &GetSubscriptions
38       &GetSubscription    &CountSubscriptionFromBiblionumber      &GetSubscriptionsFromBiblionumber
39       &GetFullSubscriptionsFromBiblionumber   &GetFullSubscription &ModSubscriptionHistory
40       &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
41
42       &GetNextSeq         &NewIssue           &ItemizeSerials    &GetSerials
43       &GetLatestSerials   &ModSerialStatus    &GetNextDate       &GetSerials2
44       &ReNewSubscription  &GetLateIssues      &GetLateOrMissingIssues
45       &GetSerialInformation                   &AddItem2Serial
46       &PrepareSerialsData &GetNextExpected    &ModNextExpected
47
48       &UpdateClaimdateIssues
49       &GetSuppliersWithLateIssues             &getsupplierbyserialid
50       &GetDistributedTo   &SetDistributedTo
51       &getroutinglist     &delroutingmember   &addroutingmember
52       &reorder_members
53       &check_routing &updateClaim &removeMissingIssue
54       &CountIssues
55       HasItems
56       &GetSubscriptionsFromBorrower
57
58     );
59 }
60
61 =head1 NAME
62
63 C4::Serials - Serials Module Functions
64
65 =head1 SYNOPSIS
66
67   use C4::Serials;
68
69 =head1 DESCRIPTION
70
71 Functions for handling subscriptions, claims routing etc.
72
73
74 =head1 SUBROUTINES
75
76 =head2 GetSuppliersWithLateIssues
77
78 $supplierlist = GetSuppliersWithLateIssues()
79
80 this function get all suppliers with late issues.
81
82 return :
83 an array_ref of suppliers each entry is a hash_ref containing id and name
84 the array is in name order
85
86 =cut
87
88 sub GetSuppliersWithLateIssues {
89     my $dbh   = C4::Context->dbh;
90     my $query = qq|
91         SELECT DISTINCT id, name
92     FROM            subscription
93     LEFT JOIN       serial ON serial.subscriptionid=subscription.subscriptionid
94     LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
95     WHERE id > 0 AND ((planneddate < now() AND serial.status=1) OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
96     return $dbh->selectall_arrayref($query, { Slice => {} });
97 }
98
99 =head2 GetLateIssues
100
101 @issuelist = GetLateIssues($supplierid)
102
103 this function selects late issues from the database
104
105 return :
106 the issuelist as an array. Each element of this array contains a hashi_ref containing
107 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
108
109 =cut
110
111 sub GetLateIssues {
112     my ($supplierid) = @_;
113     my $dbh = C4::Context->dbh;
114     my $sth;
115     if ($supplierid) {
116         my $query = qq|
117             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
118             FROM       subscription
119             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
120             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
121             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
122             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
123             AND        subscription.aqbooksellerid=?
124             ORDER BY   title
125         |;
126         $sth = $dbh->prepare($query);
127         $sth->execute($supplierid);
128     } else {
129         my $query = qq|
130             SELECT     name,title,planneddate,serialseq,serial.subscriptionid
131             FROM       subscription
132             LEFT JOIN  serial ON subscription.subscriptionid = serial.subscriptionid
133             LEFT JOIN  biblio ON biblio.biblionumber = subscription.biblionumber
134             LEFT JOIN  aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
135             WHERE      ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
136             ORDER BY   title
137         |;
138         $sth = $dbh->prepare($query);
139         $sth->execute;
140     }
141     my @issuelist;
142     my $last_title;
143     my $odd   = 0;
144     while ( my $line = $sth->fetchrow_hashref ) {
145         $odd++ unless $line->{title} eq $last_title;
146         $line->{title} = "" if $line->{title} eq $last_title;
147         $last_title = $line->{title} if ( $line->{title} );
148         $line->{planneddate} = format_date( $line->{planneddate} );
149         push @issuelist, $line;
150     }
151     return @issuelist;
152 }
153
154 =head2 GetSubscriptionHistoryFromSubscriptionId
155
156 $sth = GetSubscriptionHistoryFromSubscriptionId()
157 this function prepares the SQL request and returns the statement handle
158 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
159
160 =cut
161
162 sub GetSubscriptionHistoryFromSubscriptionId() {
163     my $dbh   = C4::Context->dbh;
164     my $query = qq|
165         SELECT *
166         FROM   subscriptionhistory
167         WHERE  subscriptionid = ?
168     |;
169     return $dbh->prepare($query);
170 }
171
172 =head2 GetSerialStatusFromSerialId
173
174 $sth = GetSerialStatusFromSerialId();
175 this function returns a statement handle
176 After this function, don't forget to execute it by using $sth->execute($serialid)
177 return :
178 $sth = $dbh->prepare($query).
179
180 =cut
181
182 sub GetSerialStatusFromSerialId() {
183     my $dbh   = C4::Context->dbh;
184     my $query = qq|
185         SELECT status
186         FROM   serial
187         WHERE  serialid = ?
188     |;
189     return $dbh->prepare($query);
190 }
191
192 =head2 GetSerialInformation
193
194
195 $data = GetSerialInformation($serialid);
196 returns a hash_ref containing :
197   items : items marcrecord (can be an array)
198   serial table field
199   subscription table field
200   + information about subscription expiration
201
202 =cut
203
204 sub GetSerialInformation {
205     my ($serialid) = @_;
206     my $dbh        = C4::Context->dbh;
207     my $query      = qq|
208         SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
209     if (   C4::Context->preference('IndependantBranches')
210         && C4::Context->userenv
211         && C4::Context->userenv->{'flags'} != 1
212         && C4::Context->userenv->{'branch'} ) {
213         $query .= "
214       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
215     }
216     $query .= qq|             
217         FROM   serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
218         WHERE  serialid = ?
219     |;
220     my $rq = $dbh->prepare($query);
221     $rq->execute($serialid);
222     my $data = $rq->fetchrow_hashref;
223
224     # create item information if we have serialsadditems for this subscription
225     if ( $data->{'serialsadditems'} ) {
226         my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
227         $queryitem->execute($serialid);
228         my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
229         require C4::Items;
230         if ( scalar(@$itemnumbers) > 0 ) {
231             foreach my $itemnum (@$itemnumbers) {
232
233                 #It is ASSUMED that GetMarcItem ALWAYS WORK...
234                 #Maybe GetMarcItem should return values on failure
235                 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
236                 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
237                 $itemprocessed->{'itemnumber'}   = $itemnum->[0];
238                 $itemprocessed->{'itemid'}       = $itemnum->[0];
239                 $itemprocessed->{'serialid'}     = $serialid;
240                 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
241                 push @{ $data->{'items'} }, $itemprocessed;
242             }
243         } else {
244             my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
245             $itemprocessed->{'itemid'}       = "N$serialid";
246             $itemprocessed->{'serialid'}     = $serialid;
247             $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
248             $itemprocessed->{'countitems'}   = 0;
249             push @{ $data->{'items'} }, $itemprocessed;
250         }
251     }
252     $data->{ "status" . $data->{'serstatus'} } = 1;
253     $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
254     $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
255     return $data;
256 }
257
258 =head2 AddItem2Serial
259
260 $rows = AddItem2Serial($serialid,$itemnumber);
261 Adds an itemnumber to Serial record
262 returns the number of rows affected
263
264 =cut
265
266 sub AddItem2Serial {
267     my ( $serialid, $itemnumber ) = @_;
268     my $dbh = C4::Context->dbh;
269     my $rq  = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
270     $rq->execute( $serialid, $itemnumber );
271     return $rq->rows;
272 }
273
274 =head2 UpdateClaimdateIssues
275
276 UpdateClaimdateIssues($serialids,[$date]);
277
278 Update Claimdate for issues in @$serialids list with date $date
279 (Take Today if none)
280
281 =cut
282
283 sub UpdateClaimdateIssues {
284     my ( $serialids, $date ) = @_;
285     my $dbh = C4::Context->dbh;
286     $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
287     my $query = "
288         UPDATE serial SET claimdate = ?, status = 7
289         WHERE  serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
290     my $rq = $dbh->prepare($query);
291     $rq->execute($date, @$serialids);
292     return $rq->rows;
293 }
294
295 =head2 GetSubscription
296
297 $subs = GetSubscription($subscriptionid)
298 this function returns the subscription which has $subscriptionid as id.
299 return :
300 a hashref. This hash containts
301 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
302
303 =cut
304
305 sub GetSubscription {
306     my ($subscriptionid) = @_;
307     my $dbh              = C4::Context->dbh;
308     my $query            = qq(
309         SELECT  subscription.*,
310                 subscriptionhistory.*,
311                 aqbooksellers.name AS aqbooksellername,
312                 biblio.title AS bibliotitle,
313                 subscription.biblionumber as bibnum);
314     if (   C4::Context->preference('IndependantBranches')
315         && C4::Context->userenv
316         && C4::Context->userenv->{'flags'} != 1
317         && C4::Context->userenv->{'branch'} ) {
318         $query .= "
319       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
320     }
321     $query .= qq(             
322        FROM subscription
323        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
324        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
325        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
326        WHERE subscription.subscriptionid = ?
327     );
328
329     #     if (C4::Context->preference('IndependantBranches') &&
330     #         C4::Context->userenv &&
331     #         C4::Context->userenv->{'flags'} != 1){
332     # #       $debug and warn "flags: ".C4::Context->userenv->{'flags'};
333     #       $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
334     #     }
335     $debug and warn "query : $query\nsubsid :$subscriptionid";
336     my $sth = $dbh->prepare($query);
337     $sth->execute($subscriptionid);
338     return $sth->fetchrow_hashref;
339 }
340
341 =head2 GetFullSubscription
342
343    $array_ref = GetFullSubscription($subscriptionid)
344    this function reads the serial table.
345
346 =cut
347
348 sub GetFullSubscription {
349     my ($subscriptionid) = @_;
350     my $dbh              = C4::Context->dbh;
351     my $query            = qq|
352   SELECT    serial.serialid,
353             serial.serialseq,
354             serial.planneddate, 
355             serial.publisheddate, 
356             serial.status, 
357             serial.notes as notes,
358             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
359             aqbooksellers.name as aqbooksellername,
360             biblio.title as bibliotitle,
361             subscription.branchcode AS branchcode,
362             subscription.subscriptionid AS subscriptionid |;
363     if (   C4::Context->preference('IndependantBranches')
364         && C4::Context->userenv
365         && C4::Context->userenv->{'flags'} != 1
366         && C4::Context->userenv->{'branch'} ) {
367         $query .= "
368       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
369     }
370     $query .= qq|
371   FROM      serial 
372   LEFT JOIN subscription ON 
373           (serial.subscriptionid=subscription.subscriptionid )
374   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
375   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
376   WHERE     serial.subscriptionid = ? 
377   ORDER BY year DESC,
378           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
379           serial.subscriptionid
380           |;
381     $debug and warn "GetFullSubscription query: $query";
382     my $sth = $dbh->prepare($query);
383     $sth->execute($subscriptionid);
384     return $sth->fetchall_arrayref( {} );
385 }
386
387 =head2 PrepareSerialsData
388
389    $array_ref = PrepareSerialsData($serialinfomation)
390    where serialinformation is a hashref array
391
392 =cut
393
394 sub PrepareSerialsData {
395     my ($lines) = @_;
396     my %tmpresults;
397     my $year;
398     my @res;
399     my $startdate;
400     my $aqbooksellername;
401     my $bibliotitle;
402     my @loopissues;
403     my $first;
404     my $previousnote = "";
405
406     foreach my $subs (@{$lines}) {
407         for my $datefield ( qw(publisheddate planneddate) ) {
408             # handle both undef and undef returned as 0000-00-00
409             if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
410                 $subs->{$datefield} = 'XXX';
411             }
412             else {
413                 $subs->{$datefield} = format_date( $subs->{$datefield}  );
414             }
415         }
416         $subs->{ "status" . $subs->{'status'} } = 1;
417         $subs->{"checked"}                      = $subs->{'status'} =~ /1|3|4|7/;
418
419         if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
420             $year = $subs->{'year'};
421         } else {
422             $year = "manage";
423         }
424         if ( $tmpresults{$year} ) {
425             push @{ $tmpresults{$year}->{'serials'} }, $subs;
426         } else {
427             $tmpresults{$year} = {
428                 'year'             => $year,
429                 'aqbooksellername' => $subs->{'aqbooksellername'},
430                 'bibliotitle'      => $subs->{'bibliotitle'},
431                 'serials'          => [$subs],
432                 'first'            => $first,
433             };
434         }
435     }
436     foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
437         push @res, $tmpresults{$key};
438     }
439     return \@res;
440 }
441
442 =head2 GetSubscriptionsFromBiblionumber
443
444 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
445 this function get the subscription list. it reads the subscription table.
446 return :
447 reference to an array of subscriptions which have the biblionumber given on input arg.
448 each element of this array is a hashref containing
449 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
450
451 =cut
452
453 sub GetSubscriptionsFromBiblionumber {
454     my ($biblionumber) = @_;
455     my $dbh            = C4::Context->dbh;
456     my $query          = qq(
457         SELECT subscription.*,
458                branches.branchname,
459                subscriptionhistory.*,
460                aqbooksellers.name AS aqbooksellername,
461                biblio.title AS bibliotitle
462        FROM subscription
463        LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
464        LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
465        LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
466        LEFT JOIN branches ON branches.branchcode=subscription.branchcode
467        WHERE subscription.biblionumber = ?
468     );
469     my $sth = $dbh->prepare($query);
470     $sth->execute($biblionumber);
471     my @res;
472     while ( my $subs = $sth->fetchrow_hashref ) {
473         $subs->{startdate}     = format_date( $subs->{startdate} );
474         $subs->{histstartdate} = format_date( $subs->{histstartdate} );
475         $subs->{histenddate}   = format_date( $subs->{histenddate} );
476         $subs->{opacnote}     =~ s/\n/\<br\/\>/g;
477         $subs->{missinglist}  =~ s/\n/\<br\/\>/g;
478         $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
479         $subs->{ "periodicity" . $subs->{periodicity} }     = 1;
480         $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
481         $subs->{ "status" . $subs->{'status'} }             = 1;
482         $subs->{'cannotedit'} =
483           (      C4::Context->preference('IndependantBranches')
484               && C4::Context->userenv
485               && C4::Context->userenv->{flags} % 2 != 1
486               && C4::Context->userenv->{branch}
487               && $subs->{branchcode}
488               && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
489
490         if ( $subs->{enddate} eq '0000-00-00' ) {
491             $subs->{enddate} = '';
492         } else {
493             $subs->{enddate} = format_date( $subs->{enddate} );
494         }
495         $subs->{'abouttoexpire'}       = abouttoexpire( $subs->{'subscriptionid'} );
496         $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
497         push @res, $subs;
498     }
499     return \@res;
500 }
501
502 =head2 GetFullSubscriptionsFromBiblionumber
503
504    $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
505    this function reads the serial table.
506
507 =cut
508
509 sub GetFullSubscriptionsFromBiblionumber {
510     my ($biblionumber) = @_;
511     my $dbh            = C4::Context->dbh;
512     my $query          = qq|
513   SELECT    serial.serialid,
514             serial.serialseq,
515             serial.planneddate, 
516             serial.publisheddate, 
517             serial.status, 
518             serial.notes as notes,
519             year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
520             biblio.title as bibliotitle,
521             subscription.branchcode AS branchcode,
522             subscription.subscriptionid AS subscriptionid|;
523     if (   C4::Context->preference('IndependantBranches')
524         && C4::Context->userenv
525         && C4::Context->userenv->{'flags'} != 1
526         && C4::Context->userenv->{'branch'} ) {
527         $query .= "
528       , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
529     }
530
531     $query .= qq|      
532   FROM      serial 
533   LEFT JOIN subscription ON 
534           (serial.subscriptionid=subscription.subscriptionid)
535   LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id 
536   LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber 
537   WHERE     subscription.biblionumber = ? 
538   ORDER BY year DESC,
539           IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
540           serial.subscriptionid
541           |;
542     my $sth = $dbh->prepare($query);
543     $sth->execute($biblionumber);
544     return $sth->fetchall_arrayref( {} );
545 }
546
547 =head2 GetSubscriptions
548
549 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
550 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
551 return:
552 a table of hashref. Each hash containt the subscription.
553
554 =cut
555
556 sub GetSubscriptions {
557     my ( $string, $issn, $ean, $biblionumber ) = @_;
558
559     #return unless $title or $ISSN or $biblionumber;
560     my $dbh = C4::Context->dbh;
561     my $sth;
562     my $sql = qq(
563             SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
564             FROM   subscription
565             LEFT JOIN subscriptionhistory USING(subscriptionid)
566             LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
567             LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
568     );
569     my @bind_params;
570     my $sqlwhere = q{};
571     if ($biblionumber) {
572         $sqlwhere = "   WHERE biblio.biblionumber=?";
573         push @bind_params, $biblionumber;
574     }
575     if ($string) {
576         my @sqlstrings;
577         my @strings_to_search;
578         @strings_to_search = map { "%$_%" } split( / /, $string );
579         foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
580             push @bind_params, @strings_to_search;
581             my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
582             $debug && warn "$tmpstring";
583             $tmpstring =~ s/^AND //;
584             push @sqlstrings, $tmpstring;
585         }
586         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
587     }
588     if ($issn) {
589         my @sqlstrings;
590         my @strings_to_search;
591         @strings_to_search = map { "%$_%" } split( / /, $issn );
592         foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
593             push @bind_params, @strings_to_search;
594             my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
595             $debug && warn "$tmpstring";
596             $tmpstring =~ s/^OR //;
597             push @sqlstrings, $tmpstring;
598         }
599         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
600     }
601     if ($ean) {
602         my @sqlstrings;
603         my @strings_to_search;
604         @strings_to_search = map { "$_" } split( / /, $ean );
605         foreach my $index ( qw(biblioitems.ean) ) {
606             push @bind_params, @strings_to_search;
607             my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
608             $debug && warn "$tmpstring";
609             $tmpstring =~ s/^OR //;
610             push @sqlstrings, $tmpstring;
611         }
612         $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
613     }
614
615     $sql .= "$sqlwhere ORDER BY title";
616     $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
617     $sth = $dbh->prepare($sql);
618     $sth->execute(@bind_params);
619     my @results;
620
621     while ( my $line = $sth->fetchrow_hashref ) {
622         $line->{'cannotedit'} =
623           (      C4::Context->preference('IndependantBranches')
624               && C4::Context->userenv
625               && C4::Context->userenv->{flags} % 2 != 1
626               && C4::Context->userenv->{branch}
627               && $line->{branchcode}
628               && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
629         push @results, $line;
630     }
631     return @results;
632 }
633
634 =head2 GetSerials
635
636 ($totalissues,@serials) = GetSerials($subscriptionid);
637 this function gets every serial not arrived for a given subscription
638 as well as the number of issues registered in the database (all types)
639 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
640
641 FIXME: We should return \@serials.
642
643 =cut
644
645 sub GetSerials {
646     my ( $subscriptionid, $count ) = @_;
647     my $dbh = C4::Context->dbh;
648
649     # status = 2 is "arrived"
650     my $counter = 0;
651     $count = 5 unless ($count);
652     my @serials;
653     my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
654                         FROM   serial
655                         WHERE  subscriptionid = ? AND status NOT IN (2,4,5) 
656                         ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
657     my $sth = $dbh->prepare($query);
658     $sth->execute($subscriptionid);
659
660     while ( my $line = $sth->fetchrow_hashref ) {
661         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
662         for my $datefield ( qw( planneddate publisheddate) ) {
663             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
664                 $line->{$datefield} = format_date( $line->{$datefield});
665             } else {
666                 $line->{$datefield} = q{};
667             }
668         }
669         push @serials, $line;
670     }
671
672     # OK, now add the last 5 issues arrives/missing
673     $query = "SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
674        FROM     serial
675        WHERE    subscriptionid = ?
676        AND      (status in (2,4,5))
677        ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
678       ";
679     $sth = $dbh->prepare($query);
680     $sth->execute($subscriptionid);
681     while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
682         $counter++;
683         $line->{ "status" . $line->{status} } = 1;                                         # fills a "statusX" value, used for template status select list
684         for my $datefield ( qw( planneddate publisheddate) ) {
685             if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
686                 $line->{$datefield} = format_date( $line->{$datefield});
687             } else {
688                 $line->{$datefield} = q{};
689             }
690         }
691
692         push @serials, $line;
693     }
694
695     $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
696     $sth   = $dbh->prepare($query);
697     $sth->execute($subscriptionid);
698     my ($totalissues) = $sth->fetchrow;
699     return ( $totalissues, @serials );
700 }
701
702 =head2 GetSerials2
703
704 @serials = GetSerials2($subscriptionid,$status);
705 this function returns every serial waited for a given subscription
706 as well as the number of issues registered in the database (all types)
707 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
708
709 =cut
710
711 sub GetSerials2 {
712     my ( $subscription, $status ) = @_;
713     my $dbh   = C4::Context->dbh;
714     my $query = qq|
715                  SELECT   serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
716                  FROM     serial 
717                  WHERE    subscriptionid=$subscription AND status IN ($status)
718                  ORDER BY publisheddate,serialid DESC
719                     |;
720     $debug and warn "GetSerials2 query: $query";
721     my $sth = $dbh->prepare($query);
722     $sth->execute;
723     my @serials;
724
725     while ( my $line = $sth->fetchrow_hashref ) {
726         $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
727         # Format dates for display
728         for my $datefield ( qw( planneddate publisheddate ) ) {
729             if ($line->{$datefield} =~m/^00/) {
730                 $line->{$datefield} = q{};
731             }
732             else {
733                 $line->{$datefield} = format_date( $line->{$datefield} );
734             }
735         }
736         push @serials, $line;
737     }
738     return @serials;
739 }
740
741 =head2 GetLatestSerials
742
743 \@serials = GetLatestSerials($subscriptionid,$limit)
744 get the $limit's latest serials arrived or missing for a given subscription
745 return :
746 a ref to an array which contains all of the latest serials stored into a hash.
747
748 =cut
749
750 sub GetLatestSerials {
751     my ( $subscriptionid, $limit ) = @_;
752     my $dbh = C4::Context->dbh;
753
754     # status = 2 is "arrived"
755     my $strsth = "SELECT   serialid,serialseq, status, planneddate, notes
756                         FROM     serial
757                         WHERE    subscriptionid = ?
758                         AND      (status =2 or status=4)
759                         ORDER BY publisheddate DESC LIMIT 0,$limit
760                 ";
761     my $sth = $dbh->prepare($strsth);
762     $sth->execute($subscriptionid);
763     my @serials;
764     while ( my $line = $sth->fetchrow_hashref ) {
765         $line->{ "status" . $line->{status} } = 1;                        # fills a "statusX" value, used for template status select list
766         $line->{"planneddate"} = format_date( $line->{"planneddate"} );
767         push @serials, $line;
768     }
769
770     return \@serials;
771 }
772
773 =head2 GetDistributedTo
774
775 $distributedto=GetDistributedTo($subscriptionid)
776 This function returns the field distributedto for the subscription matching subscriptionid
777
778 =cut
779
780 sub GetDistributedTo {
781     my $dbh = C4::Context->dbh;
782     my $distributedto;
783     my $subscriptionid = @_;
784     my $query          = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
785     my $sth            = $dbh->prepare($query);
786     $sth->execute($subscriptionid);
787     return ($distributedto) = $sth->fetchrow;
788 }
789
790 =head2 GetNextSeq
791
792 GetNextSeq($val)
793 $val is a hashref containing all the attributes of the table 'subscription'
794 This function get the next issue for the subscription given on input arg
795 return:
796 a list containing all the input params updated.
797
798 =cut
799
800 # sub GetNextSeq {
801 #     my ($val) =@_;
802 #     my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
803 #     $calculated = $val->{numberingmethod};
804 # # calculate the (expected) value of the next issue recieved.
805 #     $newlastvalue1 = $val->{lastvalue1};
806 # # check if we have to increase the new value.
807 #     $newinnerloop1 = $val->{innerloop1}+1;
808 #     $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
809 #     $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
810 #     $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
811 #     $calculated =~ s/\{X\}/$newlastvalue1/g;
812 #
813 #     $newlastvalue2 = $val->{lastvalue2};
814 # # check if we have to increase the new value.
815 #     $newinnerloop2 = $val->{innerloop2}+1;
816 #     $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
817 #     $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
818 #     $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
819 #     $calculated =~ s/\{Y\}/$newlastvalue2/g;
820 #
821 #     $newlastvalue3 = $val->{lastvalue3};
822 # # check if we have to increase the new value.
823 #     $newinnerloop3 = $val->{innerloop3}+1;
824 #     $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
825 #     $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
826 #     $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
827 #     $calculated =~ s/\{Z\}/$newlastvalue3/g;
828 #     return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
829 # }
830
831 sub GetNextSeq {
832     my ($val) = @_;
833     my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
834     my $pattern          = $val->{numberpattern};
835     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
836     my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
837     $calculated    = $val->{numberingmethod};
838     $newlastvalue1 = $val->{lastvalue1};
839     $newlastvalue2 = $val->{lastvalue2};
840     $newlastvalue3 = $val->{lastvalue3};
841     $newlastvalue1 = $val->{lastvalue1};
842
843     # check if we have to increase the new value.
844     $newinnerloop1 = $val->{innerloop1} + 1;
845     $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
846     $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 );    # <1 to be true when 0 or empty.
847     $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} );    # reset counter if needed.
848     $calculated =~ s/\{X\}/$newlastvalue1/g;
849
850     $newlastvalue2 = $val->{lastvalue2};
851
852     # check if we have to increase the new value.
853     $newinnerloop2 = $val->{innerloop2} + 1;
854     $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
855     $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 );                         # <1 to be true when 0 or empty.
856     $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} );    # reset counter if needed.
857     if ( $pattern == 6 ) {
858         if ( $val->{hemisphere} == 2 ) {
859             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
860             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
861         } else {
862             my $newlastvalue2seq = $seasons[$newlastvalue2];
863             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
864         }
865     } else {
866         $calculated =~ s/\{Y\}/$newlastvalue2/g;
867     }
868
869     $newlastvalue3 = $val->{lastvalue3};
870
871     # check if we have to increase the new value.
872     $newinnerloop3 = $val->{innerloop3} + 1;
873     $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
874     $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 );    # <1 to be true when 0 or empty.
875     $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} );    # reset counter if needed.
876     $calculated =~ s/\{Z\}/$newlastvalue3/g;
877
878     return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
879 }
880
881 =head2 GetSeq
882
883 $calculated = GetSeq($val)
884 $val is a hashref containing all the attributes of the table 'subscription'
885 this function transforms {X},{Y},{Z} to 150,0,0 for example.
886 return:
887 the sequence in integer format
888
889 =cut
890
891 sub GetSeq {
892     my ($val) = @_;
893     my $pattern = $val->{numberpattern};
894     my @seasons          = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
895     my @southern_seasons = ( '',        'Summer', 'Autumn', 'Winter', 'Spring' );
896     my $calculated       = $val->{numberingmethod};
897     my $x                = $val->{'lastvalue1'};
898     $calculated =~ s/\{X\}/$x/g;
899     my $newlastvalue2 = $val->{'lastvalue2'};
900
901     if ( $pattern == 6 ) {
902         if ( $val->{hemisphere} == 2 ) {
903             my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
904             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
905         } else {
906             my $newlastvalue2seq = $seasons[$newlastvalue2];
907             $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
908         }
909     } else {
910         $calculated =~ s/\{Y\}/$newlastvalue2/g;
911     }
912     my $z = $val->{'lastvalue3'};
913     $calculated =~ s/\{Z\}/$z/g;
914     return $calculated;
915 }
916
917 =head2 GetExpirationDate
918
919 $enddate = GetExpirationDate($subscriptionid, [$startdate])
920
921 this function return the next expiration date for a subscription given on input args.
922
923 return
924 the enddate or undef
925
926 =cut
927
928 sub GetExpirationDate {
929     my ( $subscriptionid, $startdate ) = @_;
930     my $dbh          = C4::Context->dbh;
931     my $subscription = GetSubscription($subscriptionid);
932     my $enddate;
933
934     # we don't do the same test if the subscription is based on X numbers or on X weeks/months
935     $enddate = $startdate || $subscription->{startdate};
936     my @date = split( /-/, $enddate );
937     return if ( scalar(@date) != 3 || not check_date(@date) );
938     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
939
940         # If Not Irregular
941         if ( my $length = $subscription->{numberlength} ) {
942
943             #calculate the date of the last issue.
944             for ( my $i = 1 ; $i <= $length ; $i++ ) {
945                 $enddate = GetNextDate( $enddate, $subscription );
946             }
947         } elsif ( $subscription->{monthlength} ) {
948             if ( $$subscription{startdate} ) {
949                 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
950                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
951             }
952         } elsif ( $subscription->{weeklength} ) {
953             if ( $$subscription{startdate} ) {
954                 my @date = split( /-/, $subscription->{startdate} );
955                 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
956                 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
957             }
958         }
959         return $enddate;
960     } else {
961         return;
962     }
963 }
964
965 =head2 CountSubscriptionFromBiblionumber
966
967 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
968 this returns a count of the subscriptions for a given biblionumber
969 return :
970 the number of subscriptions
971
972 =cut
973
974 sub CountSubscriptionFromBiblionumber {
975     my ($biblionumber) = @_;
976     my $dbh            = C4::Context->dbh;
977     my $query          = "SELECT count(*) FROM subscription WHERE biblionumber=?";
978     my $sth            = $dbh->prepare($query);
979     $sth->execute($biblionumber);
980     my $subscriptionsnumber = $sth->fetchrow;
981     return $subscriptionsnumber;
982 }
983
984 =head2 ModSubscriptionHistory
985
986 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
987
988 this function modifies the history of a subscription. Put your new values on input arg.
989 returns the number of rows affected
990
991 =cut
992
993 sub ModSubscriptionHistory {
994     my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
995     my $dbh   = C4::Context->dbh;
996     my $query = "UPDATE subscriptionhistory 
997                     SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
998                     WHERE subscriptionid=?
999                 ";
1000     my $sth = $dbh->prepare($query);
1001     $recievedlist =~ s/^; //;
1002     $missinglist  =~ s/^; //;
1003     $opacnote     =~ s/^; //;
1004     $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1005     return $sth->rows;
1006 }
1007
1008 =head2 ModSerialStatus
1009
1010 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1011
1012 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1013 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1014
1015 =cut
1016
1017 sub ModSerialStatus {
1018     my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1019
1020     #It is a usual serial
1021     # 1st, get previous status :
1022     my $dbh   = C4::Context->dbh;
1023     my $query = "SELECT subscriptionid,status FROM serial WHERE  serialid=?";
1024     my $sth   = $dbh->prepare($query);
1025     $sth->execute($serialid);
1026     my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1027
1028     # change status & update subscriptionhistory
1029     my $val;
1030     if ( $status == 6 ) {
1031         DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1032     }
1033     else {
1034         my $query =
1035 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE  serialid = ?';
1036         $sth = $dbh->prepare($query);
1037         $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1038         $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1039         $sth   = $dbh->prepare($query);
1040         $sth->execute($subscriptionid);
1041         my $val = $sth->fetchrow_hashref;
1042         unless ( $val->{manualhistory} ) {
1043             $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE  subscriptionid=?";
1044             $sth   = $dbh->prepare($query);
1045             $sth->execute($subscriptionid);
1046             my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1047             if ( $status == 2 ) {
1048
1049                 $recievedlist .= "; $serialseq"
1050                   unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1051             }
1052
1053             #         warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1054             $missinglist .= "; $serialseq"
1055               if ( $status == 4
1056                 and not index( "$missinglist", "$serialseq" ) >= 0 );
1057             $missinglist .= "; not issued $serialseq"
1058               if ( $status == 5
1059                 and index( "$missinglist", "$serialseq" ) >= 0 );
1060             $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE  subscriptionid=?";
1061             $sth   = $dbh->prepare($query);
1062             $recievedlist =~ s/^; //;
1063             $missinglist  =~ s/^; //;
1064             $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1065         }
1066     }
1067
1068     # create new waited entry if needed (ie : was a "waited" and has changed)
1069     if ( $oldstatus == 1 && $status != 1 ) {
1070         my $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1071         $sth = $dbh->prepare($query);
1072         $sth->execute($subscriptionid);
1073         my $val = $sth->fetchrow_hashref;
1074
1075         # next issue number
1076         my (
1077             $newserialseq,  $newlastvalue1, $newlastvalue2, $newlastvalue3,
1078             $newinnerloop1, $newinnerloop2, $newinnerloop3
1079         ) = GetNextSeq($val);
1080
1081         # next date (calculated from actual date & frequency parameters)
1082         my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1083         NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1084         $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1085                     WHERE  subscriptionid = ?";
1086         $sth = $dbh->prepare($query);
1087         $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1088
1089 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1090         if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1091             require C4::Letters;
1092             C4::Letters::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         require C4::Suggestions;
1342         C4::Suggestions::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             require C4::Items;
1560             C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1561             return 1;
1562         }
1563         return ( 0, @errors );
1564     }
1565 }
1566
1567 =head2 HasSubscriptionStrictlyExpired
1568
1569 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1570
1571 the subscription has stricly expired when today > the end subscription date 
1572
1573 return :
1574 1 if true, 0 if false, -1 if the expiration date is not set.
1575
1576 =cut
1577
1578 sub HasSubscriptionStrictlyExpired {
1579
1580     # Getting end of subscription date
1581     my ($subscriptionid) = @_;
1582     my $dbh              = C4::Context->dbh;
1583     my $subscription     = GetSubscription($subscriptionid);
1584     my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1585
1586     # If the expiration date is set
1587     if ( $expirationdate != 0 ) {
1588         my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1589
1590         # Getting today's date
1591         my ( $nowyear, $nowmonth, $nowday ) = Today();
1592
1593         # if today's date > expiration date, then the subscription has stricly expired
1594         if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1595             return 1;
1596         } else {
1597             return 0;
1598         }
1599     } else {
1600
1601         # There are some cases where the expiration date is not set
1602         # As we can't determine if the subscription has expired on a date-basis,
1603         # we return -1;
1604         return -1;
1605     }
1606 }
1607
1608 =head2 HasSubscriptionExpired
1609
1610 $has_expired = HasSubscriptionExpired($subscriptionid)
1611
1612 the subscription has expired when the next issue to arrive is out of subscription limit.
1613
1614 return :
1615 0 if the subscription has not expired
1616 1 if the subscription has expired
1617 2 if has subscription does not have a valid expiration date set
1618
1619 =cut
1620
1621 sub HasSubscriptionExpired {
1622     my ($subscriptionid) = @_;
1623     my $dbh              = C4::Context->dbh;
1624     my $subscription     = GetSubscription($subscriptionid);
1625     if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1626         my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1627         if (!defined $expirationdate) {
1628             $expirationdate = q{};
1629         }
1630         my $query          = qq|
1631             SELECT max(planneddate)
1632             FROM   serial
1633             WHERE  subscriptionid=?
1634       |;
1635         my $sth = $dbh->prepare($query);
1636         $sth->execute($subscriptionid);
1637         my ($res) = $sth->fetchrow;
1638         if (!$res || $res=~m/^0000/) {
1639             return 0;
1640         }
1641         my @res                   = split( /-/, $res );
1642         my @endofsubscriptiondate = split( /-/, $expirationdate );
1643         return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1644         return 1
1645           if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1646             || ( !$res ) );
1647         return 0;
1648     } else {
1649         if ( $subscription->{'numberlength'} ) {
1650             my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1651             return 1 if ( $countreceived > $subscription->{'numberlength'} );
1652             return 0;
1653         } else {
1654             return 0;
1655         }
1656     }
1657     return 0;    # Notice that you'll never get here.
1658 }
1659
1660 =head2 SetDistributedto
1661
1662 SetDistributedto($distributedto,$subscriptionid);
1663 This function update the value of distributedto for a subscription given on input arg.
1664
1665 =cut
1666
1667 sub SetDistributedto {
1668     my ( $distributedto, $subscriptionid ) = @_;
1669     my $dbh   = C4::Context->dbh;
1670     my $query = qq|
1671         UPDATE subscription
1672         SET    distributedto=?
1673         WHERE  subscriptionid=?
1674     |;
1675     my $sth = $dbh->prepare($query);
1676     $sth->execute( $distributedto, $subscriptionid );
1677     return;
1678 }
1679
1680 =head2 DelSubscription
1681
1682 DelSubscription($subscriptionid)
1683 this function deletes subscription which has $subscriptionid as id.
1684
1685 =cut
1686
1687 sub DelSubscription {
1688     my ($subscriptionid) = @_;
1689     my $dbh = C4::Context->dbh;
1690     $subscriptionid = $dbh->quote($subscriptionid);
1691     $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1692     $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1693     $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1694
1695     logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1696 }
1697
1698 =head2 DelIssue
1699
1700 DelIssue($serialseq,$subscriptionid)
1701 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1702
1703 returns the number of rows affected
1704
1705 =cut
1706
1707 sub DelIssue {
1708     my ($dataissue) = @_;
1709     my $dbh = C4::Context->dbh;
1710     ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1711
1712     my $query = qq|
1713         DELETE FROM serial
1714         WHERE       serialid= ?
1715         AND         subscriptionid= ?
1716     |;
1717     my $mainsth = $dbh->prepare($query);
1718     $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1719
1720     #Delete element from subscription history
1721     $query = "SELECT * FROM   subscription WHERE  subscriptionid = ?";
1722     my $sth = $dbh->prepare($query);
1723     $sth->execute( $dataissue->{'subscriptionid'} );
1724     my $val = $sth->fetchrow_hashref;
1725     unless ( $val->{manualhistory} ) {
1726         my $query = qq|
1727           SELECT * FROM subscriptionhistory
1728           WHERE       subscriptionid= ?
1729       |;
1730         my $sth = $dbh->prepare($query);
1731         $sth->execute( $dataissue->{'subscriptionid'} );
1732         my $data      = $sth->fetchrow_hashref;
1733         my $serialseq = $dataissue->{'serialseq'};
1734         $data->{'missinglist'}  =~ s/\b$serialseq\b//;
1735         $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1736         my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1737         $sth = $dbh->prepare($strsth);
1738         $sth->execute( $dataissue->{'subscriptionid'} );
1739     }
1740
1741     return $mainsth->rows;
1742 }
1743
1744 =head2 GetLateOrMissingIssues
1745
1746 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1747
1748 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1749
1750 return :
1751 the issuelist as an array of hash refs. Each element of this array contains 
1752 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1753
1754 =cut
1755
1756 sub GetLateOrMissingIssues {
1757     my ( $supplierid, $serialid, $order ) = @_;
1758     my $dbh = C4::Context->dbh;
1759     my $sth;
1760     my $byserial = '';
1761     if ($serialid) {
1762         $byserial = "and serialid = " . $serialid;
1763     }
1764     if ($order) {
1765         $order .= ", title";
1766     } else {
1767         $order = "title";
1768     }
1769     if ($supplierid) {
1770         $sth = $dbh->prepare(
1771             "SELECT
1772                 serialid,      aqbooksellerid,        name,
1773                 biblio.title,  planneddate,           serialseq,
1774                 serial.status, serial.subscriptionid, claimdate,
1775                 subscription.branchcode
1776             FROM      serial 
1777                 LEFT JOIN subscription  ON serial.subscriptionid=subscription.subscriptionid 
1778                 LEFT JOIN biblio        ON subscription.biblionumber=biblio.biblionumber
1779                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1780                 WHERE subscription.subscriptionid = serial.subscriptionid 
1781                 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1782                 AND subscription.aqbooksellerid=$supplierid
1783                 $byserial
1784                 ORDER BY $order"
1785         );
1786     } else {
1787         $sth = $dbh->prepare(
1788             "SELECT 
1789             serialid,      aqbooksellerid,         name,
1790             biblio.title,  planneddate,           serialseq,
1791                 serial.status, serial.subscriptionid, claimdate,
1792                 subscription.branchcode
1793             FROM serial 
1794                 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid 
1795                 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1796                 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1797                 WHERE subscription.subscriptionid = serial.subscriptionid 
1798                         AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1799                 $byserial
1800                 ORDER BY $order"
1801         );
1802     }
1803     $sth->execute;
1804     my @issuelist;
1805     while ( my $line = $sth->fetchrow_hashref ) {
1806
1807         if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1808             $line->{planneddate} = format_date( $line->{planneddate} );
1809         }
1810         if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1811             $line->{claimdate}   = format_date( $line->{claimdate} );
1812         }
1813         $line->{"status".$line->{status}}   = 1;
1814         push @issuelist, $line;
1815     }
1816     return @issuelist;
1817 }
1818
1819 =head2 removeMissingIssue
1820
1821 removeMissingIssue($subscriptionid)
1822
1823 this function removes an issue from being part of the missing string in 
1824 subscriptionlist.missinglist column
1825
1826 called when a missing issue is found from the serials-recieve.pl file
1827
1828 =cut
1829
1830 sub removeMissingIssue {
1831     my ( $sequence, $subscriptionid ) = @_;
1832     my $dbh = C4::Context->dbh;
1833     my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1834     $sth->execute($subscriptionid);
1835     my $data              = $sth->fetchrow_hashref;
1836     my $missinglist       = $data->{'missinglist'};
1837     my $missinglistbefore = $missinglist;
1838
1839     # warn $missinglist." before";
1840     $missinglist =~ s/($sequence)//;
1841
1842     # warn $missinglist." after";
1843     if ( $missinglist ne $missinglistbefore ) {
1844         $missinglist =~ s/\|\s\|/\|/g;
1845         $missinglist =~ s/^\| //g;
1846         $missinglist =~ s/\|$//g;
1847         my $sth2 = $dbh->prepare(
1848             "UPDATE subscriptionhistory
1849                     SET missinglist = ?
1850                     WHERE subscriptionid = ?"
1851         );
1852         $sth2->execute( $missinglist, $subscriptionid );
1853     }
1854     return;
1855 }
1856
1857 =head2 updateClaim
1858
1859 &updateClaim($serialid)
1860
1861 this function updates the time when a claim is issued for late/missing items
1862
1863 called from claims.pl file
1864
1865 =cut
1866
1867 sub updateClaim {
1868     my ($serialid) = @_;
1869     my $dbh        = C4::Context->dbh;
1870     my $sth        = $dbh->prepare(
1871         "UPDATE serial SET claimdate = now()
1872                 WHERE serialid = ?
1873         "
1874     );
1875     $sth->execute($serialid);
1876     return;
1877 }
1878
1879 =head2 getsupplierbyserialid
1880
1881 $result = getsupplierbyserialid($serialid)
1882
1883 this function is used to find the supplier id given a serial id
1884
1885 return :
1886 hashref containing serialid, subscriptionid, and aqbooksellerid
1887
1888 =cut
1889
1890 sub getsupplierbyserialid {
1891     my ($serialid) = @_;
1892     my $dbh        = C4::Context->dbh;
1893     my $sth        = $dbh->prepare(
1894         "SELECT serialid, serial.subscriptionid, aqbooksellerid
1895          FROM serial 
1896             LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1897             WHERE serialid = ?
1898         "
1899     );
1900     $sth->execute($serialid);
1901     my $line   = $sth->fetchrow_hashref;
1902     my $result = $line->{'aqbooksellerid'};
1903     return $result;
1904 }
1905
1906 =head2 check_routing
1907
1908 $result = &check_routing($subscriptionid)
1909
1910 this function checks to see if a serial has a routing list and returns the count of routingid
1911 used to show either an 'add' or 'edit' link
1912
1913 =cut
1914
1915 sub check_routing {
1916     my ($subscriptionid) = @_;
1917     my $dbh              = C4::Context->dbh;
1918     my $sth              = $dbh->prepare(
1919         "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist 
1920                               ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1921                               WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1922                               "
1923     );
1924     $sth->execute($subscriptionid);
1925     my $line   = $sth->fetchrow_hashref;
1926     my $result = $line->{'routingids'};
1927     return $result;
1928 }
1929
1930 =head2 addroutingmember
1931
1932 addroutingmember($borrowernumber,$subscriptionid)
1933
1934 this function takes a borrowernumber and subscriptionid and adds the member to the
1935 routing list for that serial subscription and gives them a rank on the list
1936 of either 1 or highest current rank + 1
1937
1938 =cut
1939
1940 sub addroutingmember {
1941     my ( $borrowernumber, $subscriptionid ) = @_;
1942     my $rank;
1943     my $dbh = C4::Context->dbh;
1944     my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1945     $sth->execute($subscriptionid);
1946     while ( my $line = $sth->fetchrow_hashref ) {
1947         if ( $line->{'rank'} > 0 ) {
1948             $rank = $line->{'rank'} + 1;
1949         } else {
1950             $rank = 1;
1951         }
1952     }
1953     $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1954     $sth->execute( $subscriptionid, $borrowernumber, $rank );
1955 }
1956
1957 =head2 reorder_members
1958
1959 reorder_members($subscriptionid,$routingid,$rank)
1960
1961 this function is used to reorder the routing list
1962
1963 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1964 - it gets all members on list puts their routingid's into an array
1965 - removes the one in the array that is $routingid
1966 - then reinjects $routingid at point indicated by $rank
1967 - then update the database with the routingids in the new order
1968
1969 =cut
1970
1971 sub reorder_members {
1972     my ( $subscriptionid, $routingid, $rank ) = @_;
1973     my $dbh = C4::Context->dbh;
1974     my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1975     $sth->execute($subscriptionid);
1976     my @result;
1977     while ( my $line = $sth->fetchrow_hashref ) {
1978         push( @result, $line->{'routingid'} );
1979     }
1980
1981     # To find the matching index
1982     my $i;
1983     my $key = -1;    # to allow for 0 being a valid response
1984     for ( $i = 0 ; $i < @result ; $i++ ) {
1985         if ( $routingid == $result[$i] ) {
1986             $key = $i;    # save the index
1987             last;
1988         }
1989     }
1990
1991     # if index exists in array then move it to new position
1992     if ( $key > -1 && $rank > 0 ) {
1993         my $new_rank = $rank - 1;                       # $new_rank is what you want the new index to be in the array
1994         my $moving_item = splice( @result, $key, 1 );
1995         splice( @result, $new_rank, 0, $moving_item );
1996     }
1997     for ( my $j = 0 ; $j < @result ; $j++ ) {
1998         my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1999         $sth->execute;
2000     }
2001     return;
2002 }
2003
2004 =head2 delroutingmember
2005
2006 delroutingmember($routingid,$subscriptionid)
2007
2008 this function either deletes one member from routing list if $routingid exists otherwise
2009 deletes all members from the routing list
2010
2011 =cut
2012
2013 sub delroutingmember {
2014
2015     # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2016     my ( $routingid, $subscriptionid ) = @_;
2017     my $dbh = C4::Context->dbh;
2018     if ($routingid) {
2019         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2020         $sth->execute($routingid);
2021         reorder_members( $subscriptionid, $routingid );
2022     } else {
2023         my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2024         $sth->execute($subscriptionid);
2025     }
2026     return;
2027 }
2028
2029 =head2 getroutinglist
2030
2031 @routinglist = getroutinglist($subscriptionid)
2032
2033 this gets the info from the subscriptionroutinglist for $subscriptionid
2034
2035 return :
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     $sth->execute($subscriptionid);
2051     my $routinglist = $sth->fetchall_arrayref({});
2052     return @{$routinglist};
2053 }
2054
2055 =head2 countissuesfrom
2056
2057 $result = countissuesfrom($subscriptionid,$startdate)
2058
2059 Returns a count of serial rows matching the given subsctiptionid
2060 with published date greater than startdate
2061
2062 =cut
2063
2064 sub countissuesfrom {
2065     my ( $subscriptionid, $startdate ) = @_;
2066     my $dbh   = C4::Context->dbh;
2067     my $query = qq|
2068             SELECT count(*)
2069             FROM   serial
2070             WHERE  subscriptionid=?
2071             AND serial.publisheddate>?
2072         |;
2073     my $sth = $dbh->prepare($query);
2074     $sth->execute( $subscriptionid, $startdate );
2075     my ($countreceived) = $sth->fetchrow;
2076     return $countreceived;
2077 }
2078
2079 =head2 CountIssues
2080
2081 $result = CountIssues($subscriptionid)
2082
2083 Returns a count of serial rows matching the given subsctiptionid
2084
2085 =cut
2086
2087 sub CountIssues {
2088     my ($subscriptionid) = @_;
2089     my $dbh              = C4::Context->dbh;
2090     my $query            = qq|
2091             SELECT count(*)
2092             FROM   serial
2093             WHERE  subscriptionid=?
2094         |;
2095     my $sth = $dbh->prepare($query);
2096     $sth->execute($subscriptionid);
2097     my ($countreceived) = $sth->fetchrow;
2098     return $countreceived;
2099 }
2100
2101 =head2 HasItems
2102
2103 $result = HasItems($subscriptionid)
2104
2105 returns a count of items from serial matching the subscriptionid
2106
2107 =cut
2108
2109 sub HasItems {
2110     my ($subscriptionid) = @_;
2111     my $dbh              = C4::Context->dbh;
2112     my $query = q|
2113             SELECT COUNT(serialitems.itemnumber)
2114             FROM   serial 
2115                         LEFT JOIN serialitems USING(serialid)
2116             WHERE  subscriptionid=? AND serialitems.serialid IS NOT NULL
2117         |;
2118     my $sth=$dbh->prepare($query);
2119     $sth->execute($subscriptionid);
2120     my ($countitems)=$sth->fetchrow_array();
2121     return $countitems;  
2122 }
2123
2124 =head2 abouttoexpire
2125
2126 $result = abouttoexpire($subscriptionid)
2127
2128 this function alerts you to the penultimate issue for a serial subscription
2129
2130 returns 1 - if this is the penultimate issue
2131 returns 0 - if not
2132
2133 =cut
2134
2135 sub abouttoexpire {
2136     my ($subscriptionid) = @_;
2137     my $dbh              = C4::Context->dbh;
2138     my $subscription     = GetSubscription($subscriptionid);
2139     my $per = $subscription->{'periodicity'};
2140     if ($per && $per % 16 > 0){
2141         my $expirationdate   = GetExpirationDate($subscriptionid);
2142         my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2143         my @res;
2144         if (defined $res) {
2145             @res=split (/-/,$res);
2146             @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2147         } else { # default an undefined value
2148             @res=Date::Calc::Today;
2149         }
2150         my @endofsubscriptiondate=split(/-/,$expirationdate);
2151         my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2152         my @datebeforeend;
2153         @datebeforeend = Add_Delta_Days(  $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2154             - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2155         return 1 if ( @res &&
2156             (@datebeforeend &&
2157                 Delta_Days($res[0],$res[1],$res[2],
2158                     $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2159             (@endofsubscriptiondate &&
2160                 Delta_Days($res[0],$res[1],$res[2],
2161                     $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2162         return 0;
2163     } elsif ($subscription->{numberlength}>0) {
2164         return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2165     }
2166     return 0;
2167 }
2168
2169 sub in_array {    # used in next sub down
2170     my ( $val, @elements ) = @_;
2171     foreach my $elem (@elements) {
2172         if ( $val == $elem ) {
2173             return 1;
2174         }
2175     }
2176     return 0;
2177 }
2178
2179 =head2 GetSubscriptionsFromBorrower
2180
2181 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2182
2183 this gets the info from subscriptionroutinglist for each $subscriptionid
2184
2185 return :
2186 a count of the serial subscription routing lists to which a patron belongs,
2187 with the titles of those serial subscriptions as an array. Each element of the array
2188 contains a hash_ref with subscriptionID and title of subscription.
2189
2190 =cut
2191
2192 sub GetSubscriptionsFromBorrower {
2193     my ($borrowernumber) = @_;
2194     my $dbh              = C4::Context->dbh;
2195     my $sth              = $dbh->prepare(
2196         "SELECT subscription.subscriptionid, biblio.title
2197             FROM subscription
2198             JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2199             JOIN subscriptionroutinglist USING (subscriptionid)
2200             WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2201                                "
2202     );
2203     $sth->execute($borrowernumber);
2204     my @routinglist;
2205     my $count = 0;
2206     while ( my $line = $sth->fetchrow_hashref ) {
2207         $count++;
2208         push( @routinglist, $line );
2209     }
2210     return ( $count, @routinglist );
2211 }
2212
2213 =head2 GetNextDate
2214
2215 $resultdate = GetNextDate($planneddate,$subscription)
2216
2217 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2218 exists an irregularity
2219 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be 
2220 skipped then the returned date will be 2007-05-10
2221
2222 return :
2223 $resultdate - then next date in the sequence
2224
2225 Return 0 if periodicity==0
2226
2227 =cut
2228
2229 sub GetNextDate(@) {
2230     my ( $planneddate, $subscription ) = @_;
2231     my @irreg = split( /\,/, $subscription->{irregularity} );
2232
2233     #date supposed to be in ISO.
2234
2235     my ( $year, $month, $day ) = split( /-/, $planneddate );
2236     $month = 1 unless ($month);
2237     $day   = 1 unless ($day);
2238     my @resultdate;
2239
2240     #       warn "DOW $dayofweek";
2241     if ( $subscription->{periodicity} % 16 == 0 ) {    # 'without regularity' || 'irregular'
2242         return 0;
2243     }
2244
2245     #   daily : n / week
2246     #   Since we're interpreting irregularity here as which days of the week to skip an issue,
2247     #   renaming this pattern from 1/day to " n / week ".
2248     if ( $subscription->{periodicity} == 1 ) {
2249         my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2250         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2251         else {
2252             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2253                 $dayofweek = 0 if ( $dayofweek == 7 );
2254                 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2255                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2256                     $dayofweek++;
2257                 }
2258             }
2259             @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2260         }
2261     }
2262
2263     #   1  week
2264     if ( $subscription->{periodicity} == 2 ) {
2265         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2266         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2267         else {
2268             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2269
2270                 #FIXME: if two consecutive irreg, do we only skip one?
2271                 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2272                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2273                     $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2274                 }
2275             }
2276             @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2277         }
2278     }
2279
2280     #   1 / 2 weeks
2281     if ( $subscription->{periodicity} == 3 ) {
2282         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2283         if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2284         else {
2285             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2286                 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2287                     ### BUGFIX was previously +1 ^
2288                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2289                     $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2290                 }
2291             }
2292             @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2293         }
2294     }
2295
2296     #   1 / 3 weeks
2297     if ( $subscription->{periodicity} == 4 ) {
2298         my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2299         if ($@) { warn "annĂ©e mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2300         else {
2301             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2302                 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2303                     ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2304                     $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2305                 }
2306             }
2307             @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2308         }
2309     }
2310     my $tmpmonth = $month;
2311     if ( $year && $month && $day ) {
2312         if ( $subscription->{periodicity} == 5 ) {
2313             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2314                 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2315                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2316                     $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2317                 }
2318             }
2319             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2320         }
2321         if ( $subscription->{periodicity} == 6 ) {
2322             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2323                 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2324                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2325                     $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2326                 }
2327             }
2328             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2329         }
2330         if ( $subscription->{periodicity} == 7 ) {
2331             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2332                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2333                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2334                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2335                 }
2336             }
2337             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2338         }
2339         if ( $subscription->{periodicity} == 8 ) {
2340             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2341                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2342                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2343                     $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2344                 }
2345             }
2346             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2347         }
2348         if ( $subscription->{periodicity} == 13 ) {
2349             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2350                 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2351                     ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2352                     $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2353                 }
2354             }
2355             @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2356         }
2357         if ( $subscription->{periodicity} == 9 ) {
2358             for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2359                 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2360                     ### BUFIX Seems to need more Than One ?
2361                     ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2362                     $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2363                 }
2364             }
2365             @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2366         }
2367         if ( $subscription->{periodicity} == 10 ) {
2368             @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2369         }
2370         if ( $subscription->{periodicity} == 11 ) {
2371             @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2372         }
2373     }
2374     my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2375
2376     return "$resultdate";
2377 }
2378
2379 =head2 is_barcode_in_use
2380
2381 Returns number of occurence of the barcode in the items table
2382 Can be used as a boolean test of whether the barcode has
2383 been deployed as yet
2384
2385 =cut
2386
2387 sub is_barcode_in_use {
2388     my $barcode = shift;
2389     my $dbh       = C4::Context->dbh;
2390     my $occurences = $dbh->selectall_arrayref(
2391         'SELECT itemnumber from items where barcode = ?',
2392         {}, $barcode
2393
2394     );
2395
2396     return @{$occurences};
2397 }
2398
2399 1;
2400 __END__
2401
2402 =head1 AUTHOR
2403
2404 Koha Development Team <http://koha-community.org/>
2405
2406 =cut