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