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