3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2010 Biblibre
6 # This file is part of Koha.
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
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.
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.
23 use C4::Dates qw(format_date format_date_in_iso);
24 use Date::Calc qw(:all);
25 use POSIX qw(strftime setlocale LC_TIME);
27 use C4::Log; # logaction
29 use C4::Serials::Frequency;
30 use C4::Serials::Numberpattern;
32 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
35 $VERSION = 3.07.00.049; # set version for version checking
39 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
40 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
42 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
43 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
44 &GetSubscriptionHistoryFromSubscriptionId
46 &GetNextSeq &GetSeq &NewIssue &ItemizeSerials &GetSerials
47 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
48 &ReNewSubscription &GetLateIssues &GetLateOrMissingIssues
49 &GetSerialInformation &AddItem2Serial
50 &PrepareSerialsData &GetNextExpected &ModNextExpected
52 &UpdateClaimdateIssues
53 &GetSuppliersWithLateIssues &getsupplierbyserialid
54 &GetDistributedTo &SetDistributedTo
55 &getroutinglist &delroutingmember &addroutingmember
57 &check_routing &updateClaim &removeMissingIssue
60 &GetSubscriptionsFromBorrower
67 C4::Serials - Serials Module Functions
75 Functions for handling subscriptions, claims routing etc.
80 =head2 GetSuppliersWithLateIssues
82 $supplierlist = GetSuppliersWithLateIssues()
84 this function get all suppliers with late issues.
87 an array_ref of suppliers each entry is a hash_ref containing id and name
88 the array is in name order
92 sub GetSuppliersWithLateIssues {
93 my $dbh = C4::Context->dbh;
95 SELECT DISTINCT id, name
97 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
98 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
101 (planneddate < now() AND serial.status=1)
102 OR serial.STATUS = 3 OR serial.STATUS = 4
104 AND subscription.closed = 0
106 return $dbh->selectall_arrayref($query, { Slice => {} });
111 @issuelist = GetLateIssues($supplierid)
113 this function selects late issues from the database
116 the issuelist as an array. Each element of this array contains a hashi_ref containing
117 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
122 my ($supplierid) = @_;
123 my $dbh = C4::Context->dbh;
127 SELECT name,title,planneddate,serialseq,serial.subscriptionid
129 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
130 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
131 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
132 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
133 AND subscription.aqbooksellerid=?
134 AND subscription.closed = 0
137 $sth = $dbh->prepare($query);
138 $sth->execute($supplierid);
141 SELECT name,title,planneddate,serialseq,serial.subscriptionid
143 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
144 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
145 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
146 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
147 AND subscription.closed = 0
150 $sth = $dbh->prepare($query);
156 while ( my $line = $sth->fetchrow_hashref ) {
157 $odd++ unless $line->{title} eq $last_title;
158 $line->{title} = "" if $line->{title} eq $last_title;
159 $last_title = $line->{title} if ( $line->{title} );
160 $line->{planneddate} = format_date( $line->{planneddate} );
161 push @issuelist, $line;
166 =head2 GetSubscriptionHistoryFromSubscriptionId
168 $history = GetSubscriptionHistoryFromSubscriptionId($subscriptionid);
170 This function returns the subscription history as a hashref
174 sub GetSubscriptionHistoryFromSubscriptionId {
175 my ($subscriptionid) = @_;
177 return unless $subscriptionid;
179 my $dbh = C4::Context->dbh;
182 FROM subscriptionhistory
183 WHERE subscriptionid = ?
185 my $sth = $dbh->prepare($query);
186 $sth->execute($subscriptionid);
187 my $results = $sth->fetchrow_hashref;
193 =head2 GetSerialStatusFromSerialId
195 $sth = GetSerialStatusFromSerialId();
196 this function returns a statement handle
197 After this function, don't forget to execute it by using $sth->execute($serialid)
199 $sth = $dbh->prepare($query).
203 sub GetSerialStatusFromSerialId {
204 my $dbh = C4::Context->dbh;
210 return $dbh->prepare($query);
213 =head2 GetSerialInformation
216 $data = GetSerialInformation($serialid);
217 returns a hash_ref containing :
218 items : items marcrecord (can be an array)
220 subscription table field
221 + information about subscription expiration
225 sub GetSerialInformation {
227 my $dbh = C4::Context->dbh;
229 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
230 if ( C4::Context->preference('IndependantBranches')
231 && C4::Context->userenv
232 && C4::Context->userenv->{'flags'} != 1
233 && C4::Context->userenv->{'branch'} ) {
235 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
238 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
241 my $rq = $dbh->prepare($query);
242 $rq->execute($serialid);
243 my $data = $rq->fetchrow_hashref;
245 # create item information if we have serialsadditems for this subscription
246 if ( $data->{'serialsadditems'} ) {
247 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
248 $queryitem->execute($serialid);
249 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
251 if ( scalar(@$itemnumbers) > 0 ) {
252 foreach my $itemnum (@$itemnumbers) {
254 #It is ASSUMED that GetMarcItem ALWAYS WORK...
255 #Maybe GetMarcItem should return values on failure
256 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
257 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
258 $itemprocessed->{'itemnumber'} = $itemnum->[0];
259 $itemprocessed->{'itemid'} = $itemnum->[0];
260 $itemprocessed->{'serialid'} = $serialid;
261 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
262 push @{ $data->{'items'} }, $itemprocessed;
265 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
266 $itemprocessed->{'itemid'} = "N$serialid";
267 $itemprocessed->{'serialid'} = $serialid;
268 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
269 $itemprocessed->{'countitems'} = 0;
270 push @{ $data->{'items'} }, $itemprocessed;
273 $data->{ "status" . $data->{'serstatus'} } = 1;
274 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
275 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
279 =head2 AddItem2Serial
281 $rows = AddItem2Serial($serialid,$itemnumber);
282 Adds an itemnumber to Serial record
283 returns the number of rows affected
288 my ( $serialid, $itemnumber ) = @_;
289 my $dbh = C4::Context->dbh;
290 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
291 $rq->execute( $serialid, $itemnumber );
295 =head2 UpdateClaimdateIssues
297 UpdateClaimdateIssues($serialids,[$date]);
299 Update Claimdate for issues in @$serialids list with date $date
304 sub UpdateClaimdateIssues {
305 my ( $serialids, $date ) = @_;
306 my $dbh = C4::Context->dbh;
307 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
309 UPDATE serial SET claimdate = ?, status = 7
310 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
311 my $rq = $dbh->prepare($query);
312 $rq->execute($date, @$serialids);
316 =head2 GetSubscription
318 $subs = GetSubscription($subscriptionid)
319 this function returns the subscription which has $subscriptionid as id.
321 a hashref. This hash containts
322 subscription, subscriptionhistory, aqbooksellers.name, biblio.title
326 sub GetSubscription {
327 my ($subscriptionid) = @_;
328 my $dbh = C4::Context->dbh;
330 SELECT subscription.*,
331 subscriptionhistory.*,
332 aqbooksellers.name AS aqbooksellername,
333 biblio.title AS bibliotitle,
334 subscription.biblionumber as bibnum);
335 if ( C4::Context->preference('IndependantBranches')
336 && C4::Context->userenv
337 && C4::Context->userenv->{'flags'} != 1
338 && C4::Context->userenv->{'branch'} ) {
340 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
344 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
345 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
346 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
347 WHERE subscription.subscriptionid = ?
350 # if (C4::Context->preference('IndependantBranches') &&
351 # C4::Context->userenv &&
352 # C4::Context->userenv->{'flags'} != 1){
353 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
354 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
356 $debug and warn "query : $query\nsubsid :$subscriptionid";
357 my $sth = $dbh->prepare($query);
358 $sth->execute($subscriptionid);
359 return $sth->fetchrow_hashref;
362 =head2 GetFullSubscription
364 $array_ref = GetFullSubscription($subscriptionid)
365 this function reads the serial table.
369 sub GetFullSubscription {
370 my ($subscriptionid) = @_;
371 my $dbh = C4::Context->dbh;
373 SELECT serial.serialid,
376 serial.publisheddate,
378 serial.notes as notes,
379 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
380 aqbooksellers.name as aqbooksellername,
381 biblio.title as bibliotitle,
382 subscription.branchcode AS branchcode,
383 subscription.subscriptionid AS subscriptionid |;
384 if ( C4::Context->preference('IndependantBranches')
385 && C4::Context->userenv
386 && C4::Context->userenv->{'flags'} != 1
387 && C4::Context->userenv->{'branch'} ) {
389 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
393 LEFT JOIN subscription ON
394 (serial.subscriptionid=subscription.subscriptionid )
395 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
396 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
397 WHERE serial.subscriptionid = ?
399 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
400 serial.subscriptionid
402 $debug and warn "GetFullSubscription query: $query";
403 my $sth = $dbh->prepare($query);
404 $sth->execute($subscriptionid);
405 return $sth->fetchall_arrayref( {} );
408 =head2 PrepareSerialsData
410 $array_ref = PrepareSerialsData($serialinfomation)
411 where serialinformation is a hashref array
415 sub PrepareSerialsData {
421 my $aqbooksellername;
425 my $previousnote = "";
427 foreach my $subs (@{$lines}) {
428 for my $datefield ( qw(publisheddate planneddate) ) {
429 # handle both undef and undef returned as 0000-00-00
430 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
431 $subs->{$datefield} = 'XXX';
434 $subs->{$datefield} = format_date( $subs->{$datefield} );
437 $subs->{ "status" . $subs->{'status'} } = 1;
438 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
440 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
441 $year = $subs->{'year'};
445 if ( $tmpresults{$year} ) {
446 push @{ $tmpresults{$year}->{'serials'} }, $subs;
448 $tmpresults{$year} = {
450 'aqbooksellername' => $subs->{'aqbooksellername'},
451 'bibliotitle' => $subs->{'bibliotitle'},
452 'serials' => [$subs],
457 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
458 push @res, $tmpresults{$key};
463 =head2 GetSubscriptionsFromBiblionumber
465 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
466 this function get the subscription list. it reads the subscription table.
468 reference to an array of subscriptions which have the biblionumber given on input arg.
469 each element of this array is a hashref containing
470 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
474 sub GetSubscriptionsFromBiblionumber {
475 my ($biblionumber) = @_;
476 my $dbh = C4::Context->dbh;
478 SELECT subscription.*,
480 subscriptionhistory.*,
481 aqbooksellers.name AS aqbooksellername,
482 biblio.title AS bibliotitle
484 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
485 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
486 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
487 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
488 WHERE subscription.biblionumber = ?
490 my $sth = $dbh->prepare($query);
491 $sth->execute($biblionumber);
493 while ( my $subs = $sth->fetchrow_hashref ) {
494 $subs->{startdate} = format_date( $subs->{startdate} );
495 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
496 $subs->{histenddate} = format_date( $subs->{histenddate} );
497 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
498 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
499 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
500 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
501 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
502 $subs->{ "status" . $subs->{'status'} } = 1;
503 $subs->{'cannotedit'} =
504 ( C4::Context->preference('IndependantBranches')
505 && C4::Context->userenv
506 && C4::Context->userenv->{flags} % 2 != 1
507 && C4::Context->userenv->{branch}
508 && $subs->{branchcode}
509 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
511 if ( $subs->{enddate} eq '0000-00-00' ) {
512 $subs->{enddate} = '';
514 $subs->{enddate} = format_date( $subs->{enddate} );
516 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
517 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
523 =head2 GetFullSubscriptionsFromBiblionumber
525 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
526 this function reads the serial table.
530 sub GetFullSubscriptionsFromBiblionumber {
531 my ($biblionumber) = @_;
532 my $dbh = C4::Context->dbh;
534 SELECT serial.serialid,
537 serial.publisheddate,
539 serial.notes as notes,
540 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
541 biblio.title as bibliotitle,
542 subscription.branchcode AS branchcode,
543 subscription.subscriptionid AS subscriptionid|;
544 if ( C4::Context->preference('IndependantBranches')
545 && C4::Context->userenv
546 && C4::Context->userenv->{'flags'} != 1
547 && C4::Context->userenv->{'branch'} ) {
549 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
554 LEFT JOIN subscription ON
555 (serial.subscriptionid=subscription.subscriptionid)
556 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
557 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
558 WHERE subscription.biblionumber = ?
560 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
561 serial.subscriptionid
563 my $sth = $dbh->prepare($query);
564 $sth->execute($biblionumber);
565 return $sth->fetchall_arrayref( {} );
568 =head2 GetSubscriptions
570 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
571 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
573 a table of hashref. Each hash containt the subscription.
577 sub GetSubscriptions {
578 my ( $string, $issn, $ean, $biblionumber ) = @_;
580 #return unless $title or $ISSN or $biblionumber;
581 my $dbh = C4::Context->dbh;
584 SELECT subscriptionhistory.*, subscription.*, biblio.title,biblioitems.issn,biblio.biblionumber
586 LEFT JOIN subscriptionhistory USING(subscriptionid)
587 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
588 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
593 $sqlwhere = " WHERE biblio.biblionumber=?";
594 push @bind_params, $biblionumber;
598 my @strings_to_search;
599 @strings_to_search = map { "%$_%" } split( / /, $string );
600 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
601 push @bind_params, @strings_to_search;
602 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
603 $debug && warn "$tmpstring";
604 $tmpstring =~ s/^AND //;
605 push @sqlstrings, $tmpstring;
607 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
611 my @strings_to_search;
612 @strings_to_search = map { "%$_%" } split( / /, $issn );
613 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
614 push @bind_params, @strings_to_search;
615 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
616 $debug && warn "$tmpstring";
617 $tmpstring =~ s/^OR //;
618 push @sqlstrings, $tmpstring;
620 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
624 my @strings_to_search;
625 @strings_to_search = map { "$_" } split( / /, $ean );
626 foreach my $index ( qw(biblioitems.ean) ) {
627 push @bind_params, @strings_to_search;
628 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
629 $debug && warn "$tmpstring";
630 $tmpstring =~ s/^OR //;
631 push @sqlstrings, $tmpstring;
633 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
636 $sql .= "$sqlwhere ORDER BY title";
637 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
638 $sth = $dbh->prepare($sql);
639 $sth->execute(@bind_params);
642 while ( my $line = $sth->fetchrow_hashref ) {
643 $line->{'cannotedit'} =
644 ( C4::Context->preference('IndependantBranches')
645 && C4::Context->userenv
646 && C4::Context->userenv->{flags} % 2 != 1
647 && C4::Context->userenv->{branch}
648 && $line->{branchcode}
649 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
650 push @results, $line;
655 =head2 SearchSubscriptions
657 @results = SearchSubscriptions($args);
658 $args is a hashref. Its keys can be contained: title, issn, ean, publisher, bookseller and branchcode
660 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.
663 a table of hashref. Each hash containt the subscription.
667 sub SearchSubscriptions {
671 SELECT subscription.*, subscriptionhistory.*, biblio.*, biblioitems.issn
673 LEFT JOIN subscriptionhistory USING(subscriptionid)
674 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
675 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
676 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
680 if( $args->{biblionumber} ) {
681 push @where_strs, "biblio.biblionumber = ?";
682 push @where_args, $args->{biblionumber};
684 if( $args->{title} ){
685 my @words = split / /, $args->{title};
687 foreach my $word (@words) {
688 push @strs, "biblio.title LIKE ?";
689 push @args, "%$word%";
692 push @where_strs, '(' . join (' AND ', @strs) . ')';
693 push @where_args, @args;
697 push @where_strs, "biblioitems.issn LIKE ?";
698 push @where_args, "%$args->{issn}%";
701 push @where_strs, "biblioitems.ean LIKE ?";
702 push @where_args, "%$args->{ean}%";
704 if( $args->{publisher} ){
705 push @where_strs, "biblioitems.publishercode LIKE ?";
706 push @where_args, "%$args->{publisher}%";
708 if( $args->{bookseller} ){
709 push @where_strs, "aqbooksellers.name LIKE ?";
710 push @where_args, "%$args->{bookseller}%";
712 if( $args->{branch} ){
713 push @where_strs, "subscription.branchcode = ?";
714 push @where_args, "$args->{branch}";
716 if( defined $args->{closed} ){
717 push @where_strs, "subscription.closed = ?";
718 push @where_args, "$args->{closed}";
721 $query .= " WHERE " . join(" AND ", @where_strs);
724 my $dbh = C4::Context->dbh;
725 my $sth = $dbh->prepare($query);
726 $sth->execute(@where_args);
727 my $results = $sth->fetchall_arrayref( {} );
736 ($totalissues,@serials) = GetSerials($subscriptionid);
737 this function gets every serial not arrived for a given subscription
738 as well as the number of issues registered in the database (all types)
739 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
741 FIXME: We should return \@serials.
746 my ( $subscriptionid, $count ) = @_;
747 my $dbh = C4::Context->dbh;
749 # status = 2 is "arrived"
751 $count = 5 unless ($count);
753 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
755 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
756 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
757 my $sth = $dbh->prepare($query);
758 $sth->execute($subscriptionid);
760 while ( my $line = $sth->fetchrow_hashref ) {
761 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
762 for my $datefield ( qw( planneddate publisheddate) ) {
763 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
764 $line->{$datefield} = format_date( $line->{$datefield});
766 $line->{$datefield} = q{};
769 push @serials, $line;
772 # OK, now add the last 5 issues arrives/missing
773 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
775 WHERE subscriptionid = ?
776 AND (status in (2,4,5))
777 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
779 $sth = $dbh->prepare($query);
780 $sth->execute($subscriptionid);
781 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
783 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
784 for my $datefield ( qw( planneddate publisheddate) ) {
785 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
786 $line->{$datefield} = format_date( $line->{$datefield});
788 $line->{$datefield} = q{};
792 push @serials, $line;
795 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
796 $sth = $dbh->prepare($query);
797 $sth->execute($subscriptionid);
798 my ($totalissues) = $sth->fetchrow;
799 return ( $totalissues, @serials );
804 @serials = GetSerials2($subscriptionid,$status);
805 this function returns every serial waited for a given subscription
806 as well as the number of issues registered in the database (all types)
807 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
812 my ( $subscription, $status ) = @_;
813 my $dbh = C4::Context->dbh;
815 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
817 WHERE subscriptionid=$subscription AND status IN ($status)
818 ORDER BY publisheddate,serialid DESC
820 $debug and warn "GetSerials2 query: $query";
821 my $sth = $dbh->prepare($query);
825 while ( my $line = $sth->fetchrow_hashref ) {
826 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
827 # Format dates for display
828 for my $datefield ( qw( planneddate publisheddate ) ) {
829 if ($line->{$datefield} =~m/^00/) {
830 $line->{$datefield} = q{};
833 $line->{$datefield} = format_date( $line->{$datefield} );
836 push @serials, $line;
841 =head2 GetLatestSerials
843 \@serials = GetLatestSerials($subscriptionid,$limit)
844 get the $limit's latest serials arrived or missing for a given subscription
846 a ref to an array which contains all of the latest serials stored into a hash.
850 sub GetLatestSerials {
851 my ( $subscriptionid, $limit ) = @_;
852 my $dbh = C4::Context->dbh;
854 # status = 2 is "arrived"
855 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
857 WHERE subscriptionid = ?
858 AND (status =2 or status=4)
859 ORDER BY publisheddate DESC LIMIT 0,$limit
861 my $sth = $dbh->prepare($strsth);
862 $sth->execute($subscriptionid);
864 while ( my $line = $sth->fetchrow_hashref ) {
865 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
866 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
867 push @serials, $line;
873 =head2 GetDistributedTo
875 $distributedto=GetDistributedTo($subscriptionid)
876 This function returns the field distributedto for the subscription matching subscriptionid
880 sub GetDistributedTo {
881 my $dbh = C4::Context->dbh;
883 my $subscriptionid = @_;
884 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
885 my $sth = $dbh->prepare($query);
886 $sth->execute($subscriptionid);
887 return ($distributedto) = $sth->fetchrow;
893 $val is a hashref containing all the attributes of the table 'subscription'
894 This function get the next issue for the subscription given on input arg
896 a list containing all the input params updated.
901 my ($val, $planneddate) = @_;
902 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3,
903 $newinnerloop1, $newinnerloop2, $newinnerloop3 );
906 if($val->{'skip_serialseq'}) {
907 my @irreg = split /;/, $val->{'irregularity'};
909 my $irregularities = {};
910 $irregularities->{$_} = 1 foreach(@irreg);
911 my $issueno = GetFictiveIssueNumber($val, $planneddate) + 1;
912 while($irregularities->{$issueno}) {
919 my $pattern = $val->{numberpattern};
920 $calculated = $val->{numberingmethod};
921 my $locale = $val->{locale};
922 $newlastvalue1 = $val->{lastvalue1} || 0;
923 $newlastvalue2 = $val->{lastvalue2} || 0;
924 $newlastvalue3 = $val->{lastvalue3} || 0;
925 $newinnerloop1 = $val->{innerloop1} || 0;
926 $newinnerloop2 = $val->{innerloop2} || 0;
927 $newinnerloop3 = $val->{innerloop3} || 0;
930 $calc{$_} = 1 if ($val->{'numberingmethod'} =~ /\{$_\}/);
933 for(my $i = 0; $i < $count; $i++) {
935 # check if we have to increase the new value.
937 if ($newinnerloop1 >= $val->{every1}) {
939 $newlastvalue1 += $val->{add1};
941 # reset counter if needed.
942 $newlastvalue1 = $val->{setto1} if ($newlastvalue1 > $val->{whenmorethan1});
945 # check if we have to increase the new value.
947 if ($newinnerloop2 >= $val->{every2}) {
949 $newlastvalue2 += $val->{add2};
951 # reset counter if needed.
952 $newlastvalue2 = $val->{setto2} if ($newlastvalue2 > $val->{whenmorethan2});
955 # check if we have to increase the new value.
957 if ($newinnerloop3 >= $val->{every3}) {
959 $newlastvalue3 += $val->{add3};
961 # reset counter if needed.
962 $newlastvalue3 = $val->{setto3} if ($newlastvalue3 > $val->{whenmorethan3});
966 my $newlastvalue1string = _numeration( $newlastvalue1, $val->{numbering1}, $locale );
967 $calculated =~ s/\{X\}/$newlastvalue1string/g;
970 my $newlastvalue2string = _numeration( $newlastvalue2, $val->{numbering2}, $locale );
971 $calculated =~ s/\{Y\}/$newlastvalue2string/g;
974 my $newlastvalue3string = _numeration( $newlastvalue3, $val->{numbering3}, $locale );
975 $calculated =~ s/\{Z\}/$newlastvalue3string/g;
979 $newlastvalue1, $newlastvalue2, $newlastvalue3,
980 $newinnerloop1, $newinnerloop2, $newinnerloop3);
985 $calculated = GetSeq($val)
986 $val is a hashref containing all the attributes of the table 'subscription'
987 this function transforms {X},{Y},{Z} to 150,0,0 for example.
989 the sequence in integer format
995 my $locale = $val->{locale};
997 my $pattern = $val->{numberpattern};
998 my $calculated = $val->{numberingmethod};
1000 my $newlastvalue1 = $val->{'lastvalue1'} || 0;
1001 $newlastvalue1 = _numeration($newlastvalue1, $val->{numbering1}, $locale) if ($val->{numbering1}); # reset counter if needed.
1002 $calculated =~ s/\{X\}/$newlastvalue1/g;
1004 my $newlastvalue2 = $val->{'lastvalue2'} || 0;
1005 $newlastvalue2 = _numeration($newlastvalue2, $val->{numbering2}, $locale) if ($val->{numbering2}); # reset counter if needed.
1006 $calculated =~ s/\{Y\}/$newlastvalue2/g;
1008 my $newlastvalue3 = $val->{'lastvalue3'} || 0;
1009 $newlastvalue3 = _numeration($newlastvalue3, $val->{numbering3}, $locale) if ($val->{numbering3}); # reset counter if needed.
1010 $calculated =~ s/\{Z\}/$newlastvalue3/g;
1014 =head2 GetExpirationDate
1016 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1018 this function return the next expiration date for a subscription given on input args.
1021 the enddate or undef
1025 sub GetExpirationDate {
1026 my ( $subscriptionid, $startdate ) = @_;
1027 my $dbh = C4::Context->dbh;
1028 my $subscription = GetSubscription($subscriptionid);
1031 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1032 $enddate = $startdate || $subscription->{startdate};
1033 my @date = split( /-/, $enddate );
1034 return if ( scalar(@date) != 3 || not check_date(@date) );
1035 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity});
1036 if ( $frequency and $frequency->{unit} ) {
1039 if ( my $length = $subscription->{numberlength} ) {
1041 #calculate the date of the last issue.
1042 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1043 $enddate = GetNextDate( $subscription, $enddate );
1045 } elsif ( $subscription->{monthlength} ) {
1046 if ( $$subscription{startdate} ) {
1047 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1048 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1050 } elsif ( $subscription->{weeklength} ) {
1051 if ( $$subscription{startdate} ) {
1052 my @date = split( /-/, $subscription->{startdate} );
1053 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1054 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1057 $enddate = $subscription->{enddate};
1061 return $subscription->{enddate};
1065 =head2 CountSubscriptionFromBiblionumber
1067 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1068 this returns a count of the subscriptions for a given biblionumber
1070 the number of subscriptions
1074 sub CountSubscriptionFromBiblionumber {
1075 my ($biblionumber) = @_;
1076 my $dbh = C4::Context->dbh;
1077 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1078 my $sth = $dbh->prepare($query);
1079 $sth->execute($biblionumber);
1080 my $subscriptionsnumber = $sth->fetchrow;
1081 return $subscriptionsnumber;
1084 =head2 ModSubscriptionHistory
1086 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1088 this function modifies the history of a subscription. Put your new values on input arg.
1089 returns the number of rows affected
1093 sub ModSubscriptionHistory {
1094 my ( $subscriptionid, $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote ) = @_;
1095 my $dbh = C4::Context->dbh;
1096 my $query = "UPDATE subscriptionhistory
1097 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1098 WHERE subscriptionid=?
1100 my $sth = $dbh->prepare($query);
1101 $receivedlist =~ s/^; // if $receivedlist;
1102 $missinglist =~ s/^; // if $missinglist;
1103 $opacnote =~ s/^; // if $opacnote;
1104 $sth->execute( $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1108 # Update missinglist field, used by ModSerialStatus
1109 sub _update_missinglist {
1110 my $subscriptionid = shift;
1112 my $dbh = C4::Context->dbh;
1113 my @missingserials = GetSerials2($subscriptionid, "4,5");
1115 foreach (@missingserials) {
1116 if($_->{'status'} == 4) {
1117 $missinglist .= $_->{'serialseq'} . "; ";
1118 } elsif($_->{'status'} == 5) {
1119 $missinglist .= "not issued " . $_->{'serialseq'} . "; ";
1122 $missinglist =~ s/; $//;
1124 UPDATE subscriptionhistory
1126 WHERE subscriptionid = ?
1128 my $sth = $dbh->prepare($query);
1129 $sth->execute($missinglist, $subscriptionid);
1132 # Update recievedlist field, used by ModSerialStatus
1133 sub _update_receivedlist {
1134 my $subscriptionid = shift;
1136 my $dbh = C4::Context->dbh;
1137 my @receivedserials = GetSerials2($subscriptionid, "2");
1139 foreach (@receivedserials) {
1140 $receivedlist .= $_->{'serialseq'} . "; ";
1142 $receivedlist =~ s/; $//;
1144 UPDATE subscriptionhistory
1145 SET recievedlist = ?
1146 WHERE subscriptionid = ?
1148 my $sth = $dbh->prepare($query);
1149 $sth->execute($receivedlist, $subscriptionid);
1152 =head2 ModSerialStatus
1154 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1156 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1157 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1161 sub ModSerialStatus {
1162 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1165 #It is a usual serial
1166 # 1st, get previous status :
1167 my $dbh = C4::Context->dbh;
1168 my $query = "SELECT serial.subscriptionid,serial.status,subscription.periodicity
1169 FROM serial, subscription
1170 WHERE serial.subscriptionid=subscription.subscriptionid
1172 my $sth = $dbh->prepare($query);
1173 $sth->execute($serialid);
1174 my ( $subscriptionid, $oldstatus, $periodicity ) = $sth->fetchrow;
1175 my $frequency = GetSubscriptionFrequency($periodicity);
1177 # change status & update subscriptionhistory
1179 if ( $status == 6 ) {
1180 DelIssue( { 'serialid' => $serialid, 'subscriptionid' => $subscriptionid, 'serialseq' => $serialseq } );
1183 unless ($frequency->{'unit'}) {
1184 if ( not $planneddate or $planneddate eq '0000-00-00' ) { $planneddate = C4::Dates->new()->output('iso') };
1185 if ( not $publisheddate or $publisheddate eq '0000-00-00' ) { $publisheddate = C4::Dates->new()->output('iso') };
1187 my $query = 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1188 $sth = $dbh->prepare($query);
1189 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1190 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1191 $sth = $dbh->prepare($query);
1192 $sth->execute($subscriptionid);
1193 my $val = $sth->fetchrow_hashref;
1194 unless ( $val->{manualhistory} ) {
1195 if ( $status == 2 || ($oldstatus == 2 && $status != 2) ) {
1196 _update_receivedlist($subscriptionid);
1198 if($status == 4 || $status == 5
1199 || ($oldstatus == 4 && $status != 4)
1200 || ($oldstatus == 5 && $status != 5)) {
1201 _update_missinglist($subscriptionid);
1206 # create new waited entry if needed (ie : was a "waited" and has changed)
1207 if ( $oldstatus == 1 && $status != 1 ) {
1209 SELECT subscription.*, subscription_numberpatterns.*,
1210 subscription_frequencies.*
1212 LEFT JOIN subscription_numberpatterns ON subscription.numberpattern = subscription_numberpatterns.id
1213 LEFT JOIN subscription_frequencies ON subscription.periodicity = subscription_frequencies.id
1214 WHERE subscriptionid = ?
1216 $sth = $dbh->prepare($query);
1217 $sth->execute($subscriptionid);
1218 my $val = $sth->fetchrow_hashref;
1221 my ( $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 ) = GetNextSeq($val, $publisheddate);
1223 # next date (calculated from actual date & frequency parameters)
1224 my $nextpublisheddate = GetNextDate($val, $publisheddate, 1);
1225 my $nextpubdate = $nextpublisheddate;
1226 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpubdate, $nextpubdate );
1227 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1228 WHERE subscriptionid = ?";
1229 $sth = $dbh->prepare($query);
1230 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1232 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1233 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1234 require C4::Letters;
1235 C4::Letters::SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1242 =head2 GetNextExpected
1244 $nextexpected = GetNextExpected($subscriptionid)
1246 Get the planneddate for the current expected issue of the subscription.
1252 planneddate => ISO date
1257 sub GetNextExpected {
1258 my ($subscriptionid) = @_;
1260 my $dbh = C4::Context->dbh;
1264 WHERE subscriptionid = ?
1268 my $sth = $dbh->prepare($query);
1270 # Each subscription has only one 'expected' issue, with serial.status==1.
1271 $sth->execute( $subscriptionid, 1 );
1272 my $nextissue = $sth->fetchrow_hashref;
1273 if ( !$nextissue ) {
1277 WHERE subscriptionid = ?
1278 ORDER BY planneddate DESC
1281 $sth = $dbh->prepare($query);
1282 $sth->execute($subscriptionid);
1283 $nextissue = $sth->fetchrow_hashref;
1285 foreach(qw/planneddate publisheddate/) {
1286 if ( !defined $nextissue->{$_} ) {
1287 # or should this default to 1st Jan ???
1288 $nextissue->{$_} = strftime( '%Y-%m-%d', localtime );
1290 $nextissue->{$_} = ($nextissue->{$_} ne '0000-00-00')
1298 =head2 ModNextExpected
1300 ModNextExpected($subscriptionid,$date)
1302 Update the planneddate for the current expected issue of the subscription.
1303 This will modify all future prediction results.
1305 C<$date> is an ISO date.
1311 sub ModNextExpected {
1312 my ( $subscriptionid, $date ) = @_;
1313 my $dbh = C4::Context->dbh;
1315 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1316 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1318 # Each subscription has only one 'expected' issue, with serial.status==1.
1319 $sth->execute( $date, $date, $subscriptionid, 1 );
1324 =head2 GetSubscriptionIrregularities
1328 =item @irreg = &GetSubscriptionIrregularities($subscriptionid);
1329 get the list of irregularities for a subscription
1335 sub GetSubscriptionIrregularities {
1336 my $subscriptionid = shift;
1338 return undef unless $subscriptionid;
1340 my $dbh = C4::Context->dbh;
1344 WHERE subscriptionid = ?
1346 my $sth = $dbh->prepare($query);
1347 $sth->execute($subscriptionid);
1349 my ($result) = $sth->fetchrow_array;
1350 my @irreg = split /;/, $result;
1355 =head2 ModSubscription
1357 this function modifies a subscription. Put all new values on input args.
1358 returns the number of rows affected
1362 sub ModSubscription {
1364 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
1365 $periodicity, $firstacquidate, $irregularity, $numberpattern, $locale,
1366 $numberlength, $weeklength, $monthlength, $lastvalue1, $innerloop1,
1367 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, $status,
1368 $biblionumber, $callnumber, $notes, $letter, $manualhistory,
1369 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1370 $graceperiod, $location, $enddate, $subscriptionid, $skip_serialseq
1373 my $dbh = C4::Context->dbh;
1374 my $query = "UPDATE subscription
1375 SET librarian=?, branchcode=?, aqbooksellerid=?, cost=?, aqbudgetid=?,
1376 startdate=?, periodicity=?, firstacquidate=?, irregularity=?,
1377 numberpattern=?, locale=?, numberlength=?, weeklength=?, monthlength=?,
1378 lastvalue1=?, innerloop1=?, lastvalue2=?, innerloop2=?,
1379 lastvalue3=?, innerloop3=?, status=?, biblionumber=?,
1380 callnumber=?, notes=?, letter=?, manualhistory=?,
1381 internalnotes=?, serialsadditems=?, staffdisplaycount=?,
1382 opacdisplaycount=?, graceperiod=?, location = ?, enddate=?,
1384 WHERE subscriptionid = ?";
1386 my $sth = $dbh->prepare($query);
1388 $auser, $branchcode, $aqbooksellerid, $cost,
1389 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1390 $irregularity, $numberpattern, $locale, $numberlength,
1391 $weeklength, $monthlength, $lastvalue1, $innerloop1,
1392 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
1393 $status, $biblionumber, $callnumber, $notes,
1394 $letter, ($manualhistory ? $manualhistory : 0),
1395 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1396 $graceperiod, $location, $enddate, $skip_serialseq,
1399 my $rows = $sth->rows;
1401 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1405 =head2 NewSubscription
1407 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1408 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1409 $lastvalue1,$innerloop1,$lastvalue2,$innerloop2,$lastvalue3,$innerloop3,
1410 $status, $notes, $letter, $firstacquidate, $irregularity, $numberpattern,
1411 $callnumber, $hemisphere, $manualhistory, $internalnotes, $serialsadditems,
1412 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq);
1414 Create a new subscription with value given on input args.
1417 the id of this new subscription
1421 sub NewSubscription {
1423 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1424 $startdate, $periodicity, $numberlength, $weeklength, $monthlength,
1425 $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, $lastvalue3,
1426 $innerloop3, $status, $notes, $letter, $firstacquidate, $irregularity,
1427 $numberpattern, $locale, $callnumber, $manualhistory, $internalnotes,
1428 $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,
1429 $location, $enddate, $skip_serialseq
1431 my $dbh = C4::Context->dbh;
1433 #save subscription (insert into database)
1435 INSERT INTO subscription
1436 (librarian, branchcode, aqbooksellerid, cost, aqbudgetid,
1437 biblionumber, startdate, periodicity, numberlength, weeklength,
1438 monthlength, lastvalue1, innerloop1, lastvalue2, innerloop2,
1439 lastvalue3, innerloop3, status, notes, letter, firstacquidate,
1440 irregularity, numberpattern, locale, callnumber,
1441 manualhistory, internalnotes, serialsadditems, staffdisplaycount,
1442 opacdisplaycount, graceperiod, location, enddate, skip_serialseq)
1443 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1445 my $sth = $dbh->prepare($query);
1447 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1448 $startdate, $periodicity, $numberlength, $weeklength,
1449 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
1450 $lastvalue3, $innerloop3, $status, $notes, $letter,
1451 $firstacquidate, $irregularity, $numberpattern, $locale, $callnumber,
1452 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
1453 $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq
1456 my $subscriptionid = $dbh->{'mysql_insertid'};
1458 $enddate = GetExpirationDate( $subscriptionid, $startdate );
1462 WHERE subscriptionid=?
1464 $sth = $dbh->prepare($query);
1465 $sth->execute( $enddate, $subscriptionid );
1468 # then create the 1st expected number
1470 INSERT INTO subscriptionhistory
1471 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1474 $sth = $dbh->prepare($query);
1475 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1477 # reread subscription to get a hash (for calculation of the 1st issue number)
1481 LEFT JOIN subscription_numberpatterns ON subscription.numberpattern = subscription_numberpatterns.id
1482 WHERE subscriptionid = ?
1484 $sth = $dbh->prepare($query);
1485 $sth->execute($subscriptionid);
1486 my $val = $sth->fetchrow_hashref;
1488 # calculate issue number
1489 my $serialseq = GetSeq($val);
1492 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1493 VALUES (?,?,?,?,?,?)
1495 $sth = $dbh->prepare($query);
1496 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1498 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1500 #set serial flag on biblio if not already set.
1501 my $bib = GetBiblio($biblionumber);
1502 if ( $bib and !$bib->{'serial'} ) {
1503 my $record = GetMarcBiblio($biblionumber);
1504 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1506 eval { $record->field($tag)->update( $subf => 1 ); };
1508 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1510 return $subscriptionid;
1513 =head2 ReNewSubscription
1515 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1517 this function renew a subscription with values given on input args.
1521 sub ReNewSubscription {
1522 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1523 my $dbh = C4::Context->dbh;
1524 my $subscription = GetSubscription($subscriptionid);
1528 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1529 WHERE biblio.biblionumber=?
1531 my $sth = $dbh->prepare($query);
1532 $sth->execute( $subscription->{biblionumber} );
1533 my $biblio = $sth->fetchrow_hashref;
1535 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1536 require C4::Suggestions;
1537 C4::Suggestions::NewSuggestion(
1538 { 'suggestedby' => $user,
1539 'title' => $subscription->{bibliotitle},
1540 'author' => $biblio->{author},
1541 'publishercode' => $biblio->{publishercode},
1542 'note' => $biblio->{note},
1543 'biblionumber' => $subscription->{biblionumber}
1548 # renew subscription
1551 SET startdate=?,numberlength=?,weeklength=?,monthlength=?
1552 WHERE subscriptionid=?
1554 $sth = $dbh->prepare($query);
1555 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1556 my $enddate = GetExpirationDate($subscriptionid);
1557 $debug && warn "enddate :$enddate";
1561 WHERE subscriptionid=?
1563 $sth = $dbh->prepare($query);
1564 $sth->execute( $enddate, $subscriptionid );
1566 UPDATE subscriptionhistory
1568 WHERE subscriptionid=?
1570 $sth = $dbh->prepare($query);
1571 $sth->execute( $enddate, $subscriptionid );
1573 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1579 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1581 Create a new issue stored on the database.
1582 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1583 returns the serial id
1588 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1589 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1591 my $dbh = C4::Context->dbh;
1594 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1595 VALUES (?,?,?,?,?,?,?)
1597 my $sth = $dbh->prepare($query);
1598 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1599 my $serialid = $dbh->{'mysql_insertid'};
1601 SELECT missinglist,recievedlist
1602 FROM subscriptionhistory
1603 WHERE subscriptionid=?
1605 $sth = $dbh->prepare($query);
1606 $sth->execute($subscriptionid);
1607 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1609 if ( $status == 2 ) {
1610 ### TODO Add a feature that improves recognition and description.
1611 ### As such count (serialseq) i.e. : N18,2(N19),N20
1612 ### Would use substr and index But be careful to previous presence of ()
1613 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1615 if ( $status == 4 ) {
1616 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1619 UPDATE subscriptionhistory
1620 SET recievedlist=?, missinglist=?
1621 WHERE subscriptionid=?
1623 $sth = $dbh->prepare($query);
1624 $recievedlist =~ s/^; //;
1625 $missinglist =~ s/^; //;
1626 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1630 =head2 ItemizeSerials
1632 ItemizeSerials($serialid, $info);
1633 $info is a hashref containing barcode branch, itemcallnumber, status, location
1634 $serialid the serialid
1636 1 if the itemize is a succes.
1637 0 and @error otherwise. @error containts the list of errors found.
1641 sub ItemizeSerials {
1642 my ( $serialid, $info ) = @_;
1643 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1645 my $dbh = C4::Context->dbh;
1651 my $sth = $dbh->prepare($query);
1652 $sth->execute($serialid);
1653 my $data = $sth->fetchrow_hashref;
1654 if ( C4::Context->preference("RoutingSerials") ) {
1656 # check for existing biblioitem relating to serial issue
1657 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1659 for ( my $i = 0 ; $i < $count ; $i++ ) {
1660 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1661 $bibitemno = $results[$i]->{'biblioitemnumber'};
1665 if ( $bibitemno == 0 ) {
1666 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1667 $sth->execute( $data->{'biblionumber'} );
1668 my $biblioitem = $sth->fetchrow_hashref;
1669 $biblioitem->{'volumedate'} = $data->{planneddate};
1670 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1671 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1675 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1676 if ( $info->{barcode} ) {
1678 if ( is_barcode_in_use( $info->{barcode} ) ) {
1679 push @errors, 'barcode_not_unique';
1681 my $marcrecord = MARC::Record->new();
1682 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1683 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1684 $marcrecord->insert_fields_ordered($newField);
1685 if ( $info->{branch} ) {
1686 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1688 #warn "items.homebranch : $tag , $subfield";
1689 if ( $marcrecord->field($tag) ) {
1690 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1692 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1693 $marcrecord->insert_fields_ordered($newField);
1695 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1697 #warn "items.holdingbranch : $tag , $subfield";
1698 if ( $marcrecord->field($tag) ) {
1699 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1701 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1702 $marcrecord->insert_fields_ordered($newField);
1705 if ( $info->{itemcallnumber} ) {
1706 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1708 if ( $marcrecord->field($tag) ) {
1709 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1711 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1712 $marcrecord->insert_fields_ordered($newField);
1715 if ( $info->{notes} ) {
1716 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1718 if ( $marcrecord->field($tag) ) {
1719 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1721 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1722 $marcrecord->insert_fields_ordered($newField);
1725 if ( $info->{location} ) {
1726 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1728 if ( $marcrecord->field($tag) ) {
1729 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1731 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1732 $marcrecord->insert_fields_ordered($newField);
1735 if ( $info->{status} ) {
1736 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1738 if ( $marcrecord->field($tag) ) {
1739 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1741 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1742 $marcrecord->insert_fields_ordered($newField);
1745 if ( C4::Context->preference("RoutingSerials") ) {
1746 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1747 if ( $marcrecord->field($tag) ) {
1748 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1750 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1751 $marcrecord->insert_fields_ordered($newField);
1755 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1758 return ( 0, @errors );
1762 =head2 HasSubscriptionStrictlyExpired
1764 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1766 the subscription has stricly expired when today > the end subscription date
1769 1 if true, 0 if false, -1 if the expiration date is not set.
1773 sub HasSubscriptionStrictlyExpired {
1775 # Getting end of subscription date
1776 my ($subscriptionid) = @_;
1777 my $dbh = C4::Context->dbh;
1778 my $subscription = GetSubscription($subscriptionid);
1779 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1781 # If the expiration date is set
1782 if ( $expirationdate != 0 ) {
1783 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1785 # Getting today's date
1786 my ( $nowyear, $nowmonth, $nowday ) = Today();
1788 # if today's date > expiration date, then the subscription has stricly expired
1789 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1796 # There are some cases where the expiration date is not set
1797 # As we can't determine if the subscription has expired on a date-basis,
1803 =head2 HasSubscriptionExpired
1805 $has_expired = HasSubscriptionExpired($subscriptionid)
1807 the subscription has expired when the next issue to arrive is out of subscription limit.
1810 0 if the subscription has not expired
1811 1 if the subscription has expired
1812 2 if has subscription does not have a valid expiration date set
1816 sub HasSubscriptionExpired {
1817 my ($subscriptionid) = @_;
1818 my $dbh = C4::Context->dbh;
1819 my $subscription = GetSubscription($subscriptionid);
1820 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity});
1821 if ( $frequency and $frequency->{unit} ) {
1822 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1823 if (!defined $expirationdate) {
1824 $expirationdate = q{};
1827 SELECT max(planneddate)
1829 WHERE subscriptionid=?
1831 my $sth = $dbh->prepare($query);
1832 $sth->execute($subscriptionid);
1833 my ($res) = $sth->fetchrow;
1834 if (!$res || $res=~m/^0000/) {
1837 my @res = split( /-/, $res );
1838 my @endofsubscriptiondate = split( /-/, $expirationdate );
1839 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1841 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1846 if ( $subscription->{'numberlength'} ) {
1847 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1848 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1854 return 0; # Notice that you'll never get here.
1857 =head2 SetDistributedto
1859 SetDistributedto($distributedto,$subscriptionid);
1860 This function update the value of distributedto for a subscription given on input arg.
1864 sub SetDistributedto {
1865 my ( $distributedto, $subscriptionid ) = @_;
1866 my $dbh = C4::Context->dbh;
1870 WHERE subscriptionid=?
1872 my $sth = $dbh->prepare($query);
1873 $sth->execute( $distributedto, $subscriptionid );
1877 =head2 DelSubscription
1879 DelSubscription($subscriptionid)
1880 this function deletes subscription which has $subscriptionid as id.
1884 sub DelSubscription {
1885 my ($subscriptionid) = @_;
1886 my $dbh = C4::Context->dbh;
1887 $subscriptionid = $dbh->quote($subscriptionid);
1888 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1889 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1890 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1892 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1897 DelIssue($serialseq,$subscriptionid)
1898 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1900 returns the number of rows affected
1905 my ($dataissue) = @_;
1906 my $dbh = C4::Context->dbh;
1907 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1912 AND subscriptionid= ?
1914 my $mainsth = $dbh->prepare($query);
1915 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1917 #Delete element from subscription history
1918 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1919 my $sth = $dbh->prepare($query);
1920 $sth->execute( $dataissue->{'subscriptionid'} );
1921 my $val = $sth->fetchrow_hashref;
1922 unless ( $val->{manualhistory} ) {
1924 SELECT * FROM subscriptionhistory
1925 WHERE subscriptionid= ?
1927 my $sth = $dbh->prepare($query);
1928 $sth->execute( $dataissue->{'subscriptionid'} );
1929 my $data = $sth->fetchrow_hashref;
1930 my $serialseq = $dataissue->{'serialseq'};
1931 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1932 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1933 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1934 $sth = $dbh->prepare($strsth);
1935 $sth->execute( $dataissue->{'subscriptionid'} );
1938 return $mainsth->rows;
1941 =head2 GetLateOrMissingIssues
1943 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1945 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1948 the issuelist as an array of hash refs. Each element of this array contains
1949 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1953 sub GetLateOrMissingIssues {
1954 my ( $supplierid, $serialid, $order ) = @_;
1955 my $dbh = C4::Context->dbh;
1959 $byserial = "and serialid = " . $serialid;
1962 $order .= ", title";
1967 $sth = $dbh->prepare(
1969 serialid, aqbooksellerid, name,
1970 biblio.title, planneddate, serialseq,
1971 serial.status, serial.subscriptionid, claimdate,
1972 subscription.branchcode
1974 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1975 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1976 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1977 WHERE subscription.subscriptionid = serial.subscriptionid
1978 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1979 AND subscription.aqbooksellerid=$supplierid
1984 $sth = $dbh->prepare(
1986 serialid, aqbooksellerid, name,
1987 biblio.title, planneddate, serialseq,
1988 serial.status, serial.subscriptionid, claimdate,
1989 subscription.branchcode
1991 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1992 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1993 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1994 WHERE subscription.subscriptionid = serial.subscriptionid
1995 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
2002 while ( my $line = $sth->fetchrow_hashref ) {
2004 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
2005 $line->{planneddate} = format_date( $line->{planneddate} );
2007 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
2008 $line->{claimdate} = format_date( $line->{claimdate} );
2010 $line->{"status".$line->{status}} = 1;
2011 push @issuelist, $line;
2016 =head2 removeMissingIssue
2018 removeMissingIssue($subscriptionid)
2020 this function removes an issue from being part of the missing string in
2021 subscriptionlist.missinglist column
2023 called when a missing issue is found from the serials-recieve.pl file
2027 sub removeMissingIssue {
2028 my ( $sequence, $subscriptionid ) = @_;
2029 my $dbh = C4::Context->dbh;
2030 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
2031 $sth->execute($subscriptionid);
2032 my $data = $sth->fetchrow_hashref;
2033 my $missinglist = $data->{'missinglist'};
2034 my $missinglistbefore = $missinglist;
2036 # warn $missinglist." before";
2037 $missinglist =~ s/($sequence)//;
2039 # warn $missinglist." after";
2040 if ( $missinglist ne $missinglistbefore ) {
2041 $missinglist =~ s/\|\s\|/\|/g;
2042 $missinglist =~ s/^\| //g;
2043 $missinglist =~ s/\|$//g;
2044 my $sth2 = $dbh->prepare(
2045 "UPDATE subscriptionhistory
2047 WHERE subscriptionid = ?"
2049 $sth2->execute( $missinglist, $subscriptionid );
2056 &updateClaim($serialid)
2058 this function updates the time when a claim is issued for late/missing items
2060 called from claims.pl file
2065 my ($serialid) = @_;
2066 my $dbh = C4::Context->dbh;
2067 my $sth = $dbh->prepare(
2068 "UPDATE serial SET claimdate = now()
2072 $sth->execute($serialid);
2076 =head2 getsupplierbyserialid
2078 $result = getsupplierbyserialid($serialid)
2080 this function is used to find the supplier id given a serial id
2083 hashref containing serialid, subscriptionid, and aqbooksellerid
2087 sub getsupplierbyserialid {
2088 my ($serialid) = @_;
2089 my $dbh = C4::Context->dbh;
2090 my $sth = $dbh->prepare(
2091 "SELECT serialid, serial.subscriptionid, aqbooksellerid
2093 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
2097 $sth->execute($serialid);
2098 my $line = $sth->fetchrow_hashref;
2099 my $result = $line->{'aqbooksellerid'};
2103 =head2 check_routing
2105 $result = &check_routing($subscriptionid)
2107 this function checks to see if a serial has a routing list and returns the count of routingid
2108 used to show either an 'add' or 'edit' link
2113 my ($subscriptionid) = @_;
2114 my $dbh = C4::Context->dbh;
2115 my $sth = $dbh->prepare(
2116 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
2117 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2118 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2121 $sth->execute($subscriptionid);
2122 my $line = $sth->fetchrow_hashref;
2123 my $result = $line->{'routingids'};
2127 =head2 addroutingmember
2129 addroutingmember($borrowernumber,$subscriptionid)
2131 this function takes a borrowernumber and subscriptionid and adds the member to the
2132 routing list for that serial subscription and gives them a rank on the list
2133 of either 1 or highest current rank + 1
2137 sub addroutingmember {
2138 my ( $borrowernumber, $subscriptionid ) = @_;
2140 my $dbh = C4::Context->dbh;
2141 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
2142 $sth->execute($subscriptionid);
2143 while ( my $line = $sth->fetchrow_hashref ) {
2144 if ( $line->{'rank'} > 0 ) {
2145 $rank = $line->{'rank'} + 1;
2150 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
2151 $sth->execute( $subscriptionid, $borrowernumber, $rank );
2154 =head2 reorder_members
2156 reorder_members($subscriptionid,$routingid,$rank)
2158 this function is used to reorder the routing list
2160 it takes the routingid of the member one wants to re-rank and the rank it is to move to
2161 - it gets all members on list puts their routingid's into an array
2162 - removes the one in the array that is $routingid
2163 - then reinjects $routingid at point indicated by $rank
2164 - then update the database with the routingids in the new order
2168 sub reorder_members {
2169 my ( $subscriptionid, $routingid, $rank ) = @_;
2170 my $dbh = C4::Context->dbh;
2171 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
2172 $sth->execute($subscriptionid);
2174 while ( my $line = $sth->fetchrow_hashref ) {
2175 push( @result, $line->{'routingid'} );
2178 # To find the matching index
2180 my $key = -1; # to allow for 0 being a valid response
2181 for ( $i = 0 ; $i < @result ; $i++ ) {
2182 if ( $routingid == $result[$i] ) {
2183 $key = $i; # save the index
2188 # if index exists in array then move it to new position
2189 if ( $key > -1 && $rank > 0 ) {
2190 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
2191 my $moving_item = splice( @result, $key, 1 );
2192 splice( @result, $new_rank, 0, $moving_item );
2194 for ( my $j = 0 ; $j < @result ; $j++ ) {
2195 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
2201 =head2 delroutingmember
2203 delroutingmember($routingid,$subscriptionid)
2205 this function either deletes one member from routing list if $routingid exists otherwise
2206 deletes all members from the routing list
2210 sub delroutingmember {
2212 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2213 my ( $routingid, $subscriptionid ) = @_;
2214 my $dbh = C4::Context->dbh;
2216 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2217 $sth->execute($routingid);
2218 reorder_members( $subscriptionid, $routingid );
2220 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2221 $sth->execute($subscriptionid);
2226 =head2 getroutinglist
2228 @routinglist = getroutinglist($subscriptionid)
2230 this gets the info from the subscriptionroutinglist for $subscriptionid
2233 the routinglist as an array. Each element of the array contains a hash_ref containing
2234 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2238 sub getroutinglist {
2239 my ($subscriptionid) = @_;
2240 my $dbh = C4::Context->dbh;
2241 my $sth = $dbh->prepare(
2242 'SELECT routingid, borrowernumber, ranking, biblionumber
2244 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2245 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2247 $sth->execute($subscriptionid);
2248 my $routinglist = $sth->fetchall_arrayref({});
2249 return @{$routinglist};
2252 =head2 countissuesfrom
2254 $result = countissuesfrom($subscriptionid,$startdate)
2256 Returns a count of serial rows matching the given subsctiptionid
2257 with published date greater than startdate
2261 sub countissuesfrom {
2262 my ( $subscriptionid, $startdate ) = @_;
2263 my $dbh = C4::Context->dbh;
2267 WHERE subscriptionid=?
2268 AND serial.publisheddate>?
2270 my $sth = $dbh->prepare($query);
2271 $sth->execute( $subscriptionid, $startdate );
2272 my ($countreceived) = $sth->fetchrow;
2273 return $countreceived;
2278 $result = CountIssues($subscriptionid)
2280 Returns a count of serial rows matching the given subsctiptionid
2285 my ($subscriptionid) = @_;
2286 my $dbh = C4::Context->dbh;
2290 WHERE subscriptionid=?
2292 my $sth = $dbh->prepare($query);
2293 $sth->execute($subscriptionid);
2294 my ($countreceived) = $sth->fetchrow;
2295 return $countreceived;
2300 $result = HasItems($subscriptionid)
2302 returns a count of items from serial matching the subscriptionid
2307 my ($subscriptionid) = @_;
2308 my $dbh = C4::Context->dbh;
2310 SELECT COUNT(serialitems.itemnumber)
2312 LEFT JOIN serialitems USING(serialid)
2313 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2315 my $sth=$dbh->prepare($query);
2316 $sth->execute($subscriptionid);
2317 my ($countitems)=$sth->fetchrow_array();
2321 =head2 abouttoexpire
2323 $result = abouttoexpire($subscriptionid)
2325 this function alerts you to the penultimate issue for a serial subscription
2327 returns 1 - if this is the penultimate issue
2333 my ($subscriptionid) = @_;
2334 my $dbh = C4::Context->dbh;
2335 my $subscription = GetSubscription($subscriptionid);
2336 my $per = $subscription->{'periodicity'};
2337 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($per);
2338 if ($frequency and $frequency->{unit}){
2339 my $expirationdate = GetExpirationDate($subscriptionid);
2340 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2341 my $nextdate = GetNextDate($subscription, $res);
2342 if(Date::Calc::Delta_Days(
2343 split( /-/, $nextdate ),
2344 split( /-/, $expirationdate )
2348 } elsif ($subscription->{numberlength}>0) {
2349 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2354 sub in_array { # used in next sub down
2355 my ( $val, @elements ) = @_;
2356 foreach my $elem (@elements) {
2357 if ( $val == $elem ) {
2364 =head2 GetSubscriptionsFromBorrower
2366 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2368 this gets the info from subscriptionroutinglist for each $subscriptionid
2371 a count of the serial subscription routing lists to which a patron belongs,
2372 with the titles of those serial subscriptions as an array. Each element of the array
2373 contains a hash_ref with subscriptionID and title of subscription.
2377 sub GetSubscriptionsFromBorrower {
2378 my ($borrowernumber) = @_;
2379 my $dbh = C4::Context->dbh;
2380 my $sth = $dbh->prepare(
2381 "SELECT subscription.subscriptionid, biblio.title
2383 JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2384 JOIN subscriptionroutinglist USING (subscriptionid)
2385 WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2388 $sth->execute($borrowernumber);
2391 while ( my $line = $sth->fetchrow_hashref ) {
2393 push( @routinglist, $line );
2395 return ( $count, @routinglist );
2399 =head2 GetFictiveIssueNumber
2401 $issueno = GetFictiveIssueNumber($subscription, $publishedate);
2403 Get the position of the issue published at $publisheddate, considering the
2404 first issue (at firstacquidate) is at position 1, the next is at position 2, etc...
2405 This issuenumber doesn't take into account irregularities, so, for instance, if the 3rd
2406 issue is declared as 'irregular' (will be skipped at receipt), the next issue number
2407 will be 4, not 3. It's why it is called 'fictive'. It is NOT a serial seq, and is not
2408 depending on how many rows are in serial table.
2409 The issue number calculation is based on subscription frequency, first acquisition
2410 date, and $publisheddate.
2414 sub GetFictiveIssueNumber {
2415 my ($subscription, $publisheddate) = @_;
2417 my $frequency = GetSubscriptionFrequency($subscription->{'periodicity'});
2418 my $unit = $frequency->{unit} ? lc $frequency->{'unit'} : undef;
2422 my ($year, $month, $day) = split /-/, $publisheddate;
2423 my ($fa_year, $fa_month, $fa_day) = split /-/, $subscription->{'firstacquidate'};
2427 if($unit eq 'day') {
2428 $delta = Delta_Days($fa_year, $fa_month, $fa_day, $year, $month, $day);
2429 } elsif($unit eq 'week') {
2430 ($wkno, $year) = Week_of_Year($year, $month, $day);
2431 my ($fa_wkno, $fa_yr) = Week_of_Year($fa_year, $fa_month, $fa_day);
2432 $delta = ($fa_yr == $year) ? ($wkno - $fa_wkno) : ( ($year-$fa_yr-1)*52 + (52-$fa_wkno+$wkno) );
2433 } elsif($unit eq 'month') {
2434 $delta = ($fa_year == $year)
2435 ? ($month - $fa_month)
2436 : ( ($year-$fa_year-1)*12 + (12-$fa_month+$month) );
2437 } elsif($unit eq 'year') {
2438 $delta = $year - $fa_year;
2440 if($frequency->{'unitsperissue'} == 1) {
2441 $issueno = $delta * $frequency->{'issuesperunit'} + $subscription->{'countissuesperunit'};
2443 # Assuming issuesperunit == 1
2444 $issueno = int( ($delta + $frequency->{'unitsperissue'}) / $frequency->{'unitsperissue'} );
2452 $resultdate = GetNextDate($publisheddate,$subscription)
2454 this function it takes the publisheddate and will return the next issue's date
2455 and will skip dates if there exists an irregularity.
2456 $publisheddate has to be an ISO date
2457 $subscription is a hashref containing at least 'periodicity', 'firstacquidate', 'irregularity', and 'countissuesperunit'
2458 $updatecount is a boolean value which, when set to true, update the 'countissuesperunit' in database
2459 - eg if periodicity is monthly and $publisheddate is 2007-02-10 but if March and April is to be
2460 skipped then the returned date will be 2007-05-10
2463 $resultdate - then next date in the sequence (ISO date)
2465 Return $publisheddate if subscription is irregular
2470 my ( $subscription, $publisheddate, $updatecount ) = @_;
2472 my $freqdata = GetSubscriptionFrequency($subscription->{'periodicity'});
2474 if ($freqdata->{'unit'}) {
2475 my ( $year, $month, $day ) = split /-/, $publisheddate;
2477 # Process an irregularity Hash
2478 # Suppose that irregularities are stored in a string with this structure
2479 # irreg1;irreg2;irreg3
2480 # where irregX is the number of issue which will not be received
2481 # (the first issue takes the number 1, the 2nd the number 2 and so on)
2482 my @irreg = split /;/, $subscription->{'irregularity'} ;
2484 foreach my $irregularity (@irreg) {
2485 $irregularities{$irregularity} = 1;
2488 # Get the 'fictive' next issue number
2489 # It is used to check if next issue is an irregular issue.
2490 my $issueno = GetFictiveIssueNumber($subscription, $publisheddate) + 1;
2492 # Then get the next date
2493 my $unit = lc $freqdata->{'unit'};
2494 if ($unit eq 'day') {
2495 while ($irregularities{$issueno}) {
2496 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2497 ($year,$month,$day) = Add_Delta_Days($year,$month, $day , $freqdata->{'unitsperissue'} );
2498 $subscription->{'countissuesperunit'} = 1;
2500 $subscription->{'countissuesperunit'}++;
2504 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2505 ($year,$month,$day) = Add_Delta_Days($year,$month, $day , $freqdata->{"unitsperissue"} );
2506 $subscription->{'countissuesperunit'} = 1;
2508 $subscription->{'countissuesperunit'}++;
2511 elsif ($unit eq 'week') {
2512 my ($wkno, $yr) = Week_of_Year($year, $month, $day);
2513 while ($irregularities{$issueno}) {
2514 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2515 $subscription->{'countissuesperunit'} = 1;
2516 $wkno += $freqdata->{"unitsperissue"};
2521 my $dow = Day_of_Week($year, $month, $day);
2522 ($year,$month,$day) = Monday_of_Week($wkno, $yr);
2523 if($freqdata->{'issuesperunit'} == 1) {
2524 ($year, $month, $day) = Add_Delta_Days($year, $month, $day, $dow - 1);
2527 $subscription->{'countissuesperunit'}++;
2531 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2532 $subscription->{'countissuesperunit'} = 1;
2533 $wkno += $freqdata->{"unitsperissue"};
2535 $wkno = $wkno % 52 ;
2538 my $dow = Day_of_Week($year, $month, $day);
2539 ($year,$month,$day) = Monday_of_Week($wkno, $yr);
2540 if($freqdata->{'issuesperunit'} == 1) {
2541 ($year, $month, $day) = Add_Delta_Days($year, $month, $day, $dow - 1);
2544 $subscription->{'countissuesperunit'}++;
2547 elsif ($unit eq 'month') {
2548 while ($irregularities{$issueno}) {
2549 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2550 $subscription->{'countissuesperunit'} = 1;
2551 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, 0,$freqdata->{"unitsperissue"});
2552 unless($freqdata->{'issuesperunit'} == 1) {
2553 $day = 1; # Jumping to the first day of month, because we don't know what day is expected
2556 $subscription->{'countissuesperunit'}++;
2560 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2561 $subscription->{'countissuesperunit'} = 1;
2562 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, 0,$freqdata->{"unitsperissue"});
2563 unless($freqdata->{'issuesperunit'} == 1) {
2564 $day = 1; # Jumping to the first day of month, because we don't know what day is expected
2567 $subscription->{'countissuesperunit'}++;
2570 elsif ($unit eq 'year') {
2571 while ($irregularities{$issueno}) {
2572 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2573 $subscription->{'countissuesperunit'} = 1;
2574 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, $freqdata->{"unitsperissue"},0);
2575 unless($freqdata->{'issuesperunit'} == 1) {
2576 # Jumping to the first day of year, because we don't know what day is expected
2581 $subscription->{'countissuesperunit'}++;
2585 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2586 $subscription->{'countissuesperunit'} = 1;
2587 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, $freqdata->{"unitsperissue"},0);
2588 unless($freqdata->{'issuesperunit'} == 1) {
2589 # Jumping to the first day of year, because we don't know what day is expected
2594 $subscription->{'countissuesperunit'}++;
2598 my $dbh = C4::Context->dbh;
2601 SET countissuesperunit = ?
2602 WHERE subscriptionid = ?
2604 my $sth = $dbh->prepare($query);
2605 $sth->execute($subscription->{'countissuesperunit'}, $subscription->{'subscriptionid'});
2607 return sprintf("%04d-%02d-%02d", $year, $month, $day);
2610 return $publisheddate;
2616 $string = &_numeration($value,$num_type,$locale);
2618 _numeration returns the string corresponding to $value in the num_type
2628 my ($value, $num_type, $locale) = @_;
2630 my $initlocale = setlocale(LC_TIME);
2631 if($locale and $locale ne $initlocale) {
2632 $locale = setlocale(LC_TIME, $locale);
2634 $locale ||= $initlocale;
2638 when (/^dayname$/) {
2639 $value = $value % 7;
2640 $string = POSIX::strftime("%A",0,0,0,0,0,0,$value);
2642 when (/^monthname$/) {
2643 $value = $value % 12;
2644 $string = POSIX::strftime("%B",0,0,0,1,$value,0,0,0,0);
2647 my $seasonlocale = ($locale)
2648 ? (substr $locale,0,2)
2652 [qw(Spring Summer Fall Winter)],
2654 [qw(Printemps Été Automne Hiver)],
2656 $value = $value % 4;
2657 $string = ($seasons{$seasonlocale})
2658 ? $seasons{$seasonlocale}->[$value]
2659 : $seasons{'en'}->[$value];
2665 if($locale ne $initlocale) {
2666 setlocale(LC_TIME, $initlocale);
2671 =head2 is_barcode_in_use
2673 Returns number of occurence of the barcode in the items table
2674 Can be used as a boolean test of whether the barcode has
2675 been deployed as yet
2679 sub is_barcode_in_use {
2680 my $barcode = shift;
2681 my $dbh = C4::Context->dbh;
2682 my $occurences = $dbh->selectall_arrayref(
2683 'SELECT itemnumber from items where barcode = ?',
2688 return @{$occurences};
2691 =head2 CloseSubscription
2692 Close a subscription given a subscriptionid
2694 sub CloseSubscription {
2695 my ( $subscriptionid ) = @_;
2696 return unless $subscriptionid;
2697 my $dbh = C4::Context->dbh;
2698 my $sth = $dbh->prepare( qq{
2701 WHERE subscriptionid = ?
2703 $sth->execute( $subscriptionid );
2705 # Set status = missing when status = stopped
2706 $sth = $dbh->prepare( qq{
2709 WHERE subscriptionid = ?
2712 $sth->execute( $subscriptionid );
2715 =head2 ReopenSubscription
2716 Reopen a subscription given a subscriptionid
2718 sub ReopenSubscription {
2719 my ( $subscriptionid ) = @_;
2720 return unless $subscriptionid;
2721 my $dbh = C4::Context->dbh;
2722 my $sth = $dbh->prepare( qq{
2725 WHERE subscriptionid = ?
2727 $sth->execute( $subscriptionid );
2729 # Set status = expected when status = stopped
2730 $sth = $dbh->prepare( qq{
2733 WHERE subscriptionid = ?
2736 $sth->execute( $subscriptionid );
2744 Koha Development Team <http://koha-community.org/>