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