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
61 &subscriptionCurrentlyOnOrder
68 C4::Serials - Serials Module Functions
76 Functions for handling subscriptions, claims routing etc.
81 =head2 GetSuppliersWithLateIssues
83 $supplierlist = GetSuppliersWithLateIssues()
85 this function get all suppliers with late issues.
88 an array_ref of suppliers each entry is a hash_ref containing id and name
89 the array is in name order
93 sub GetSuppliersWithLateIssues {
94 my $dbh = C4::Context->dbh;
96 SELECT DISTINCT id, name
98 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
99 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
102 (planneddate < now() AND serial.status=1)
103 OR serial.STATUS = 3 OR serial.STATUS = 4
105 AND subscription.closed = 0
107 return $dbh->selectall_arrayref($query, { Slice => {} });
112 @issuelist = GetLateIssues($supplierid)
114 this function selects late issues from the database
117 the issuelist as an array. Each element of this array contains a hashi_ref containing
118 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
123 my ($supplierid) = @_;
124 my $dbh = C4::Context->dbh;
128 SELECT name,title,planneddate,serialseq,serial.subscriptionid
130 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
131 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
132 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
133 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
134 AND subscription.aqbooksellerid=?
135 AND subscription.closed = 0
138 $sth = $dbh->prepare($query);
139 $sth->execute($supplierid);
142 SELECT name,title,planneddate,serialseq,serial.subscriptionid
144 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
145 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
146 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
147 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
148 AND subscription.closed = 0
151 $sth = $dbh->prepare($query);
157 while ( my $line = $sth->fetchrow_hashref ) {
158 $odd++ unless $line->{title} eq $last_title;
159 $line->{title} = "" if $line->{title} eq $last_title;
160 $last_title = $line->{title} if ( $line->{title} );
161 $line->{planneddate} = format_date( $line->{planneddate} );
162 push @issuelist, $line;
167 =head2 GetSubscriptionHistoryFromSubscriptionId
169 $history = GetSubscriptionHistoryFromSubscriptionId($subscriptionid);
171 This function returns the subscription history as a hashref
175 sub GetSubscriptionHistoryFromSubscriptionId {
176 my ($subscriptionid) = @_;
178 return unless $subscriptionid;
180 my $dbh = C4::Context->dbh;
183 FROM subscriptionhistory
184 WHERE subscriptionid = ?
186 my $sth = $dbh->prepare($query);
187 $sth->execute($subscriptionid);
188 my $results = $sth->fetchrow_hashref;
194 =head2 GetSerialStatusFromSerialId
196 $sth = GetSerialStatusFromSerialId();
197 this function returns a statement handle
198 After this function, don't forget to execute it by using $sth->execute($serialid)
200 $sth = $dbh->prepare($query).
204 sub GetSerialStatusFromSerialId {
205 my $dbh = C4::Context->dbh;
211 return $dbh->prepare($query);
214 =head2 GetSerialInformation
217 $data = GetSerialInformation($serialid);
218 returns a hash_ref containing :
219 items : items marcrecord (can be an array)
221 subscription table field
222 + information about subscription expiration
226 sub GetSerialInformation {
228 my $dbh = C4::Context->dbh;
230 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
231 if ( C4::Context->preference('IndependentBranches')
232 && C4::Context->userenv
233 && C4::Context->userenv->{'flags'} != 1
234 && C4::Context->userenv->{'branch'} ) {
236 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
239 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
242 my $rq = $dbh->prepare($query);
243 $rq->execute($serialid);
244 my $data = $rq->fetchrow_hashref;
246 # create item information if we have serialsadditems for this subscription
247 if ( $data->{'serialsadditems'} ) {
248 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
249 $queryitem->execute($serialid);
250 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
252 if ( scalar(@$itemnumbers) > 0 ) {
253 foreach my $itemnum (@$itemnumbers) {
255 #It is ASSUMED that GetMarcItem ALWAYS WORK...
256 #Maybe GetMarcItem should return values on failure
257 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
258 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
259 $itemprocessed->{'itemnumber'} = $itemnum->[0];
260 $itemprocessed->{'itemid'} = $itemnum->[0];
261 $itemprocessed->{'serialid'} = $serialid;
262 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
263 push @{ $data->{'items'} }, $itemprocessed;
266 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
267 $itemprocessed->{'itemid'} = "N$serialid";
268 $itemprocessed->{'serialid'} = $serialid;
269 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
270 $itemprocessed->{'countitems'} = 0;
271 push @{ $data->{'items'} }, $itemprocessed;
274 $data->{ "status" . $data->{'serstatus'} } = 1;
275 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
276 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
280 =head2 AddItem2Serial
282 $rows = AddItem2Serial($serialid,$itemnumber);
283 Adds an itemnumber to Serial record
284 returns the number of rows affected
289 my ( $serialid, $itemnumber ) = @_;
290 my $dbh = C4::Context->dbh;
291 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
292 $rq->execute( $serialid, $itemnumber );
296 =head2 UpdateClaimdateIssues
298 UpdateClaimdateIssues($serialids,[$date]);
300 Update Claimdate for issues in @$serialids list with date $date
305 sub UpdateClaimdateIssues {
306 my ( $serialids, $date ) = @_;
307 my $dbh = C4::Context->dbh;
308 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
310 UPDATE serial SET claimdate = ?, status = 7
311 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
312 my $rq = $dbh->prepare($query);
313 $rq->execute($date, @$serialids);
317 =head2 GetSubscription
319 $subs = GetSubscription($subscriptionid)
320 this function returns the subscription which has $subscriptionid as id.
322 a hashref. This hash containts
323 subscription, subscriptionhistory, aqbooksellers.name, biblio.title
327 sub GetSubscription {
328 my ($subscriptionid) = @_;
329 my $dbh = C4::Context->dbh;
331 SELECT subscription.*,
332 subscriptionhistory.*,
333 aqbooksellers.name AS aqbooksellername,
334 biblio.title AS bibliotitle,
335 subscription.biblionumber as bibnum);
336 if ( C4::Context->preference('IndependentBranches')
337 && C4::Context->userenv
338 && C4::Context->userenv->{'flags'} != 1
339 && C4::Context->userenv->{'branch'} ) {
341 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
345 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
346 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
347 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
348 WHERE subscription.subscriptionid = ?
351 # if (C4::Context->preference('IndependentBranches') &&
352 # C4::Context->userenv &&
353 # C4::Context->userenv->{'flags'} != 1){
354 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
355 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
357 $debug and warn "query : $query\nsubsid :$subscriptionid";
358 my $sth = $dbh->prepare($query);
359 $sth->execute($subscriptionid);
360 return $sth->fetchrow_hashref;
363 =head2 GetFullSubscription
365 $array_ref = GetFullSubscription($subscriptionid)
366 this function reads the serial table.
370 sub GetFullSubscription {
371 my ($subscriptionid) = @_;
372 my $dbh = C4::Context->dbh;
374 SELECT serial.serialid,
377 serial.publisheddate,
379 serial.notes as notes,
380 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
381 aqbooksellers.name as aqbooksellername,
382 biblio.title as bibliotitle,
383 subscription.branchcode AS branchcode,
384 subscription.subscriptionid AS subscriptionid |;
385 if ( C4::Context->preference('IndependentBranches')
386 && C4::Context->userenv
387 && C4::Context->userenv->{'flags'} != 1
388 && C4::Context->userenv->{'branch'} ) {
390 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
394 LEFT JOIN subscription ON
395 (serial.subscriptionid=subscription.subscriptionid )
396 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
397 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
398 WHERE serial.subscriptionid = ?
400 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
401 serial.subscriptionid
403 $debug and warn "GetFullSubscription query: $query";
404 my $sth = $dbh->prepare($query);
405 $sth->execute($subscriptionid);
406 return $sth->fetchall_arrayref( {} );
409 =head2 PrepareSerialsData
411 $array_ref = PrepareSerialsData($serialinfomation)
412 where serialinformation is a hashref array
416 sub PrepareSerialsData {
422 my $aqbooksellername;
426 my $previousnote = "";
428 foreach my $subs (@{$lines}) {
429 for my $datefield ( qw(publisheddate planneddate) ) {
430 # handle both undef and undef returned as 0000-00-00
431 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
432 $subs->{$datefield} = 'XXX';
435 $subs->{ "status" . $subs->{'status'} } = 1;
436 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
438 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
439 $year = $subs->{'year'};
443 if ( $tmpresults{$year} ) {
444 push @{ $tmpresults{$year}->{'serials'} }, $subs;
446 $tmpresults{$year} = {
448 'aqbooksellername' => $subs->{'aqbooksellername'},
449 'bibliotitle' => $subs->{'bibliotitle'},
450 'serials' => [$subs],
455 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
456 push @res, $tmpresults{$key};
461 =head2 GetSubscriptionsFromBiblionumber
463 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
464 this function get the subscription list. it reads the subscription table.
466 reference to an array of subscriptions which have the biblionumber given on input arg.
467 each element of this array is a hashref containing
468 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
472 sub GetSubscriptionsFromBiblionumber {
473 my ($biblionumber) = @_;
474 my $dbh = C4::Context->dbh;
476 SELECT subscription.*,
478 subscriptionhistory.*,
479 aqbooksellers.name AS aqbooksellername,
480 biblio.title AS bibliotitle
482 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
483 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
484 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
485 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
486 WHERE subscription.biblionumber = ?
488 my $sth = $dbh->prepare($query);
489 $sth->execute($biblionumber);
491 while ( my $subs = $sth->fetchrow_hashref ) {
492 $subs->{startdate} = format_date( $subs->{startdate} );
493 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
494 $subs->{histenddate} = format_date( $subs->{histenddate} );
495 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
496 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
497 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
498 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
499 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
500 $subs->{ "status" . $subs->{'status'} } = 1;
501 $subs->{'cannotedit'} =
502 ( C4::Context->preference('IndependentBranches')
503 && C4::Context->userenv
504 && C4::Context->userenv->{flags} % 2 != 1
505 && C4::Context->userenv->{branch}
506 && $subs->{branchcode}
507 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
509 if ( $subs->{enddate} eq '0000-00-00' ) {
510 $subs->{enddate} = '';
512 $subs->{enddate} = format_date( $subs->{enddate} );
514 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
515 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
521 =head2 GetFullSubscriptionsFromBiblionumber
523 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
524 this function reads the serial table.
528 sub GetFullSubscriptionsFromBiblionumber {
529 my ($biblionumber) = @_;
530 my $dbh = C4::Context->dbh;
532 SELECT serial.serialid,
535 serial.publisheddate,
537 serial.notes as notes,
538 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
539 biblio.title as bibliotitle,
540 subscription.branchcode AS branchcode,
541 subscription.subscriptionid AS subscriptionid|;
542 if ( C4::Context->preference('IndependentBranches')
543 && C4::Context->userenv
544 && C4::Context->userenv->{'flags'} != 1
545 && C4::Context->userenv->{'branch'} ) {
547 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
552 LEFT JOIN subscription ON
553 (serial.subscriptionid=subscription.subscriptionid)
554 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
555 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
556 WHERE subscription.biblionumber = ?
558 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
559 serial.subscriptionid
561 my $sth = $dbh->prepare($query);
562 $sth->execute($biblionumber);
563 return $sth->fetchall_arrayref( {} );
566 =head2 GetSubscriptions
568 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
569 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
571 a table of hashref. Each hash containt the subscription.
575 sub GetSubscriptions {
576 my ( $string, $issn, $ean, $biblionumber ) = @_;
578 #return unless $title or $ISSN or $biblionumber;
579 my $dbh = C4::Context->dbh;
582 SELECT subscriptionhistory.*, subscription.*, biblio.title,biblioitems.issn,biblio.biblionumber
584 LEFT JOIN subscriptionhistory USING(subscriptionid)
585 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
586 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
591 $sqlwhere = " WHERE biblio.biblionumber=?";
592 push @bind_params, $biblionumber;
596 my @strings_to_search;
597 @strings_to_search = map { "%$_%" } split( / /, $string );
598 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
599 push @bind_params, @strings_to_search;
600 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
601 $debug && warn "$tmpstring";
602 $tmpstring =~ s/^AND //;
603 push @sqlstrings, $tmpstring;
605 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
609 my @strings_to_search;
610 @strings_to_search = map { "%$_%" } split( / /, $issn );
611 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
612 push @bind_params, @strings_to_search;
613 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
614 $debug && warn "$tmpstring";
615 $tmpstring =~ s/^OR //;
616 push @sqlstrings, $tmpstring;
618 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
622 my @strings_to_search;
623 @strings_to_search = map { "$_" } split( / /, $ean );
624 foreach my $index ( qw(biblioitems.ean) ) {
625 push @bind_params, @strings_to_search;
626 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
627 $debug && warn "$tmpstring";
628 $tmpstring =~ s/^OR //;
629 push @sqlstrings, $tmpstring;
631 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
634 $sql .= "$sqlwhere ORDER BY title";
635 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
636 $sth = $dbh->prepare($sql);
637 $sth->execute(@bind_params);
640 while ( my $line = $sth->fetchrow_hashref ) {
641 $line->{'cannotedit'} =
642 ( C4::Context->preference('IndependentBranches')
643 && C4::Context->userenv
644 && C4::Context->userenv->{flags} % 2 != 1
645 && C4::Context->userenv->{branch}
646 && $line->{branchcode}
647 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
648 push @results, $line;
653 =head2 SearchSubscriptions
655 @results = SearchSubscriptions($args);
656 $args is a hashref. Its keys can be contained: title, issn, ean, publisher, bookseller and branchcode
658 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.
661 a table of hashref. Each hash containt the subscription.
665 sub SearchSubscriptions {
670 subscription.notes AS publicnotes,
672 subscriptionhistory.*,
673 biblio.notes AS biblionotes,
678 LEFT JOIN subscriptionhistory USING(subscriptionid)
679 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
680 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
681 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
685 if( $args->{biblionumber} ) {
686 push @where_strs, "biblio.biblionumber = ?";
687 push @where_args, $args->{biblionumber};
689 if( $args->{title} ){
690 my @words = split / /, $args->{title};
692 foreach my $word (@words) {
693 push @strs, "biblio.title LIKE ?";
694 push @args, "%$word%";
697 push @where_strs, '(' . join (' AND ', @strs) . ')';
698 push @where_args, @args;
702 push @where_strs, "biblioitems.issn LIKE ?";
703 push @where_args, "%$args->{issn}%";
706 push @where_strs, "biblioitems.ean LIKE ?";
707 push @where_args, "%$args->{ean}%";
709 if( $args->{publisher} ){
710 push @where_strs, "biblioitems.publishercode LIKE ?";
711 push @where_args, "%$args->{publisher}%";
713 if( $args->{bookseller} ){
714 push @where_strs, "aqbooksellers.name LIKE ?";
715 push @where_args, "%$args->{bookseller}%";
717 if( $args->{branch} ){
718 push @where_strs, "subscription.branchcode = ?";
719 push @where_args, "$args->{branch}";
721 if( defined $args->{closed} ){
722 push @where_strs, "subscription.closed = ?";
723 push @where_args, "$args->{closed}";
726 $query .= " WHERE " . join(" AND ", @where_strs);
729 my $dbh = C4::Context->dbh;
730 my $sth = $dbh->prepare($query);
731 $sth->execute(@where_args);
732 my $results = $sth->fetchall_arrayref( {} );
741 ($totalissues,@serials) = GetSerials($subscriptionid);
742 this function gets every serial not arrived for a given subscription
743 as well as the number of issues registered in the database (all types)
744 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
746 FIXME: We should return \@serials.
751 my ( $subscriptionid, $count ) = @_;
752 my $dbh = C4::Context->dbh;
754 # status = 2 is "arrived"
756 $count = 5 unless ($count);
758 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
760 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
761 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
762 my $sth = $dbh->prepare($query);
763 $sth->execute($subscriptionid);
765 while ( my $line = $sth->fetchrow_hashref ) {
766 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
767 for my $datefield ( qw( planneddate publisheddate) ) {
768 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
769 $line->{$datefield} = format_date( $line->{$datefield});
771 $line->{$datefield} = q{};
774 push @serials, $line;
777 # OK, now add the last 5 issues arrives/missing
778 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
780 WHERE subscriptionid = ?
781 AND (status in (2,4,5))
782 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
784 $sth = $dbh->prepare($query);
785 $sth->execute($subscriptionid);
786 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
788 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
789 for my $datefield ( qw( planneddate publisheddate) ) {
790 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
791 $line->{$datefield} = format_date( $line->{$datefield});
793 $line->{$datefield} = q{};
797 push @serials, $line;
800 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
801 $sth = $dbh->prepare($query);
802 $sth->execute($subscriptionid);
803 my ($totalissues) = $sth->fetchrow;
804 return ( $totalissues, @serials );
809 @serials = GetSerials2($subscriptionid,$status);
810 this function returns every serial waited for a given subscription
811 as well as the number of issues registered in the database (all types)
812 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
817 my ( $subscription, $status ) = @_;
818 my $dbh = C4::Context->dbh;
820 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
822 WHERE subscriptionid=$subscription AND status IN ($status)
823 ORDER BY publisheddate,serialid DESC
825 $debug and warn "GetSerials2 query: $query";
826 my $sth = $dbh->prepare($query);
830 while ( my $line = $sth->fetchrow_hashref ) {
831 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
832 # Format dates for display
833 for my $datefield ( qw( planneddate publisheddate ) ) {
834 if ($line->{$datefield} =~m/^00/) {
835 $line->{$datefield} = q{};
838 $line->{$datefield} = format_date( $line->{$datefield} );
841 push @serials, $line;
846 =head2 GetLatestSerials
848 \@serials = GetLatestSerials($subscriptionid,$limit)
849 get the $limit's latest serials arrived or missing for a given subscription
851 a ref to an array which contains all of the latest serials stored into a hash.
855 sub GetLatestSerials {
856 my ( $subscriptionid, $limit ) = @_;
857 my $dbh = C4::Context->dbh;
859 # status = 2 is "arrived"
860 my $strsth = "SELECT serialid,serialseq, status, planneddate, publisheddate, notes
862 WHERE subscriptionid = ?
863 AND (status =2 or status=4)
864 ORDER BY publisheddate DESC LIMIT 0,$limit
866 my $sth = $dbh->prepare($strsth);
867 $sth->execute($subscriptionid);
869 while ( my $line = $sth->fetchrow_hashref ) {
870 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
871 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
872 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
873 push @serials, $line;
879 =head2 GetDistributedTo
881 $distributedto=GetDistributedTo($subscriptionid)
882 This function returns the field distributedto for the subscription matching subscriptionid
886 sub GetDistributedTo {
887 my $dbh = C4::Context->dbh;
889 my $subscriptionid = @_;
890 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
891 my $sth = $dbh->prepare($query);
892 $sth->execute($subscriptionid);
893 return ($distributedto) = $sth->fetchrow;
899 $nextseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
900 $newinnerloop1, $newinnerloop2, $newinnerloop3
901 ) = GetNextSeq( $subscription, $pattern, $planneddate );
903 $subscription is a hashref containing all the attributes of the table
905 $pattern is a hashref containing all the attributes of the table
906 'subscription_numberpatterns'.
907 $planneddate is a C4::Dates object.
908 This function get the next issue for the subscription given on input arg
913 my ($subscription, $pattern, $planneddate) = @_;
914 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3,
915 $newinnerloop1, $newinnerloop2, $newinnerloop3 );
918 if ($subscription->{'skip_serialseq'}) {
919 my @irreg = split /;/, $subscription->{'irregularity'};
921 my $irregularities = {};
922 $irregularities->{$_} = 1 foreach(@irreg);
923 my $issueno = GetFictiveIssueNumber($subscription, $planneddate) + 1;
924 while($irregularities->{$issueno}) {
931 my $numberingmethod = $pattern->{numberingmethod};
932 $calculated = $numberingmethod;
933 my $locale = $subscription->{locale};
934 $newlastvalue1 = $subscription->{lastvalue1} || 0;
935 $newlastvalue2 = $subscription->{lastvalue2} || 0;
936 $newlastvalue3 = $subscription->{lastvalue3} || 0;
937 $newinnerloop1 = $subscription->{innerloop1} || 0;
938 $newinnerloop2 = $subscription->{innerloop2} || 0;
939 $newinnerloop3 = $subscription->{innerloop3} || 0;
942 $calc{$_} = 1 if ($numberingmethod =~ /\{$_\}/);
945 for(my $i = 0; $i < $count; $i++) {
947 # check if we have to increase the new value.
949 if ($newinnerloop1 >= $pattern->{every1}) {
951 $newlastvalue1 += $pattern->{add1};
953 # reset counter if needed.
954 $newlastvalue1 = $pattern->{setto1} if ($newlastvalue1 > $pattern->{whenmorethan1});
957 # check if we have to increase the new value.
959 if ($newinnerloop2 >= $pattern->{every2}) {
961 $newlastvalue2 += $pattern->{add2};
963 # reset counter if needed.
964 $newlastvalue2 = $pattern->{setto2} if ($newlastvalue2 > $pattern->{whenmorethan2});
967 # check if we have to increase the new value.
969 if ($newinnerloop3 >= $pattern->{every3}) {
971 $newlastvalue3 += $pattern->{add3};
973 # reset counter if needed.
974 $newlastvalue3 = $pattern->{setto3} if ($newlastvalue3 > $pattern->{whenmorethan3});
978 my $newlastvalue1string = _numeration( $newlastvalue1, $pattern->{numbering1}, $locale );
979 $calculated =~ s/\{X\}/$newlastvalue1string/g;
982 my $newlastvalue2string = _numeration( $newlastvalue2, $pattern->{numbering2}, $locale );
983 $calculated =~ s/\{Y\}/$newlastvalue2string/g;
986 my $newlastvalue3string = _numeration( $newlastvalue3, $pattern->{numbering3}, $locale );
987 $calculated =~ s/\{Z\}/$newlastvalue3string/g;
991 $newlastvalue1, $newlastvalue2, $newlastvalue3,
992 $newinnerloop1, $newinnerloop2, $newinnerloop3);
997 $calculated = GetSeq($subscription, $pattern)
998 $subscription is a hashref containing all the attributes of the table 'subscription'
999 $pattern is a hashref containing all the attributes of the table 'subscription_numberpatterns'
1000 this function transforms {X},{Y},{Z} to 150,0,0 for example.
1002 the sequence in string format
1007 my ($subscription, $pattern) = @_;
1008 my $locale = $subscription->{locale};
1010 my $calculated = $pattern->{numberingmethod};
1012 my $newlastvalue1 = $subscription->{'lastvalue1'} || 0;
1013 $newlastvalue1 = _numeration($newlastvalue1, $pattern->{numbering1}, $locale) if ($pattern->{numbering1}); # reset counter if needed.
1014 $calculated =~ s/\{X\}/$newlastvalue1/g;
1016 my $newlastvalue2 = $subscription->{'lastvalue2'} || 0;
1017 $newlastvalue2 = _numeration($newlastvalue2, $pattern->{numbering2}, $locale) if ($pattern->{numbering2}); # reset counter if needed.
1018 $calculated =~ s/\{Y\}/$newlastvalue2/g;
1020 my $newlastvalue3 = $subscription->{'lastvalue3'} || 0;
1021 $newlastvalue3 = _numeration($newlastvalue3, $pattern->{numbering3}, $locale) if ($pattern->{numbering3}); # reset counter if needed.
1022 $calculated =~ s/\{Z\}/$newlastvalue3/g;
1026 =head2 GetExpirationDate
1028 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1030 this function return the next expiration date for a subscription given on input args.
1033 the enddate or undef
1037 sub GetExpirationDate {
1038 my ( $subscriptionid, $startdate ) = @_;
1039 my $dbh = C4::Context->dbh;
1040 my $subscription = GetSubscription($subscriptionid);
1043 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1044 $enddate = $startdate || $subscription->{startdate};
1045 my @date = split( /-/, $enddate );
1046 return if ( scalar(@date) != 3 || not check_date(@date) );
1047 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity});
1048 if ( $frequency and $frequency->{unit} ) {
1051 if ( my $length = $subscription->{numberlength} ) {
1053 #calculate the date of the last issue.
1054 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1055 $enddate = GetNextDate( $subscription, $enddate );
1057 } elsif ( $subscription->{monthlength} ) {
1058 if ( $$subscription{startdate} ) {
1059 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1060 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1062 } elsif ( $subscription->{weeklength} ) {
1063 if ( $$subscription{startdate} ) {
1064 my @date = split( /-/, $subscription->{startdate} );
1065 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1066 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1069 $enddate = $subscription->{enddate};
1073 return $subscription->{enddate};
1077 =head2 CountSubscriptionFromBiblionumber
1079 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1080 this returns a count of the subscriptions for a given biblionumber
1082 the number of subscriptions
1086 sub CountSubscriptionFromBiblionumber {
1087 my ($biblionumber) = @_;
1088 my $dbh = C4::Context->dbh;
1089 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1090 my $sth = $dbh->prepare($query);
1091 $sth->execute($biblionumber);
1092 my $subscriptionsnumber = $sth->fetchrow;
1093 return $subscriptionsnumber;
1096 =head2 ModSubscriptionHistory
1098 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1100 this function modifies the history of a subscription. Put your new values on input arg.
1101 returns the number of rows affected
1105 sub ModSubscriptionHistory {
1106 my ( $subscriptionid, $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote ) = @_;
1107 my $dbh = C4::Context->dbh;
1108 my $query = "UPDATE subscriptionhistory
1109 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1110 WHERE subscriptionid=?
1112 my $sth = $dbh->prepare($query);
1113 $receivedlist =~ s/^; // if $receivedlist;
1114 $missinglist =~ s/^; // if $missinglist;
1115 $opacnote =~ s/^; // if $opacnote;
1116 $sth->execute( $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1120 # Update missinglist field, used by ModSerialStatus
1121 sub _update_missinglist {
1122 my $subscriptionid = shift;
1124 my $dbh = C4::Context->dbh;
1125 my @missingserials = GetSerials2($subscriptionid, "4,5");
1127 foreach (@missingserials) {
1128 if($_->{'status'} == 4) {
1129 $missinglist .= $_->{'serialseq'} . "; ";
1130 } elsif($_->{'status'} == 5) {
1131 $missinglist .= "not issued " . $_->{'serialseq'} . "; ";
1134 $missinglist =~ s/; $//;
1136 UPDATE subscriptionhistory
1138 WHERE subscriptionid = ?
1140 my $sth = $dbh->prepare($query);
1141 $sth->execute($missinglist, $subscriptionid);
1144 # Update recievedlist field, used by ModSerialStatus
1145 sub _update_receivedlist {
1146 my $subscriptionid = shift;
1148 my $dbh = C4::Context->dbh;
1149 my @receivedserials = GetSerials2($subscriptionid, "2");
1151 foreach (@receivedserials) {
1152 $receivedlist .= $_->{'serialseq'} . "; ";
1154 $receivedlist =~ s/; $//;
1156 UPDATE subscriptionhistory
1157 SET recievedlist = ?
1158 WHERE subscriptionid = ?
1160 my $sth = $dbh->prepare($query);
1161 $sth->execute($receivedlist, $subscriptionid);
1164 =head2 ModSerialStatus
1166 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1168 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1169 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1173 sub ModSerialStatus {
1174 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1177 #It is a usual serial
1178 # 1st, get previous status :
1179 my $dbh = C4::Context->dbh;
1180 my $query = "SELECT serial.subscriptionid,serial.status,subscription.periodicity
1181 FROM serial, subscription
1182 WHERE serial.subscriptionid=subscription.subscriptionid
1184 my $sth = $dbh->prepare($query);
1185 $sth->execute($serialid);
1186 my ( $subscriptionid, $oldstatus, $periodicity ) = $sth->fetchrow;
1187 my $frequency = GetSubscriptionFrequency($periodicity);
1189 # change status & update subscriptionhistory
1191 if ( $status == 6 ) {
1192 DelIssue( { 'serialid' => $serialid, 'subscriptionid' => $subscriptionid, 'serialseq' => $serialseq } );
1195 unless ($frequency->{'unit'}) {
1196 if ( not $planneddate or $planneddate eq '0000-00-00' ) { $planneddate = C4::Dates->new()->output('iso') };
1197 if ( not $publisheddate or $publisheddate eq '0000-00-00' ) { $publisheddate = C4::Dates->new()->output('iso') };
1199 my $query = 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1200 $sth = $dbh->prepare($query);
1201 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1202 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1203 $sth = $dbh->prepare($query);
1204 $sth->execute($subscriptionid);
1205 my $val = $sth->fetchrow_hashref;
1206 unless ( $val->{manualhistory} ) {
1207 if ( $status == 2 || ($oldstatus == 2 && $status != 2) ) {
1208 _update_receivedlist($subscriptionid);
1210 if($status == 4 || $status == 5
1211 || ($oldstatus == 4 && $status != 4)
1212 || ($oldstatus == 5 && $status != 5)) {
1213 _update_missinglist($subscriptionid);
1218 # create new waited entry if needed (ie : was a "waited" and has changed)
1219 if ( $oldstatus == 1 && $status != 1 ) {
1220 my $subscription = GetSubscription($subscriptionid);
1221 my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern});
1225 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1226 $newinnerloop1, $newinnerloop2, $newinnerloop3
1228 = GetNextSeq( $subscription, $pattern, $publisheddate );
1230 # next date (calculated from actual date & frequency parameters)
1231 my $nextpublisheddate = GetNextDate($subscription, $publisheddate, 1);
1232 my $nextpubdate = $nextpublisheddate;
1233 NewIssue( $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, 1, $nextpubdate, $nextpubdate );
1234 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1235 WHERE subscriptionid = ?";
1236 $sth = $dbh->prepare($query);
1237 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1239 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1240 if ( $subscription->{letter} && $status == 2 && $oldstatus != 2 ) {
1241 require C4::Letters;
1242 C4::Letters::SendAlerts( 'issue', $subscription->{subscriptionid}, $subscription->{letter} );
1249 =head2 GetNextExpected
1251 $nextexpected = GetNextExpected($subscriptionid)
1253 Get the planneddate for the current expected issue of the subscription.
1259 planneddate => ISO date
1264 sub GetNextExpected {
1265 my ($subscriptionid) = @_;
1267 my $dbh = C4::Context->dbh;
1271 WHERE subscriptionid = ?
1275 my $sth = $dbh->prepare($query);
1277 # Each subscription has only one 'expected' issue, with serial.status==1.
1278 $sth->execute( $subscriptionid, 1 );
1279 my $nextissue = $sth->fetchrow_hashref;
1280 if ( !$nextissue ) {
1284 WHERE subscriptionid = ?
1285 ORDER BY publisheddate DESC
1288 $sth = $dbh->prepare($query);
1289 $sth->execute($subscriptionid);
1290 $nextissue = $sth->fetchrow_hashref;
1292 foreach(qw/planneddate publisheddate/) {
1293 if ( !defined $nextissue->{$_} ) {
1294 # or should this default to 1st Jan ???
1295 $nextissue->{$_} = strftime( '%Y-%m-%d', localtime );
1297 $nextissue->{$_} = ($nextissue->{$_} ne '0000-00-00')
1305 =head2 ModNextExpected
1307 ModNextExpected($subscriptionid,$date)
1309 Update the planneddate for the current expected issue of the subscription.
1310 This will modify all future prediction results.
1312 C<$date> is an ISO date.
1318 sub ModNextExpected {
1319 my ( $subscriptionid, $date ) = @_;
1320 my $dbh = C4::Context->dbh;
1322 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1323 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1325 # Each subscription has only one 'expected' issue, with serial.status==1.
1326 $sth->execute( $date, $date, $subscriptionid, 1 );
1331 =head2 GetSubscriptionIrregularities
1335 =item @irreg = &GetSubscriptionIrregularities($subscriptionid);
1336 get the list of irregularities for a subscription
1342 sub GetSubscriptionIrregularities {
1343 my $subscriptionid = shift;
1345 return unless $subscriptionid;
1347 my $dbh = C4::Context->dbh;
1351 WHERE subscriptionid = ?
1353 my $sth = $dbh->prepare($query);
1354 $sth->execute($subscriptionid);
1356 my ($result) = $sth->fetchrow_array;
1357 my @irreg = split /;/, $result;
1362 =head2 ModSubscription
1364 this function modifies a subscription. Put all new values on input args.
1365 returns the number of rows affected
1369 sub ModSubscription {
1371 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
1372 $periodicity, $firstacquidate, $irregularity, $numberpattern, $locale,
1373 $numberlength, $weeklength, $monthlength, $lastvalue1, $innerloop1,
1374 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, $status,
1375 $biblionumber, $callnumber, $notes, $letter, $manualhistory,
1376 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1377 $graceperiod, $location, $enddate, $subscriptionid, $skip_serialseq
1380 my $dbh = C4::Context->dbh;
1381 my $query = "UPDATE subscription
1382 SET librarian=?, branchcode=?, aqbooksellerid=?, cost=?, aqbudgetid=?,
1383 startdate=?, periodicity=?, firstacquidate=?, irregularity=?,
1384 numberpattern=?, locale=?, numberlength=?, weeklength=?, monthlength=?,
1385 lastvalue1=?, innerloop1=?, lastvalue2=?, innerloop2=?,
1386 lastvalue3=?, innerloop3=?, status=?, biblionumber=?,
1387 callnumber=?, notes=?, letter=?, manualhistory=?,
1388 internalnotes=?, serialsadditems=?, staffdisplaycount=?,
1389 opacdisplaycount=?, graceperiod=?, location = ?, enddate=?,
1391 WHERE subscriptionid = ?";
1393 my $sth = $dbh->prepare($query);
1395 $auser, $branchcode, $aqbooksellerid, $cost,
1396 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1397 $irregularity, $numberpattern, $locale, $numberlength,
1398 $weeklength, $monthlength, $lastvalue1, $innerloop1,
1399 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
1400 $status, $biblionumber, $callnumber, $notes,
1401 $letter, ($manualhistory ? $manualhistory : 0),
1402 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1403 $graceperiod, $location, $enddate, $skip_serialseq,
1406 my $rows = $sth->rows;
1408 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1412 =head2 NewSubscription
1414 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1415 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1416 $lastvalue1,$innerloop1,$lastvalue2,$innerloop2,$lastvalue3,$innerloop3,
1417 $status, $notes, $letter, $firstacquidate, $irregularity, $numberpattern,
1418 $callnumber, $hemisphere, $manualhistory, $internalnotes, $serialsadditems,
1419 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq);
1421 Create a new subscription with value given on input args.
1424 the id of this new subscription
1428 sub NewSubscription {
1430 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1431 $startdate, $periodicity, $numberlength, $weeklength, $monthlength,
1432 $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, $lastvalue3,
1433 $innerloop3, $status, $notes, $letter, $firstacquidate, $irregularity,
1434 $numberpattern, $locale, $callnumber, $manualhistory, $internalnotes,
1435 $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,
1436 $location, $enddate, $skip_serialseq
1438 my $dbh = C4::Context->dbh;
1440 #save subscription (insert into database)
1442 INSERT INTO subscription
1443 (librarian, branchcode, aqbooksellerid, cost, aqbudgetid,
1444 biblionumber, startdate, periodicity, numberlength, weeklength,
1445 monthlength, lastvalue1, innerloop1, lastvalue2, innerloop2,
1446 lastvalue3, innerloop3, status, notes, letter, firstacquidate,
1447 irregularity, numberpattern, locale, callnumber,
1448 manualhistory, internalnotes, serialsadditems, staffdisplaycount,
1449 opacdisplaycount, graceperiod, location, enddate, skip_serialseq)
1450 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1452 my $sth = $dbh->prepare($query);
1454 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1455 $startdate, $periodicity, $numberlength, $weeklength,
1456 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
1457 $lastvalue3, $innerloop3, $status, $notes, $letter,
1458 $firstacquidate, $irregularity, $numberpattern, $locale, $callnumber,
1459 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
1460 $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq
1463 my $subscriptionid = $dbh->{'mysql_insertid'};
1465 $enddate = GetExpirationDate( $subscriptionid, $startdate );
1469 WHERE subscriptionid=?
1471 $sth = $dbh->prepare($query);
1472 $sth->execute( $enddate, $subscriptionid );
1475 # then create the 1st expected number
1477 INSERT INTO subscriptionhistory
1478 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1481 $sth = $dbh->prepare($query);
1482 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1484 # reread subscription to get a hash (for calculation of the 1st issue number)
1485 my $subscription = GetSubscription($subscriptionid);
1486 my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern});
1488 # calculate issue number
1489 my $serialseq = GetSeq($subscription, $pattern);
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=?,reneweddate=NOW()
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 );
2739 =head2 subscriptionCurrentlyOnOrder
2741 $bool = subscriptionCurrentlyOnOrder( $subscriptionid );
2743 Return 1 if subscription is currently on order else 0.
2747 sub subscriptionCurrentlyOnOrder {
2748 my ( $subscriptionid ) = @_;
2749 my $dbh = C4::Context->dbh;
2751 SELECT COUNT(*) FROM aqorders
2752 WHERE subscriptionid = ?
2753 AND datereceived IS NULL
2754 AND datecancellationprinted IS NULL
2756 my $sth = $dbh->prepare( $query );
2757 $sth->execute($subscriptionid);
2758 return $sth->fetchrow_array;
2766 Koha Development Team <http://koha-community.org/>