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