bug 5086: fix setting claim date
[koha.git] / C4 / Serials.pm
blob32e46becae8223f4afb42ac920e30ce0c4d4b4b4
1 package C4::Serials;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 use strict;
21 use warnings;
22 use C4::Dates qw(format_date format_date_in_iso);
23 use Date::Calc qw(:all);
24 use POSIX qw(strftime);
25 use C4::Suggestions;
26 use C4::Koha;
27 use C4::Biblio;
28 use C4::Branch;
29 use C4::Items;
30 use C4::Search;
31 use C4::Letters;
32 use C4::Log; # logaction
33 use C4::Debug;
35 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
37 BEGIN {
38 $VERSION = 3.01; # set version for version checking
39 require Exporter;
40 @ISA = qw(Exporter);
41 @EXPORT = qw(
42 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
43 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
44 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
45 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
47 &GetNextSeq &NewIssue &ItemizeSerials &GetSerials
48 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
49 &ReNewSubscription &GetLateIssues &GetLateOrMissingIssues
50 &GetSerialInformation &AddItem2Serial
51 &PrepareSerialsData &GetNextExpected &ModNextExpected
53 &UpdateClaimdateIssues
54 &GetSuppliersWithLateIssues &getsupplierbyserialid
55 &GetDistributedTo &SetDistributedTo
56 &getroutinglist &delroutingmember &addroutingmember
57 &reorder_members
58 &check_routing &updateClaim &removeMissingIssue
59 &CountIssues
60 HasItems
65 =head1 NAME
67 C4::Serials - Serials Module Functions
69 =head1 SYNOPSIS
71 use C4::Serials;
73 =head1 DESCRIPTION
75 Functions for handling subscriptions, claims routing etc.
78 =head1 SUBROUTINES
80 =head2 GetSuppliersWithLateIssues
82 $supplierlist = GetSuppliersWithLateIssues()
84 this function get all suppliers with late issues.
86 return :
87 an array_ref of suppliers each entry is a hash_ref containing id and name
88 the array is in name order
90 =cut
92 sub GetSuppliersWithLateIssues {
93 my $dbh = C4::Context->dbh;
94 my $query = q|
95 SELECT DISTINCT aqbooksellerid as id, aqbooksellers.name as name
96 FROM subscription
97 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
98 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
99 WHERE id > 0 AND (planneddate < now() OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
100 return $dbh->selectall_arrayref($query, { Slice => {} });
103 =head2 GetLateIssues
105 @issuelist = GetLateIssues($supplierid)
107 this function selects late issues from the database
109 return :
110 the issuelist as an array. Each element of this array contains a hashi_ref containing
111 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
113 =cut
115 sub GetLateIssues {
116 my ($supplierid) = @_;
117 my $dbh = C4::Context->dbh;
118 my $sth;
119 if ($supplierid) {
120 my $query = qq|
121 SELECT name,title,planneddate,serialseq,serial.subscriptionid
122 FROM subscription
123 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
124 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
125 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
126 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
127 AND subscription.aqbooksellerid=$supplierid
128 ORDER BY title
130 $sth = $dbh->prepare($query);
131 } else {
132 my $query = qq|
133 SELECT name,title,planneddate,serialseq,serial.subscriptionid
134 FROM subscription
135 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
136 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
137 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
138 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
139 ORDER BY title
141 $sth = $dbh->prepare($query);
143 $sth->execute;
144 my @issuelist;
145 my $last_title;
146 my $odd = 0;
147 while ( my $line = $sth->fetchrow_hashref ) {
148 $odd++ unless $line->{title} eq $last_title;
149 $line->{title} = "" if $line->{title} eq $last_title;
150 $last_title = $line->{title} if ( $line->{title} );
151 $line->{planneddate} = format_date( $line->{planneddate} );
152 push @issuelist, $line;
154 return @issuelist;
157 =head2 GetSubscriptionHistoryFromSubscriptionId
159 $sth = GetSubscriptionHistoryFromSubscriptionId()
160 this function prepares the SQL request and returns the statement handle
161 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
163 =cut
165 sub GetSubscriptionHistoryFromSubscriptionId() {
166 my $dbh = C4::Context->dbh;
167 my $query = qq|
168 SELECT *
169 FROM subscriptionhistory
170 WHERE subscriptionid = ?
172 return $dbh->prepare($query);
175 =head2 GetSerialStatusFromSerialId
177 $sth = GetSerialStatusFromSerialId();
178 this function returns a statement handle
179 After this function, don't forget to execute it by using $sth->execute($serialid)
180 return :
181 $sth = $dbh->prepare($query).
183 =cut
185 sub GetSerialStatusFromSerialId() {
186 my $dbh = C4::Context->dbh;
187 my $query = qq|
188 SELECT status
189 FROM serial
190 WHERE serialid = ?
192 return $dbh->prepare($query);
195 =head2 GetSerialInformation
198 $data = GetSerialInformation($serialid);
199 returns a hash_ref containing :
200 items : items marcrecord (can be an array)
201 serial table field
202 subscription table field
203 + information about subscription expiration
205 =cut
207 sub GetSerialInformation {
208 my ($serialid) = @_;
209 my $dbh = C4::Context->dbh;
210 my $query = qq|
211 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
212 if ( C4::Context->preference('IndependantBranches')
213 && C4::Context->userenv
214 && C4::Context->userenv->{'flags'} != 1
215 && C4::Context->userenv->{'branch'} ) {
216 $query .= "
217 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
219 $query .= qq|
220 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
221 WHERE serialid = ?
223 my $rq = $dbh->prepare($query);
224 $rq->execute($serialid);
225 my $data = $rq->fetchrow_hashref;
227 # create item information if we have serialsadditems for this subscription
228 if ( $data->{'serialsadditems'} ) {
229 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
230 $queryitem->execute($serialid);
231 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
232 if ( scalar(@$itemnumbers) > 0 ) {
233 foreach my $itemnum (@$itemnumbers) {
235 #It is ASSUMED that GetMarcItem ALWAYS WORK...
236 #Maybe GetMarcItem should return values on failure
237 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
238 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
239 $itemprocessed->{'itemnumber'} = $itemnum->[0];
240 $itemprocessed->{'itemid'} = $itemnum->[0];
241 $itemprocessed->{'serialid'} = $serialid;
242 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
243 push @{ $data->{'items'} }, $itemprocessed;
245 } else {
246 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
247 $itemprocessed->{'itemid'} = "N$serialid";
248 $itemprocessed->{'serialid'} = $serialid;
249 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
250 $itemprocessed->{'countitems'} = 0;
251 push @{ $data->{'items'} }, $itemprocessed;
254 $data->{ "status" . $data->{'serstatus'} } = 1;
255 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
256 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
257 return $data;
260 =head2 AddItem2Serial
262 $rows = AddItem2Serial($serialid,$itemnumber);
263 Adds an itemnumber to Serial record
264 returns the number of rows affected
266 =cut
268 sub AddItem2Serial {
269 my ( $serialid, $itemnumber ) = @_;
270 my $dbh = C4::Context->dbh;
271 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
272 $rq->execute( $serialid, $itemnumber );
273 return $rq->rows;
276 =head2 UpdateClaimdateIssues
278 UpdateClaimdateIssues($serialids,[$date]);
280 Update Claimdate for issues in @$serialids list with date $date
281 (Take Today if none)
283 =cut
285 sub UpdateClaimdateIssues {
286 my ( $serialids, $date ) = @_;
287 my $dbh = C4::Context->dbh;
288 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
289 my $query = "
290 UPDATE serial SET claimdate = ?, status = 7
291 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
292 my $rq = $dbh->prepare($query);
293 $rq->execute($date, @$serialids);
294 return $rq->rows;
297 =head2 GetSubscription
299 $subs = GetSubscription($subscriptionid)
300 this function returns the subscription which has $subscriptionid as id.
301 return :
302 a hashref. This hash containts
303 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
305 =cut
307 sub GetSubscription {
308 my ($subscriptionid) = @_;
309 my $dbh = C4::Context->dbh;
310 my $query = qq(
311 SELECT subscription.*,
312 subscriptionhistory.*,
313 aqbooksellers.name AS aqbooksellername,
314 biblio.title AS bibliotitle,
315 subscription.biblionumber as bibnum);
316 if ( C4::Context->preference('IndependantBranches')
317 && C4::Context->userenv
318 && C4::Context->userenv->{'flags'} != 1
319 && C4::Context->userenv->{'branch'} ) {
320 $query .= "
321 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
323 $query .= qq(
324 FROM subscription
325 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
326 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
327 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
328 WHERE subscription.subscriptionid = ?
331 # if (C4::Context->preference('IndependantBranches') &&
332 # C4::Context->userenv &&
333 # C4::Context->userenv->{'flags'} != 1){
334 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
335 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
337 $debug and warn "query : $query\nsubsid :$subscriptionid";
338 my $sth = $dbh->prepare($query);
339 $sth->execute($subscriptionid);
340 return $sth->fetchrow_hashref;
343 =head2 GetFullSubscription
345 $array_ref = GetFullSubscription($subscriptionid)
346 this function reads the serial table.
348 =cut
350 sub GetFullSubscription {
351 my ($subscriptionid) = @_;
352 my $dbh = C4::Context->dbh;
353 my $query = qq|
354 SELECT serial.serialid,
355 serial.serialseq,
356 serial.planneddate,
357 serial.publisheddate,
358 serial.status,
359 serial.notes as notes,
360 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
361 aqbooksellers.name as aqbooksellername,
362 biblio.title as bibliotitle,
363 subscription.branchcode AS branchcode,
364 subscription.subscriptionid AS subscriptionid |;
365 if ( C4::Context->preference('IndependantBranches')
366 && C4::Context->userenv
367 && C4::Context->userenv->{'flags'} != 1
368 && C4::Context->userenv->{'branch'} ) {
369 $query .= "
370 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
372 $query .= qq|
373 FROM serial
374 LEFT JOIN subscription ON
375 (serial.subscriptionid=subscription.subscriptionid )
376 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
377 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
378 WHERE serial.subscriptionid = ?
379 ORDER BY year DESC,
380 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
381 serial.subscriptionid
383 $debug and warn "GetFullSubscription query: $query";
384 my $sth = $dbh->prepare($query);
385 $sth->execute($subscriptionid);
386 return $sth->fetchall_arrayref( {} );
389 =head2 PrepareSerialsData
391 $array_ref = PrepareSerialsData($serialinfomation)
392 where serialinformation is a hashref array
394 =cut
396 sub PrepareSerialsData {
397 my ($lines) = @_;
398 my %tmpresults;
399 my $year;
400 my @res;
401 my $startdate;
402 my $aqbooksellername;
403 my $bibliotitle;
404 my @loopissues;
405 my $first;
406 my $previousnote = "";
408 foreach my $subs (@{$lines}) {
409 for my $datefield ( qw(publisheddate planneddate) ) {
410 # handle both undef and undef returned as 0000-00-00
411 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
412 $subs->{$datefield} = 'XXX';
414 else {
415 $subs->{$datefield} = format_date( $subs->{$datefield} );
418 $subs->{'branchname'} = GetBranchName( $subs->{'branchcode'} );
419 $subs->{ "status" . $subs->{'status'} } = 1;
420 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
422 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
423 $year = $subs->{'year'};
424 } else {
425 $year = "manage";
427 if ( $tmpresults{$year} ) {
428 push @{ $tmpresults{$year}->{'serials'} }, $subs;
429 } else {
430 $tmpresults{$year} = {
431 'year' => $year,
432 'aqbooksellername' => $subs->{'aqbooksellername'},
433 'bibliotitle' => $subs->{'bibliotitle'},
434 'serials' => [$subs],
435 'first' => $first,
439 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
440 push @res, $tmpresults{$key};
442 $res[0]->{'first'} = 1;
443 return \@res;
446 =head2 GetSubscriptionsFromBiblionumber
448 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
449 this function get the subscription list. it reads the subscription table.
450 return :
451 reference to an array of subscriptions which have the biblionumber given on input arg.
452 each element of this array is a hashref containing
453 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
455 =cut
457 sub GetSubscriptionsFromBiblionumber {
458 my ($biblionumber) = @_;
459 my $dbh = C4::Context->dbh;
460 my $query = qq(
461 SELECT subscription.*,
462 branches.branchname,
463 subscriptionhistory.*,
464 aqbooksellers.name AS aqbooksellername,
465 biblio.title AS bibliotitle
466 FROM subscription
467 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
468 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
469 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
470 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
471 WHERE subscription.biblionumber = ?
473 my $sth = $dbh->prepare($query);
474 $sth->execute($biblionumber);
475 my @res;
476 while ( my $subs = $sth->fetchrow_hashref ) {
477 $subs->{startdate} = format_date( $subs->{startdate} );
478 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
479 $subs->{histenddate} = format_date( $subs->{histenddate} );
480 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
481 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
482 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
483 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
484 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
485 $subs->{ "status" . $subs->{'status'} } = 1;
486 $subs->{'cannotedit'} =
487 ( C4::Context->preference('IndependantBranches')
488 && C4::Context->userenv
489 && C4::Context->userenv->{flags} % 2 != 1
490 && C4::Context->userenv->{branch}
491 && $subs->{branchcode}
492 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
494 if ( $subs->{enddate} eq '0000-00-00' ) {
495 $subs->{enddate} = '';
496 } else {
497 $subs->{enddate} = format_date( $subs->{enddate} );
499 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
500 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
501 push @res, $subs;
503 return \@res;
506 =head2 GetFullSubscriptionsFromBiblionumber
508 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
509 this function reads the serial table.
511 =cut
513 sub GetFullSubscriptionsFromBiblionumber {
514 my ($biblionumber) = @_;
515 my $dbh = C4::Context->dbh;
516 my $query = qq|
517 SELECT serial.serialid,
518 serial.serialseq,
519 serial.planneddate,
520 serial.publisheddate,
521 serial.status,
522 serial.notes as notes,
523 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
524 biblio.title as bibliotitle,
525 subscription.branchcode AS branchcode,
526 subscription.subscriptionid AS subscriptionid|;
527 if ( C4::Context->preference('IndependantBranches')
528 && C4::Context->userenv
529 && C4::Context->userenv->{'flags'} != 1
530 && C4::Context->userenv->{'branch'} ) {
531 $query .= "
532 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
535 $query .= qq|
536 FROM serial
537 LEFT JOIN subscription ON
538 (serial.subscriptionid=subscription.subscriptionid)
539 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
540 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
541 WHERE subscription.biblionumber = ?
542 ORDER BY year DESC,
543 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
544 serial.subscriptionid
546 my $sth = $dbh->prepare($query);
547 $sth->execute($biblionumber);
548 return $sth->fetchall_arrayref( {} );
551 =head2 GetSubscriptions
553 @results = GetSubscriptions($title,$ISSN,$biblionumber);
554 this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
555 return:
556 a table of hashref. Each hash containt the subscription.
558 =cut
560 sub GetSubscriptions {
561 my ( $string, $issn, $biblionumber ) = @_;
563 #return unless $title or $ISSN or $biblionumber;
564 my $dbh = C4::Context->dbh;
565 my $sth;
566 my $sql = qq(
567 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
568 FROM subscription
569 LEFT JOIN subscriptionhistory USING(subscriptionid)
570 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
571 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
573 my @bind_params;
574 my $sqlwhere;
575 if ($biblionumber) {
576 $sqlwhere = " WHERE biblio.biblionumber=?";
577 push @bind_params, $biblionumber;
579 if ($string) {
580 my @sqlstrings;
581 my @strings_to_search;
582 @strings_to_search = map { "%$_%" } split( / /, $string );
583 foreach my $index qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes) {
584 push @bind_params, @strings_to_search;
585 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
586 $debug && warn "$tmpstring";
587 $tmpstring =~ s/^AND //;
588 push @sqlstrings, $tmpstring;
590 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "(" . join( ") OR (", @sqlstrings ) . ")";
592 if ($issn) {
593 my @sqlstrings;
594 my @strings_to_search;
595 @strings_to_search = map { "%$_%" } split( / /, $issn );
596 foreach my $index qw(biblioitems.issn subscription.callnumber) {
597 push @bind_params, @strings_to_search;
598 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
599 $debug && warn "$tmpstring";
600 $tmpstring =~ s/^OR //;
601 push @sqlstrings, $tmpstring;
603 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "(" . join( ") OR (", @sqlstrings ) . ")";
605 $sql .= "$sqlwhere ORDER BY title";
606 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
607 $sth = $dbh->prepare($sql);
608 $sth->execute(@bind_params);
609 my @results;
610 my $previoustitle = "";
611 my $odd = 1;
613 while ( my $line = $sth->fetchrow_hashref ) {
614 if ( $previoustitle eq $line->{title} ) {
615 $line->{title} = "";
616 $line->{issn} = "";
617 } else {
618 $previoustitle = $line->{title};
619 $odd = -$odd;
621 $line->{toggle} = 1 if $odd == 1;
622 $line->{'cannotedit'} =
623 ( C4::Context->preference('IndependantBranches')
624 && C4::Context->userenv
625 && C4::Context->userenv->{flags} % 2 != 1
626 && C4::Context->userenv->{branch}
627 && $line->{branchcode}
628 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
629 push @results, $line;
631 return @results;
634 =head2 GetSerials
636 ($totalissues,@serials) = GetSerials($subscriptionid);
637 this function gets every serial not arrived for a given subscription
638 as well as the number of issues registered in the database (all types)
639 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
641 FIXME: We should return \@serials.
643 =cut
645 sub GetSerials {
646 my ( $subscriptionid, $count ) = @_;
647 my $dbh = C4::Context->dbh;
649 # status = 2 is "arrived"
650 my $counter = 0;
651 $count = 5 unless ($count);
652 my @serials;
653 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
654 FROM serial
655 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
656 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
657 my $sth = $dbh->prepare($query);
658 $sth->execute($subscriptionid);
660 while ( my $line = $sth->fetchrow_hashref ) {
661 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
662 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
663 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
664 push @serials, $line;
667 # OK, now add the last 5 issues arrives/missing
668 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
669 FROM serial
670 WHERE subscriptionid = ?
671 AND (status in (2,4,5))
672 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
674 $sth = $dbh->prepare($query);
675 $sth->execute($subscriptionid);
676 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
677 $counter++;
678 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
679 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
680 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
681 push @serials, $line;
684 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
685 $sth = $dbh->prepare($query);
686 $sth->execute($subscriptionid);
687 my ($totalissues) = $sth->fetchrow;
688 return ( $totalissues, @serials );
691 =head2 GetSerials2
693 @serials = GetSerials2($subscriptionid,$status);
694 this function returns every serial waited for a given subscription
695 as well as the number of issues registered in the database (all types)
696 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
698 =cut
700 sub GetSerials2 {
701 my ( $subscription, $status ) = @_;
702 my $dbh = C4::Context->dbh;
703 my $query = qq|
704 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
705 FROM serial
706 WHERE subscriptionid=$subscription AND status IN ($status)
707 ORDER BY publisheddate,serialid DESC
709 $debug and warn "GetSerials2 query: $query";
710 my $sth = $dbh->prepare($query);
711 $sth->execute;
712 my @serials;
714 while ( my $line = $sth->fetchrow_hashref ) {
715 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
716 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
717 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
718 push @serials, $line;
720 return @serials;
723 =head2 GetLatestSerials
725 \@serials = GetLatestSerials($subscriptionid,$limit)
726 get the $limit's latest serials arrived or missing for a given subscription
727 return :
728 a ref to an array which contains all of the latest serials stored into a hash.
730 =cut
732 sub GetLatestSerials {
733 my ( $subscriptionid, $limit ) = @_;
734 my $dbh = C4::Context->dbh;
736 # status = 2 is "arrived"
737 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
738 FROM serial
739 WHERE subscriptionid = ?
740 AND (status =2 or status=4)
741 ORDER BY planneddate DESC LIMIT 0,$limit
743 my $sth = $dbh->prepare($strsth);
744 $sth->execute($subscriptionid);
745 my @serials;
746 while ( my $line = $sth->fetchrow_hashref ) {
747 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
748 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
749 push @serials, $line;
752 return \@serials;
755 =head2 GetDistributedTo
757 $distributedto=GetDistributedTo($subscriptionid)
758 This function returns the field distributedto for the subscription matching subscriptionid
760 =cut
762 sub GetDistributedTo {
763 my $dbh = C4::Context->dbh;
764 my $distributedto;
765 my $subscriptionid = @_;
766 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
767 my $sth = $dbh->prepare($query);
768 $sth->execute($subscriptionid);
769 return ($distributedto) = $sth->fetchrow;
772 =head2 GetNextSeq
774 GetNextSeq($val)
775 $val is a hashref containing all the attributes of the table 'subscription'
776 This function get the next issue for the subscription given on input arg
777 return:
778 a list containing all the input params updated.
780 =cut
782 # sub GetNextSeq {
783 # my ($val) =@_;
784 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
785 # $calculated = $val->{numberingmethod};
786 # # calculate the (expected) value of the next issue recieved.
787 # $newlastvalue1 = $val->{lastvalue1};
788 # # check if we have to increase the new value.
789 # $newinnerloop1 = $val->{innerloop1}+1;
790 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
791 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
792 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
793 # $calculated =~ s/\{X\}/$newlastvalue1/g;
795 # $newlastvalue2 = $val->{lastvalue2};
796 # # check if we have to increase the new value.
797 # $newinnerloop2 = $val->{innerloop2}+1;
798 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
799 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
800 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
801 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
803 # $newlastvalue3 = $val->{lastvalue3};
804 # # check if we have to increase the new value.
805 # $newinnerloop3 = $val->{innerloop3}+1;
806 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
807 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
808 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
809 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
810 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
813 sub GetNextSeq {
814 my ($val) = @_;
815 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
816 my $pattern = $val->{numberpattern};
817 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
818 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
819 $calculated = $val->{numberingmethod};
820 $newlastvalue1 = $val->{lastvalue1};
821 $newlastvalue2 = $val->{lastvalue2};
822 $newlastvalue3 = $val->{lastvalue3};
823 $newlastvalue1 = $val->{lastvalue1};
825 # check if we have to increase the new value.
826 $newinnerloop1 = $val->{innerloop1} + 1;
827 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
828 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
829 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
830 $calculated =~ s/\{X\}/$newlastvalue1/g;
832 $newlastvalue2 = $val->{lastvalue2};
834 # check if we have to increase the new value.
835 $newinnerloop2 = $val->{innerloop2} + 1;
836 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
837 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
838 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
839 if ( $pattern == 6 ) {
840 if ( $val->{hemisphere} == 2 ) {
841 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
842 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
843 } else {
844 my $newlastvalue2seq = $seasons[$newlastvalue2];
845 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
847 } else {
848 $calculated =~ s/\{Y\}/$newlastvalue2/g;
851 $newlastvalue3 = $val->{lastvalue3};
853 # check if we have to increase the new value.
854 $newinnerloop3 = $val->{innerloop3} + 1;
855 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
856 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
857 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
858 $calculated =~ s/\{Z\}/$newlastvalue3/g;
860 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
863 =head2 GetSeq
865 $calculated = GetSeq($val)
866 $val is a hashref containing all the attributes of the table 'subscription'
867 this function transforms {X},{Y},{Z} to 150,0,0 for example.
868 return:
869 the sequence in integer format
871 =cut
873 sub GetSeq {
874 my ($val) = @_;
875 my $pattern = $val->{numberpattern};
876 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
877 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
878 my $calculated = $val->{numberingmethod};
879 my $x = $val->{'lastvalue1'};
880 $calculated =~ s/\{X\}/$x/g;
881 my $newlastvalue2 = $val->{'lastvalue2'};
883 if ( $pattern == 6 ) {
884 if ( $val->{hemisphere} == 2 ) {
885 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
886 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
887 } else {
888 my $newlastvalue2seq = $seasons[$newlastvalue2];
889 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
891 } else {
892 $calculated =~ s/\{Y\}/$newlastvalue2/g;
894 my $z = $val->{'lastvalue3'};
895 $calculated =~ s/\{Z\}/$z/g;
896 return $calculated;
899 =head2 GetExpirationDate
901 $sensddate = GetExpirationDate($subscriptionid, [$startdate])
903 this function return the next expiration date for a subscription given on input args.
905 return
906 the enddate or undef
908 =cut
910 sub GetExpirationDate {
911 my ( $subscriptionid, $startdate ) = @_;
912 my $dbh = C4::Context->dbh;
913 my $subscription = GetSubscription($subscriptionid);
914 my $enddate;
916 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
917 $enddate = $startdate || $subscription->{startdate};
918 my @date = split( /-/, $enddate );
919 return if ( scalar(@date) != 3 || not check_date(@date) );
920 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
922 # If Not Irregular
923 if ( my $length = $subscription->{numberlength} ) {
925 #calculate the date of the last issue.
926 for ( my $i = 1 ; $i <= $length ; $i++ ) {
927 $enddate = GetNextDate( $enddate, $subscription );
929 } elsif ( $subscription->{monthlength} ) {
930 if ( $$subscription{startdate} ) {
931 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
932 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
934 } elsif ( $subscription->{weeklength} ) {
935 if ( $$subscription{startdate} ) {
936 my @date = split( /-/, $subscription->{startdate} );
937 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
938 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
941 return $enddate;
942 } else {
943 return;
947 =head2 CountSubscriptionFromBiblionumber
949 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
950 this returns a count of the subscriptions for a given biblionumber
951 return :
952 the number of subscriptions
954 =cut
956 sub CountSubscriptionFromBiblionumber {
957 my ($biblionumber) = @_;
958 my $dbh = C4::Context->dbh;
959 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
960 my $sth = $dbh->prepare($query);
961 $sth->execute($biblionumber);
962 my $subscriptionsnumber = $sth->fetchrow;
963 return $subscriptionsnumber;
966 =head2 ModSubscriptionHistory
968 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
970 this function modifies the history of a subscription. Put your new values on input arg.
971 returns the number of rows affected
973 =cut
975 sub ModSubscriptionHistory {
976 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
977 my $dbh = C4::Context->dbh;
978 my $query = "UPDATE subscriptionhistory
979 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
980 WHERE subscriptionid=?
982 my $sth = $dbh->prepare($query);
983 $recievedlist =~ s/^; //;
984 $missinglist =~ s/^; //;
985 $opacnote =~ s/^; //;
986 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
987 return $sth->rows;
990 =head2 ModSerialStatus
992 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
994 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
995 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
997 =cut
999 sub ModSerialStatus {
1000 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1002 #It is a usual serial
1003 # 1st, get previous status :
1004 my $dbh = C4::Context->dbh;
1005 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1006 my $sth = $dbh->prepare($query);
1007 $sth->execute($serialid);
1008 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1010 # change status & update subscriptionhistory
1011 my $val;
1012 if ( $status == 6 ) {
1013 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1015 else {
1016 my $query =
1017 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1018 $sth = $dbh->prepare($query);
1019 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1020 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1021 $sth = $dbh->prepare($query);
1022 $sth->execute($subscriptionid);
1023 my $val = $sth->fetchrow_hashref;
1024 unless ( $val->{manualhistory} ) {
1025 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1026 $sth = $dbh->prepare($query);
1027 $sth->execute($subscriptionid);
1028 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1029 if ( $status == 2 ) {
1031 $recievedlist .= "; $serialseq"
1032 unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1035 # warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1036 $missinglist .= "; $serialseq"
1037 if ( $status == 4
1038 and not index( "$missinglist", "$serialseq" ) >= 0 );
1039 $missinglist .= "; not issued $serialseq"
1040 if ( $status == 5
1041 and index( "$missinglist", "$serialseq" ) >= 0 );
1042 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1043 $sth = $dbh->prepare($query);
1044 $recievedlist =~ s/^; //;
1045 $missinglist =~ s/^; //;
1046 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1050 # create new waited entry if needed (ie : was a "waited" and has changed)
1051 if ( $oldstatus == 1 && $status != 1 ) {
1052 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1053 $sth = $dbh->prepare($query);
1054 $sth->execute($subscriptionid);
1055 my $val = $sth->fetchrow_hashref;
1057 # next issue number
1058 my (
1059 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1060 $newinnerloop1, $newinnerloop2, $newinnerloop3
1061 ) = GetNextSeq($val);
1063 # next date (calculated from actual date & frequency parameters)
1064 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1065 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1066 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1067 WHERE subscriptionid = ?";
1068 $sth = $dbh->prepare($query);
1069 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1071 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1072 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1073 SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1076 return;
1079 =head2 GetNextExpected
1081 $nextexpected = GetNextExpected($subscriptionid)
1083 Get the planneddate for the current expected issue of the subscription.
1085 returns a hashref:
1087 $nextexepected = {
1088 serialid => int
1089 planneddate => C4::Dates object
1092 =cut
1094 sub GetNextExpected($) {
1095 my ($subscriptionid) = @_;
1096 my $dbh = C4::Context->dbh;
1097 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1099 # Each subscription has only one 'expected' issue, with serial.status==1.
1100 $sth->execute( $subscriptionid, 1 );
1101 my ( $nextissue ) = $sth->fetchrow_hashref;
1102 if( !$nextissue){
1103 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1104 $sth->execute( $subscriptionid );
1105 $nextissue = $sth->fetchrow_hashref;
1107 if (!defined $nextissue->{planneddate}) {
1108 # or should this default to 1st Jan ???
1109 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1111 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1112 return $nextissue;
1116 =head2 ModNextExpected
1118 ModNextExpected($subscriptionid,$date)
1120 Update the planneddate for the current expected issue of the subscription.
1121 This will modify all future prediction results.
1123 C<$date> is a C4::Dates object.
1125 returns 0
1127 =cut
1129 sub ModNextExpected($$) {
1130 my ( $subscriptionid, $date ) = @_;
1131 my $dbh = C4::Context->dbh;
1133 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1134 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1136 # Each subscription has only one 'expected' issue, with serial.status==1.
1137 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1138 return 0;
1142 =head2 ModSubscription
1144 this function modifies a subscription. Put all new values on input args.
1145 returns the number of rows affected
1147 =cut
1149 sub ModSubscription {
1150 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1151 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1152 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1153 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1154 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1155 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1156 ) = @_;
1158 # warn $irregularity;
1159 my $dbh = C4::Context->dbh;
1160 my $query = "UPDATE subscription
1161 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1162 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1163 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1164 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1165 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1166 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1167 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1168 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1169 ,enddate=?
1170 WHERE subscriptionid = ?";
1172 #warn "query :".$query;
1173 my $sth = $dbh->prepare($query);
1174 $sth->execute(
1175 $auser, $branchcode, $aqbooksellerid, $cost,
1176 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1177 $dow, "$irregularity", $numberpattern, $numberlength,
1178 $weeklength, $monthlength, $add1, $every1,
1179 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1180 $add2, $every2, $whenmorethan2, $setto2,
1181 $lastvalue2, $innerloop2, $add3, $every3,
1182 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1183 $numberingmethod, $status, $biblionumber, $callnumber,
1184 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1185 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1186 $graceperiod, $location, $enddate, $subscriptionid
1188 my $rows = $sth->rows;
1190 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1191 return $rows;
1194 =head2 NewSubscription
1196 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1197 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1198 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1199 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1200 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1201 $numberingmethod, $status, $notes, $serialsadditems,
1202 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1204 Create a new subscription with value given on input args.
1206 return :
1207 the id of this new subscription
1209 =cut
1211 sub NewSubscription {
1212 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1213 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1214 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1215 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1216 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1217 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1218 ) = @_;
1219 my $dbh = C4::Context->dbh;
1221 #save subscription (insert into database)
1222 my $query = qq|
1223 INSERT INTO subscription
1224 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1225 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1226 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1227 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1228 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1229 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1230 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1231 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1232 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1234 my $sth = $dbh->prepare($query);
1235 $sth->execute(
1236 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1237 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1238 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1239 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1240 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1241 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1244 #then create the 1st waited number
1245 my $subscriptionid = $dbh->{'mysql_insertid'};
1246 $query = qq(
1247 INSERT INTO subscriptionhistory
1248 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1249 VALUES (?,?,?,?,?)
1251 $sth = $dbh->prepare($query);
1252 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1254 # reread subscription to get a hash (for calculation of the 1st issue number)
1255 $query = qq(
1256 SELECT *
1257 FROM subscription
1258 WHERE subscriptionid = ?
1260 $sth = $dbh->prepare($query);
1261 $sth->execute($subscriptionid);
1262 my $val = $sth->fetchrow_hashref;
1264 # calculate issue number
1265 my $serialseq = GetSeq($val);
1266 $query = qq|
1267 INSERT INTO serial
1268 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1269 VALUES (?,?,?,?,?,?)
1271 $sth = $dbh->prepare($query);
1272 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1274 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1276 #set serial flag on biblio if not already set.
1277 my ( $null, ($bib) ) = GetBiblio($biblionumber);
1278 if ( !$bib->{'serial'} ) {
1279 my $record = GetMarcBiblio($biblionumber);
1280 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1281 if ($tag) {
1282 eval { $record->field($tag)->update( $subf => 1 ); };
1284 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1286 return $subscriptionid;
1289 =head2 ReNewSubscription
1291 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1293 this function renew a subscription with values given on input args.
1295 =cut
1297 sub ReNewSubscription {
1298 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1299 my $dbh = C4::Context->dbh;
1300 my $subscription = GetSubscription($subscriptionid);
1301 my $query = qq|
1302 SELECT *
1303 FROM biblio
1304 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1305 WHERE biblio.biblionumber=?
1307 my $sth = $dbh->prepare($query);
1308 $sth->execute( $subscription->{biblionumber} );
1309 my $biblio = $sth->fetchrow_hashref;
1311 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1313 NewSuggestion(
1314 { 'suggestedby' => $user,
1315 'title' => $subscription->{bibliotitle},
1316 'author' => $biblio->{author},
1317 'publishercode' => $biblio->{publishercode},
1318 'note' => $biblio->{note},
1319 'biblionumber' => $subscription->{biblionumber}
1324 # renew subscription
1325 $query = qq|
1326 UPDATE subscription
1327 SET startdate=?,numberlength=?,weeklength=?,monthlength=?
1328 WHERE subscriptionid=?
1330 $sth = $dbh->prepare($query);
1331 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1332 my $enddate = GetExpirationDate($subscriptionid);
1333 $debug && warn "enddate :$enddate";
1334 $query = qq|
1335 UPDATE subscription
1336 SET enddate=?
1337 WHERE subscriptionid=?
1339 $sth = $dbh->prepare($query);
1340 $sth->execute( $enddate, $subscriptionid );
1341 $query = qq|
1342 UPDATE subscriptionhistory
1343 SET histenddate=?
1344 WHERE subscriptionid=?
1346 $sth = $dbh->prepare($query);
1347 $sth->execute( $enddate, $subscriptionid );
1349 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1350 return;
1353 =head2 NewIssue
1355 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1357 Create a new issue stored on the database.
1358 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1359 returns the serial id
1361 =cut
1363 sub NewIssue {
1364 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1365 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1367 my $dbh = C4::Context->dbh;
1368 my $query = qq|
1369 INSERT INTO serial
1370 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1371 VALUES (?,?,?,?,?,?,?)
1373 my $sth = $dbh->prepare($query);
1374 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1375 my $serialid = $dbh->{'mysql_insertid'};
1376 $query = qq|
1377 SELECT missinglist,recievedlist
1378 FROM subscriptionhistory
1379 WHERE subscriptionid=?
1381 $sth = $dbh->prepare($query);
1382 $sth->execute($subscriptionid);
1383 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1385 if ( $status == 2 ) {
1386 ### TODO Add a feature that improves recognition and description.
1387 ### As such count (serialseq) i.e. : N18,2(N19),N20
1388 ### Would use substr and index But be careful to previous presence of ()
1389 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1391 if ( $status == 4 ) {
1392 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1394 $query = qq|
1395 UPDATE subscriptionhistory
1396 SET recievedlist=?, missinglist=?
1397 WHERE subscriptionid=?
1399 $sth = $dbh->prepare($query);
1400 $recievedlist =~ s/^; //;
1401 $missinglist =~ s/^; //;
1402 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1403 return $serialid;
1406 =head2 ItemizeSerials
1408 ItemizeSerials($serialid, $info);
1409 $info is a hashref containing barcode branch, itemcallnumber, status, location
1410 $serialid the serialid
1411 return :
1412 1 if the itemize is a succes.
1413 0 and @error otherwise. @error containts the list of errors found.
1415 =cut
1417 sub ItemizeSerials {
1418 my ( $serialid, $info ) = @_;
1419 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1421 my $dbh = C4::Context->dbh;
1422 my $query = qq|
1423 SELECT *
1424 FROM serial
1425 WHERE serialid=?
1427 my $sth = $dbh->prepare($query);
1428 $sth->execute($serialid);
1429 my $data = $sth->fetchrow_hashref;
1430 if ( C4::Context->preference("RoutingSerials") ) {
1432 # check for existing biblioitem relating to serial issue
1433 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1434 my $bibitemno = 0;
1435 for ( my $i = 0 ; $i < $count ; $i++ ) {
1436 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1437 $bibitemno = $results[$i]->{'biblioitemnumber'};
1438 last;
1441 if ( $bibitemno == 0 ) {
1442 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1443 $sth->execute( $data->{'biblionumber'} );
1444 my $biblioitem = $sth->fetchrow_hashref;
1445 $biblioitem->{'volumedate'} = $data->{planneddate};
1446 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1447 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1451 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1452 if ( $info->{barcode} ) {
1453 my @errors;
1454 my $exists = itemdata( $info->{'barcode'} );
1455 push @errors, "barcode_not_unique" if ($exists);
1456 unless ($exists) {
1457 my $marcrecord = MARC::Record->new();
1458 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1459 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1460 $marcrecord->insert_fields_ordered($newField);
1461 if ( $info->{branch} ) {
1462 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1464 #warn "items.homebranch : $tag , $subfield";
1465 if ( $marcrecord->field($tag) ) {
1466 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1467 } else {
1468 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1469 $marcrecord->insert_fields_ordered($newField);
1471 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1473 #warn "items.holdingbranch : $tag , $subfield";
1474 if ( $marcrecord->field($tag) ) {
1475 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1476 } else {
1477 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1478 $marcrecord->insert_fields_ordered($newField);
1481 if ( $info->{itemcallnumber} ) {
1482 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1484 if ( $marcrecord->field($tag) ) {
1485 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1486 } else {
1487 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1488 $marcrecord->insert_fields_ordered($newField);
1491 if ( $info->{notes} ) {
1492 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1494 if ( $marcrecord->field($tag) ) {
1495 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1496 } else {
1497 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1498 $marcrecord->insert_fields_ordered($newField);
1501 if ( $info->{location} ) {
1502 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1504 if ( $marcrecord->field($tag) ) {
1505 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1506 } else {
1507 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1508 $marcrecord->insert_fields_ordered($newField);
1511 if ( $info->{status} ) {
1512 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1514 if ( $marcrecord->field($tag) ) {
1515 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1516 } else {
1517 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1518 $marcrecord->insert_fields_ordered($newField);
1521 if ( C4::Context->preference("RoutingSerials") ) {
1522 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1523 if ( $marcrecord->field($tag) ) {
1524 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1525 } else {
1526 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1527 $marcrecord->insert_fields_ordered($newField);
1530 AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1531 return 1;
1533 return ( 0, @errors );
1537 =head2 HasSubscriptionStrictlyExpired
1539 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1541 the subscription has stricly expired when today > the end subscription date
1543 return :
1544 1 if true, 0 if false, -1 if the expiration date is not set.
1546 =cut
1548 sub HasSubscriptionStrictlyExpired {
1550 # Getting end of subscription date
1551 my ($subscriptionid) = @_;
1552 my $dbh = C4::Context->dbh;
1553 my $subscription = GetSubscription($subscriptionid);
1554 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1556 # If the expiration date is set
1557 if ( $expirationdate != 0 ) {
1558 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1560 # Getting today's date
1561 my ( $nowyear, $nowmonth, $nowday ) = Today();
1563 # if today's date > expiration date, then the subscription has stricly expired
1564 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1565 return 1;
1566 } else {
1567 return 0;
1569 } else {
1571 # There are some cases where the expiration date is not set
1572 # As we can't determine if the subscription has expired on a date-basis,
1573 # we return -1;
1574 return -1;
1578 =head2 HasSubscriptionExpired
1580 $has_expired = HasSubscriptionExpired($subscriptionid)
1582 the subscription has expired when the next issue to arrive is out of subscription limit.
1584 return :
1585 0 if the subscription has not expired
1586 1 if the subscription has expired
1587 2 if has subscription does not have a valid expiration date set
1589 =cut
1591 sub HasSubscriptionExpired {
1592 my ($subscriptionid) = @_;
1593 my $dbh = C4::Context->dbh;
1594 my $subscription = GetSubscription($subscriptionid);
1595 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1596 my $expirationdate = $subscription->{enddate};
1597 if (!defined $expirationdate) {
1598 $expirationdate = q{};
1600 my $query = qq|
1601 SELECT max(planneddate)
1602 FROM serial
1603 WHERE subscriptionid=?
1605 my $sth = $dbh->prepare($query);
1606 $sth->execute($subscriptionid);
1607 my ($res) = $sth->fetchrow;
1608 return 0 unless $res;
1609 my @res = split( /-/, $res );
1610 my @endofsubscriptiondate = split( /-/, $expirationdate );
1611 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1612 return 1
1613 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1614 || ( !$res ) );
1615 return 0;
1616 } else {
1617 if ( $subscription->{'numberlength'} ) {
1618 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1619 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1620 return 0;
1621 } else {
1622 return 0;
1625 return 0; # Notice that you'll never get here.
1628 =head2 SetDistributedto
1630 SetDistributedto($distributedto,$subscriptionid);
1631 This function update the value of distributedto for a subscription given on input arg.
1633 =cut
1635 sub SetDistributedto {
1636 my ( $distributedto, $subscriptionid ) = @_;
1637 my $dbh = C4::Context->dbh;
1638 my $query = qq|
1639 UPDATE subscription
1640 SET distributedto=?
1641 WHERE subscriptionid=?
1643 my $sth = $dbh->prepare($query);
1644 $sth->execute( $distributedto, $subscriptionid );
1645 return;
1648 =head2 DelSubscription
1650 DelSubscription($subscriptionid)
1651 this function deletes subscription which has $subscriptionid as id.
1653 =cut
1655 sub DelSubscription {
1656 my ($subscriptionid) = @_;
1657 my $dbh = C4::Context->dbh;
1658 $subscriptionid = $dbh->quote($subscriptionid);
1659 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1660 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1661 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1663 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1666 =head2 DelIssue
1668 DelIssue($serialseq,$subscriptionid)
1669 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1671 returns the number of rows affected
1673 =cut
1675 sub DelIssue {
1676 my ($dataissue) = @_;
1677 my $dbh = C4::Context->dbh;
1678 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1680 my $query = qq|
1681 DELETE FROM serial
1682 WHERE serialid= ?
1683 AND subscriptionid= ?
1685 my $mainsth = $dbh->prepare($query);
1686 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1688 #Delete element from subscription history
1689 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1690 my $sth = $dbh->prepare($query);
1691 $sth->execute( $dataissue->{'subscriptionid'} );
1692 my $val = $sth->fetchrow_hashref;
1693 unless ( $val->{manualhistory} ) {
1694 my $query = qq|
1695 SELECT * FROM subscriptionhistory
1696 WHERE subscriptionid= ?
1698 my $sth = $dbh->prepare($query);
1699 $sth->execute( $dataissue->{'subscriptionid'} );
1700 my $data = $sth->fetchrow_hashref;
1701 my $serialseq = $dataissue->{'serialseq'};
1702 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1703 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1704 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1705 $sth = $dbh->prepare($strsth);
1706 $sth->execute( $dataissue->{'subscriptionid'} );
1709 return $mainsth->rows;
1712 =head2 GetLateOrMissingIssues
1714 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1716 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1718 return :
1719 the issuelist as an array of hash refs. Each element of this array contains
1720 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1722 =cut
1724 sub GetLateOrMissingIssues {
1725 my ( $supplierid, $serialid, $order ) = @_;
1726 my $dbh = C4::Context->dbh;
1727 my $sth;
1728 my $byserial = '';
1729 if ($serialid) {
1730 $byserial = "and serialid = " . $serialid;
1732 if ($order) {
1733 $order .= ", title";
1734 } else {
1735 $order = "title";
1737 if ($supplierid) {
1738 $sth = $dbh->prepare(
1739 "SELECT
1740 serialid, aqbooksellerid, name,
1741 biblio.title, planneddate, serialseq,
1742 serial.status, serial.subscriptionid, claimdate
1743 FROM serial
1744 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1745 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1746 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1747 WHERE subscription.subscriptionid = serial.subscriptionid
1748 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1749 AND subscription.aqbooksellerid=$supplierid
1750 $byserial
1751 ORDER BY $order"
1753 } else {
1754 $sth = $dbh->prepare(
1755 "SELECT
1756 serialid, aqbooksellerid, name,
1757 biblio.title, planneddate, serialseq,
1758 serial.status, serial.subscriptionid, claimdate
1759 FROM serial
1760 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1761 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1762 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1763 WHERE subscription.subscriptionid = serial.subscriptionid
1764 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1765 $byserial
1766 ORDER BY $order"
1769 $sth->execute;
1770 my @issuelist;
1771 while ( my $line = $sth->fetchrow_hashref ) {
1773 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1774 $line->{planneddate} = format_date( $line->{planneddate} );
1776 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1777 $line->{claimdate} = format_date( $line->{claimdate} );
1779 $line->{"status".$line->{status}} = 1;
1780 push @issuelist, $line;
1782 return @issuelist;
1785 =head2 removeMissingIssue
1787 removeMissingIssue($subscriptionid)
1789 this function removes an issue from being part of the missing string in
1790 subscriptionlist.missinglist column
1792 called when a missing issue is found from the serials-recieve.pl file
1794 =cut
1796 sub removeMissingIssue {
1797 my ( $sequence, $subscriptionid ) = @_;
1798 my $dbh = C4::Context->dbh;
1799 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1800 $sth->execute($subscriptionid);
1801 my $data = $sth->fetchrow_hashref;
1802 my $missinglist = $data->{'missinglist'};
1803 my $missinglistbefore = $missinglist;
1805 # warn $missinglist." before";
1806 $missinglist =~ s/($sequence)//;
1808 # warn $missinglist." after";
1809 if ( $missinglist ne $missinglistbefore ) {
1810 $missinglist =~ s/\|\s\|/\|/g;
1811 $missinglist =~ s/^\| //g;
1812 $missinglist =~ s/\|$//g;
1813 my $sth2 = $dbh->prepare(
1814 "UPDATE subscriptionhistory
1815 SET missinglist = ?
1816 WHERE subscriptionid = ?"
1818 $sth2->execute( $missinglist, $subscriptionid );
1820 return;
1823 =head2 updateClaim
1825 &updateClaim($serialid)
1827 this function updates the time when a claim is issued for late/missing items
1829 called from claims.pl file
1831 =cut
1833 sub updateClaim {
1834 my ($serialid) = @_;
1835 my $dbh = C4::Context->dbh;
1836 my $sth = $dbh->prepare(
1837 "UPDATE serial SET claimdate = now()
1838 WHERE serialid = ?
1841 $sth->execute($serialid);
1842 return;
1845 =head2 getsupplierbyserialid
1847 $result = getsupplierbyserialid($serialid)
1849 this function is used to find the supplier id given a serial id
1851 return :
1852 hashref containing serialid, subscriptionid, and aqbooksellerid
1854 =cut
1856 sub getsupplierbyserialid {
1857 my ($serialid) = @_;
1858 my $dbh = C4::Context->dbh;
1859 my $sth = $dbh->prepare(
1860 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1861 FROM serial
1862 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1863 WHERE serialid = ?
1866 $sth->execute($serialid);
1867 my $line = $sth->fetchrow_hashref;
1868 my $result = $line->{'aqbooksellerid'};
1869 return $result;
1872 =head2 check_routing
1874 $result = &check_routing($subscriptionid)
1876 this function checks to see if a serial has a routing list and returns the count of routingid
1877 used to show either an 'add' or 'edit' link
1879 =cut
1881 sub check_routing {
1882 my ($subscriptionid) = @_;
1883 my $dbh = C4::Context->dbh;
1884 my $sth = $dbh->prepare(
1885 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
1886 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1887 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1890 $sth->execute($subscriptionid);
1891 my $line = $sth->fetchrow_hashref;
1892 my $result = $line->{'routingids'};
1893 return $result;
1896 =head2 addroutingmember
1898 addroutingmember($borrowernumber,$subscriptionid)
1900 this function takes a borrowernumber and subscriptionid and adds the member to the
1901 routing list for that serial subscription and gives them a rank on the list
1902 of either 1 or highest current rank + 1
1904 =cut
1906 sub addroutingmember {
1907 my ( $borrowernumber, $subscriptionid ) = @_;
1908 my $rank;
1909 my $dbh = C4::Context->dbh;
1910 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1911 $sth->execute($subscriptionid);
1912 while ( my $line = $sth->fetchrow_hashref ) {
1913 if ( $line->{'rank'} > 0 ) {
1914 $rank = $line->{'rank'} + 1;
1915 } else {
1916 $rank = 1;
1919 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1920 $sth->execute( $subscriptionid, $borrowernumber, $rank );
1923 =head2 reorder_members
1925 reorder_members($subscriptionid,$routingid,$rank)
1927 this function is used to reorder the routing list
1929 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1930 - it gets all members on list puts their routingid's into an array
1931 - removes the one in the array that is $routingid
1932 - then reinjects $routingid at point indicated by $rank
1933 - then update the database with the routingids in the new order
1935 =cut
1937 sub reorder_members {
1938 my ( $subscriptionid, $routingid, $rank ) = @_;
1939 my $dbh = C4::Context->dbh;
1940 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1941 $sth->execute($subscriptionid);
1942 my @result;
1943 while ( my $line = $sth->fetchrow_hashref ) {
1944 push( @result, $line->{'routingid'} );
1947 # To find the matching index
1948 my $i;
1949 my $key = -1; # to allow for 0 being a valid response
1950 for ( $i = 0 ; $i < @result ; $i++ ) {
1951 if ( $routingid == $result[$i] ) {
1952 $key = $i; # save the index
1953 last;
1957 # if index exists in array then move it to new position
1958 if ( $key > -1 && $rank > 0 ) {
1959 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1960 my $moving_item = splice( @result, $key, 1 );
1961 splice( @result, $new_rank, 0, $moving_item );
1963 for ( my $j = 0 ; $j < @result ; $j++ ) {
1964 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1965 $sth->execute;
1967 return;
1970 =head2 delroutingmember
1972 delroutingmember($routingid,$subscriptionid)
1974 this function either deletes one member from routing list if $routingid exists otherwise
1975 deletes all members from the routing list
1977 =cut
1979 sub delroutingmember {
1981 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
1982 my ( $routingid, $subscriptionid ) = @_;
1983 my $dbh = C4::Context->dbh;
1984 if ($routingid) {
1985 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
1986 $sth->execute($routingid);
1987 reorder_members( $subscriptionid, $routingid );
1988 } else {
1989 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
1990 $sth->execute($subscriptionid);
1992 return;
1995 =head2 getroutinglist
1997 ($count,@routinglist) = getroutinglist($subscriptionid)
1999 this gets the info from the subscriptionroutinglist for $subscriptionid
2001 return :
2002 a count of the number of members on routinglist
2003 the routinglist as an array. Each element of the array contains a hash_ref containing
2004 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2006 =cut
2008 sub getroutinglist {
2009 my ($subscriptionid) = @_;
2010 my $dbh = C4::Context->dbh;
2011 my $sth = $dbh->prepare(
2012 "SELECT routingid, borrowernumber, ranking, biblionumber
2013 FROM subscription
2014 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2015 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2018 $sth->execute($subscriptionid);
2019 my @routinglist;
2020 my $count = 0;
2021 while ( my $line = $sth->fetchrow_hashref ) {
2022 $count++;
2023 push( @routinglist, $line );
2025 return ( $count, @routinglist );
2028 =head2 countissuesfrom
2030 $result = countissuesfrom($subscriptionid,$startdate)
2032 Returns a count of serial rows matching the given subsctiptionid
2033 with published date greater than startdate
2035 =cut
2037 sub countissuesfrom {
2038 my ( $subscriptionid, $startdate ) = @_;
2039 my $dbh = C4::Context->dbh;
2040 my $query = qq|
2041 SELECT count(*)
2042 FROM serial
2043 WHERE subscriptionid=?
2044 AND serial.publisheddate>?
2046 my $sth = $dbh->prepare($query);
2047 $sth->execute( $subscriptionid, $startdate );
2048 my ($countreceived) = $sth->fetchrow;
2049 return $countreceived;
2052 =head2 CountIssues
2054 $result = CountIssues($subscriptionid)
2056 Returns a count of serial rows matching the given subsctiptionid
2058 =cut
2060 sub CountIssues {
2061 my ($subscriptionid) = @_;
2062 my $dbh = C4::Context->dbh;
2063 my $query = qq|
2064 SELECT count(*)
2065 FROM serial
2066 WHERE subscriptionid=?
2068 my $sth = $dbh->prepare($query);
2069 $sth->execute($subscriptionid);
2070 my ($countreceived) = $sth->fetchrow;
2071 return $countreceived;
2074 =head2 HasItems
2076 $result = HasItems($subscriptionid)
2078 returns a count of items from serial matching the subscriptionid
2080 =cut
2082 sub HasItems {
2083 my ($subscriptionid) = @_;
2084 my $dbh = C4::Context->dbh;
2085 my $query = q|
2086 SELECT COUNT(serialitems.itemnumber)
2087 FROM serial
2088 LEFT JOIN serialitems USING(serialid)
2089 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2091 my $sth=$dbh->prepare($query);
2092 $sth->execute($subscriptionid);
2093 my ($countitems)=$sth->fetchrow_array();
2094 return $countitems;
2097 =head2 abouttoexpire
2099 $result = abouttoexpire($subscriptionid)
2101 this function alerts you to the penultimate issue for a serial subscription
2103 returns 1 - if this is the penultimate issue
2104 returns 0 - if not
2106 =cut
2108 sub abouttoexpire {
2109 my ($subscriptionid) = @_;
2110 my $dbh = C4::Context->dbh;
2111 my $subscription = GetSubscription($subscriptionid);
2112 my $per = $subscription->{'periodicity'};
2113 if ($per && $per % 16 > 0){
2114 my $expirationdate = GetExpirationDate($subscriptionid);
2115 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2116 my @res;
2117 if (defined $res) {
2118 @res=split (/-/,$res);
2119 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2120 } else { # default an undefined value
2121 @res=Date::Calc::Today;
2123 my @endofsubscriptiondate=split(/-/,$expirationdate);
2124 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 0, 0, 0);
2125 my @datebeforeend;
2126 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2127 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2128 return 1 if ( @res &&
2129 (@datebeforeend &&
2130 Delta_Days($res[0],$res[1],$res[2],
2131 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2132 (@endofsubscriptiondate &&
2133 Delta_Days($res[0],$res[1],$res[2],
2134 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2135 return 0;
2136 } elsif ($subscription->{numberlength}>0) {
2137 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2139 return 0;
2142 sub in_array { # used in next sub down
2143 my ( $val, @elements ) = @_;
2144 foreach my $elem (@elements) {
2145 if ( $val == $elem ) {
2146 return 1;
2149 return 0;
2152 =head2 GetNextDate
2154 $resultdate = GetNextDate($planneddate,$subscription)
2156 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2157 exists an irregularity
2158 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2159 skipped then the returned date will be 2007-05-10
2161 return :
2162 $resultdate - then next date in the sequence
2164 Return 0 if periodicity==0
2166 =cut
2168 sub GetNextDate(@) {
2169 my ( $planneddate, $subscription ) = @_;
2170 my @irreg = split( /\,/, $subscription->{irregularity} );
2172 #date supposed to be in ISO.
2174 my ( $year, $month, $day ) = split( /-/, $planneddate );
2175 $month = 1 unless ($month);
2176 $day = 1 unless ($day);
2177 my @resultdate;
2179 # warn "DOW $dayofweek";
2180 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2181 return 0;
2184 # daily : n / week
2185 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2186 # renaming this pattern from 1/day to " n / week ".
2187 if ( $subscription->{periodicity} == 1 ) {
2188 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2189 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2190 else {
2191 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2192 $dayofweek = 0 if ( $dayofweek == 7 );
2193 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2194 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2195 $dayofweek++;
2198 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2202 # 1 week
2203 if ( $subscription->{periodicity} == 2 ) {
2204 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2205 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2206 else {
2207 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2209 #FIXME: if two consecutive irreg, do we only skip one?
2210 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2211 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2212 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2215 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2219 # 1 / 2 weeks
2220 if ( $subscription->{periodicity} == 3 ) {
2221 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2222 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2223 else {
2224 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2225 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2226 ### BUGFIX was previously +1 ^
2227 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2228 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2231 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2235 # 1 / 3 weeks
2236 if ( $subscription->{periodicity} == 4 ) {
2237 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2238 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2239 else {
2240 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2241 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2242 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2243 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2246 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2249 my $tmpmonth = $month;
2250 if ( $year && $month && $day ) {
2251 if ( $subscription->{periodicity} == 5 ) {
2252 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2253 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2254 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2255 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2258 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2260 if ( $subscription->{periodicity} == 6 ) {
2261 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2262 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2263 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2264 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2267 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2269 if ( $subscription->{periodicity} == 7 ) {
2270 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2271 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2272 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2273 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2276 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2278 if ( $subscription->{periodicity} == 8 ) {
2279 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2280 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2281 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2282 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2285 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2287 if ( $subscription->{periodicity} == 9 ) {
2288 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2289 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2290 ### BUFIX Seems to need more Than One ?
2291 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2292 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2295 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2297 if ( $subscription->{periodicity} == 10 ) {
2298 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2300 if ( $subscription->{periodicity} == 11 ) {
2301 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2304 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2306 return "$resultdate";
2309 =head2 itemdata
2311 $item = itemdata($barcode);
2313 Looks up the item with the given barcode, and returns a
2314 reference-to-hash containing information about that item. The keys of
2315 the hash are the fields from the C<items> and C<biblioitems> tables in
2316 the Koha database.
2318 =cut
2321 sub itemdata {
2322 my ($barcode) = @_;
2323 my $dbh = C4::Context->dbh;
2324 my $sth = $dbh->prepare(
2325 "Select * from items LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
2326 WHERE barcode=?"
2328 $sth->execute($barcode);
2329 my $data = $sth->fetchrow_hashref;
2330 $sth->finish;
2331 return ($data);
2335 __END__
2337 =head1 AUTHOR
2339 Koha Development Team <http://koha-community.org/>
2341 =cut