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