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