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