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