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);
27 use C4::Log; # logaction
30 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33 $VERSION = 3.07.00.049; # set version for version checking
37 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
38 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
40 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
41 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
43 &GetNextSeq &NewIssue &ItemizeSerials &GetSerials
44 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
45 &ReNewSubscription &GetLateIssues &GetLateOrMissingIssues
46 &GetSerialInformation &AddItem2Serial
47 &PrepareSerialsData &GetNextExpected &ModNextExpected
49 &UpdateClaimdateIssues
50 &GetSuppliersWithLateIssues &getsupplierbyserialid
51 &GetDistributedTo &SetDistributedTo
52 &getroutinglist &delroutingmember &addroutingmember
54 &check_routing &updateClaim &removeMissingIssue
57 &GetSubscriptionsFromBorrower
58 &subscriptionCurrentlyOnOrder
65 C4::Serials - Serials Module Functions
73 Functions for handling subscriptions, claims routing etc.
78 =head2 GetSuppliersWithLateIssues
80 $supplierlist = GetSuppliersWithLateIssues()
82 this function get all suppliers with late issues.
85 an array_ref of suppliers each entry is a hash_ref containing id and name
86 the array is in name order
90 sub GetSuppliersWithLateIssues {
91 my $dbh = C4::Context->dbh;
93 SELECT DISTINCT id, name
95 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
96 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
99 (planneddate < now() AND serial.status=1)
100 OR serial.STATUS = 3 OR serial.STATUS = 4
102 AND subscription.closed = 0
104 return $dbh->selectall_arrayref($query, { Slice => {} });
109 @issuelist = GetLateIssues($supplierid)
111 this function selects late issues from the database
114 the issuelist as an array. Each element of this array contains a hashi_ref containing
115 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
120 my ($supplierid) = @_;
121 my $dbh = C4::Context->dbh;
125 SELECT name,title,planneddate,serialseq,serial.subscriptionid
127 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
128 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
129 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
130 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
131 AND subscription.aqbooksellerid=?
132 AND subscription.closed = 0
135 $sth = $dbh->prepare($query);
136 $sth->execute($supplierid);
139 SELECT name,title,planneddate,serialseq,serial.subscriptionid
141 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
142 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
143 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
144 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
145 AND subscription.closed = 0
148 $sth = $dbh->prepare($query);
154 while ( my $line = $sth->fetchrow_hashref ) {
155 $odd++ unless $line->{title} eq $last_title;
156 $line->{title} = "" if $line->{title} eq $last_title;
157 $last_title = $line->{title} if ( $line->{title} );
158 $line->{planneddate} = format_date( $line->{planneddate} );
159 push @issuelist, $line;
164 =head2 GetSubscriptionHistoryFromSubscriptionId
166 $sth = GetSubscriptionHistoryFromSubscriptionId()
167 this function prepares the SQL request and returns the statement handle
168 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
172 sub GetSubscriptionHistoryFromSubscriptionId {
173 my $dbh = C4::Context->dbh;
176 FROM subscriptionhistory
177 WHERE subscriptionid = ?
179 return $dbh->prepare($query);
182 =head2 GetSerialStatusFromSerialId
184 $sth = GetSerialStatusFromSerialId();
185 this function returns a statement handle
186 After this function, don't forget to execute it by using $sth->execute($serialid)
188 $sth = $dbh->prepare($query).
192 sub GetSerialStatusFromSerialId {
193 my $dbh = C4::Context->dbh;
199 return $dbh->prepare($query);
202 =head2 GetSerialInformation
205 $data = GetSerialInformation($serialid);
206 returns a hash_ref containing :
207 items : items marcrecord (can be an array)
209 subscription table field
210 + information about subscription expiration
214 sub GetSerialInformation {
216 my $dbh = C4::Context->dbh;
218 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
219 if ( C4::Context->preference('IndependentBranches')
220 && C4::Context->userenv
221 && C4::Context->userenv->{'flags'} != 1
222 && C4::Context->userenv->{'branch'} ) {
224 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
227 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
230 my $rq = $dbh->prepare($query);
231 $rq->execute($serialid);
232 my $data = $rq->fetchrow_hashref;
234 # create item information if we have serialsadditems for this subscription
235 if ( $data->{'serialsadditems'} ) {
236 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
237 $queryitem->execute($serialid);
238 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
240 if ( scalar(@$itemnumbers) > 0 ) {
241 foreach my $itemnum (@$itemnumbers) {
243 #It is ASSUMED that GetMarcItem ALWAYS WORK...
244 #Maybe GetMarcItem should return values on failure
245 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
246 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
247 $itemprocessed->{'itemnumber'} = $itemnum->[0];
248 $itemprocessed->{'itemid'} = $itemnum->[0];
249 $itemprocessed->{'serialid'} = $serialid;
250 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
251 push @{ $data->{'items'} }, $itemprocessed;
254 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
255 $itemprocessed->{'itemid'} = "N$serialid";
256 $itemprocessed->{'serialid'} = $serialid;
257 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
258 $itemprocessed->{'countitems'} = 0;
259 push @{ $data->{'items'} }, $itemprocessed;
262 $data->{ "status" . $data->{'serstatus'} } = 1;
263 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
264 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
268 =head2 AddItem2Serial
270 $rows = AddItem2Serial($serialid,$itemnumber);
271 Adds an itemnumber to Serial record
272 returns the number of rows affected
277 my ( $serialid, $itemnumber ) = @_;
278 my $dbh = C4::Context->dbh;
279 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
280 $rq->execute( $serialid, $itemnumber );
284 =head2 UpdateClaimdateIssues
286 UpdateClaimdateIssues($serialids,[$date]);
288 Update Claimdate for issues in @$serialids list with date $date
293 sub UpdateClaimdateIssues {
294 my ( $serialids, $date ) = @_;
295 my $dbh = C4::Context->dbh;
296 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
298 UPDATE serial SET claimdate = ?, status = 7
299 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
300 my $rq = $dbh->prepare($query);
301 $rq->execute($date, @$serialids);
305 =head2 GetSubscription
307 $subs = GetSubscription($subscriptionid)
308 this function returns the subscription which has $subscriptionid as id.
310 a hashref. This hash containts
311 subscription, subscriptionhistory, aqbooksellers.name, biblio.title
315 sub GetSubscription {
316 my ($subscriptionid) = @_;
317 my $dbh = C4::Context->dbh;
319 SELECT subscription.*,
320 subscriptionhistory.*,
321 aqbooksellers.name AS aqbooksellername,
322 biblio.title AS bibliotitle,
323 subscription.biblionumber as bibnum);
324 if ( C4::Context->preference('IndependentBranches')
325 && C4::Context->userenv
326 && C4::Context->userenv->{'flags'} != 1
327 && C4::Context->userenv->{'branch'} ) {
329 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
333 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
334 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
335 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
336 WHERE subscription.subscriptionid = ?
339 # if (C4::Context->preference('IndependentBranches') &&
340 # C4::Context->userenv &&
341 # C4::Context->userenv->{'flags'} != 1){
342 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
343 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
345 $debug and warn "query : $query\nsubsid :$subscriptionid";
346 my $sth = $dbh->prepare($query);
347 $sth->execute($subscriptionid);
348 return $sth->fetchrow_hashref;
351 =head2 GetFullSubscription
353 $array_ref = GetFullSubscription($subscriptionid)
354 this function reads the serial table.
358 sub GetFullSubscription {
359 my ($subscriptionid) = @_;
360 my $dbh = C4::Context->dbh;
362 SELECT serial.serialid,
365 serial.publisheddate,
367 serial.notes as notes,
368 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
369 aqbooksellers.name as aqbooksellername,
370 biblio.title as bibliotitle,
371 subscription.branchcode AS branchcode,
372 subscription.subscriptionid AS subscriptionid |;
373 if ( C4::Context->preference('IndependentBranches')
374 && C4::Context->userenv
375 && C4::Context->userenv->{'flags'} != 1
376 && C4::Context->userenv->{'branch'} ) {
378 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
382 LEFT JOIN subscription ON
383 (serial.subscriptionid=subscription.subscriptionid )
384 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
385 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
386 WHERE serial.subscriptionid = ?
388 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
389 serial.subscriptionid
391 $debug and warn "GetFullSubscription query: $query";
392 my $sth = $dbh->prepare($query);
393 $sth->execute($subscriptionid);
394 return $sth->fetchall_arrayref( {} );
397 =head2 PrepareSerialsData
399 $array_ref = PrepareSerialsData($serialinfomation)
400 where serialinformation is a hashref array
404 sub PrepareSerialsData {
410 my $aqbooksellername;
414 my $previousnote = "";
416 foreach my $subs (@{$lines}) {
417 for my $datefield ( qw(publisheddate planneddate) ) {
418 # handle both undef and undef returned as 0000-00-00
419 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
420 $subs->{$datefield} = 'XXX';
423 $subs->{ "status" . $subs->{'status'} } = 1;
424 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
426 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
427 $year = $subs->{'year'};
431 if ( $tmpresults{$year} ) {
432 push @{ $tmpresults{$year}->{'serials'} }, $subs;
434 $tmpresults{$year} = {
436 'aqbooksellername' => $subs->{'aqbooksellername'},
437 'bibliotitle' => $subs->{'bibliotitle'},
438 'serials' => [$subs],
443 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
444 push @res, $tmpresults{$key};
449 =head2 GetSubscriptionsFromBiblionumber
451 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
452 this function get the subscription list. it reads the subscription table.
454 reference to an array of subscriptions which have the biblionumber given on input arg.
455 each element of this array is a hashref containing
456 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
460 sub GetSubscriptionsFromBiblionumber {
461 my ($biblionumber) = @_;
462 my $dbh = C4::Context->dbh;
464 SELECT subscription.*,
466 subscriptionhistory.*,
467 aqbooksellers.name AS aqbooksellername,
468 biblio.title AS bibliotitle
470 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
471 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
472 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
473 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
474 WHERE subscription.biblionumber = ?
476 my $sth = $dbh->prepare($query);
477 $sth->execute($biblionumber);
479 while ( my $subs = $sth->fetchrow_hashref ) {
480 $subs->{startdate} = format_date( $subs->{startdate} );
481 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
482 $subs->{histenddate} = format_date( $subs->{histenddate} );
483 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
484 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
485 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
486 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
487 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
488 $subs->{ "status" . $subs->{'status'} } = 1;
489 $subs->{'cannotedit'} =
490 ( C4::Context->preference('IndependentBranches')
491 && C4::Context->userenv
492 && C4::Context->userenv->{flags} % 2 != 1
493 && C4::Context->userenv->{branch}
494 && $subs->{branchcode}
495 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
497 if ( $subs->{enddate} eq '0000-00-00' ) {
498 $subs->{enddate} = '';
500 $subs->{enddate} = format_date( $subs->{enddate} );
502 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
503 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
509 =head2 GetFullSubscriptionsFromBiblionumber
511 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
512 this function reads the serial table.
516 sub GetFullSubscriptionsFromBiblionumber {
517 my ($biblionumber) = @_;
518 my $dbh = C4::Context->dbh;
520 SELECT serial.serialid,
523 serial.publisheddate,
525 serial.notes as notes,
526 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
527 biblio.title as bibliotitle,
528 subscription.branchcode AS branchcode,
529 subscription.subscriptionid AS subscriptionid|;
530 if ( C4::Context->preference('IndependentBranches')
531 && C4::Context->userenv
532 && C4::Context->userenv->{'flags'} != 1
533 && C4::Context->userenv->{'branch'} ) {
535 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
540 LEFT JOIN subscription ON
541 (serial.subscriptionid=subscription.subscriptionid)
542 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
543 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
544 WHERE subscription.biblionumber = ?
546 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
547 serial.subscriptionid
549 my $sth = $dbh->prepare($query);
550 $sth->execute($biblionumber);
551 return $sth->fetchall_arrayref( {} );
554 =head2 GetSubscriptions
556 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
557 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
559 a table of hashref. Each hash containt the subscription.
563 sub GetSubscriptions {
564 my ( $string, $issn, $ean, $biblionumber ) = @_;
566 #return unless $title or $ISSN or $biblionumber;
567 my $dbh = C4::Context->dbh;
570 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
572 LEFT JOIN subscriptionhistory USING(subscriptionid)
573 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
574 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
579 $sqlwhere = " WHERE biblio.biblionumber=?";
580 push @bind_params, $biblionumber;
584 my @strings_to_search;
585 @strings_to_search = map { "%$_%" } split( / /, $string );
586 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
587 push @bind_params, @strings_to_search;
588 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
589 $debug && warn "$tmpstring";
590 $tmpstring =~ s/^AND //;
591 push @sqlstrings, $tmpstring;
593 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
597 my @strings_to_search;
598 @strings_to_search = map { "%$_%" } split( / /, $issn );
599 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
600 push @bind_params, @strings_to_search;
601 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
602 $debug && warn "$tmpstring";
603 $tmpstring =~ s/^OR //;
604 push @sqlstrings, $tmpstring;
606 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
610 my @strings_to_search;
611 @strings_to_search = map { "$_" } split( / /, $ean );
612 foreach my $index ( qw(biblioitems.ean) ) {
613 push @bind_params, @strings_to_search;
614 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
615 $debug && warn "$tmpstring";
616 $tmpstring =~ s/^OR //;
617 push @sqlstrings, $tmpstring;
619 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
622 $sql .= "$sqlwhere ORDER BY title";
623 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
624 $sth = $dbh->prepare($sql);
625 $sth->execute(@bind_params);
628 while ( my $line = $sth->fetchrow_hashref ) {
629 $line->{'cannotedit'} =
630 ( C4::Context->preference('IndependentBranches')
631 && C4::Context->userenv
632 && C4::Context->userenv->{flags} % 2 != 1
633 && C4::Context->userenv->{branch}
634 && $line->{branchcode}
635 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
636 push @results, $line;
641 =head2 SearchSubscriptions
643 @results = SearchSubscriptions($args);
644 $args is a hashref. Its keys can be contained: title, issn, ean, publisher, bookseller and branchcode
646 this function gets all subscriptions which have title like $title, ISSN like $issn, EAN like $ean, publisher like $publisher, bookseller like $bookseller AND branchcode eq $branch.
649 a table of hashref. Each hash containt the subscription.
653 sub SearchSubscriptions {
658 subscription.notes AS publicnotes,
660 subscriptionhistory.*,
661 biblio.notes AS biblionotes,
666 LEFT JOIN subscriptionhistory USING(subscriptionid)
667 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
668 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
669 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
673 if( $args->{biblionumber} ) {
674 push @where_strs, "biblio.biblionumber = ?";
675 push @where_args, $args->{biblionumber};
677 if( $args->{title} ){
678 my @words = split / /, $args->{title};
680 foreach my $word (@words) {
681 push @strs, "biblio.title LIKE ?";
682 push @args, "%$word%";
685 push @where_strs, '(' . join (' AND ', @strs) . ')';
686 push @where_args, @args;
690 push @where_strs, "biblioitems.issn LIKE ?";
691 push @where_args, "%$args->{issn}%";
694 push @where_strs, "biblioitems.ean LIKE ?";
695 push @where_args, "%$args->{ean}%";
697 if( $args->{publisher} ){
698 push @where_strs, "biblioitems.publishercode LIKE ?";
699 push @where_args, "%$args->{publisher}%";
701 if( $args->{bookseller} ){
702 push @where_strs, "aqbooksellers.name LIKE ?";
703 push @where_args, "%$args->{bookseller}%";
705 if( $args->{branch} ){
706 push @where_strs, "subscription.branchcode = ?";
707 push @where_args, "$args->{branch}";
709 if( defined $args->{closed} ){
710 push @where_strs, "subscription.closed = ?";
711 push @where_args, "$args->{closed}";
714 $query .= " WHERE " . join(" AND ", @where_strs);
717 my $dbh = C4::Context->dbh;
718 my $sth = $dbh->prepare($query);
719 $sth->execute(@where_args);
720 my $results = $sth->fetchall_arrayref( {} );
729 ($totalissues,@serials) = GetSerials($subscriptionid);
730 this function gets every serial not arrived for a given subscription
731 as well as the number of issues registered in the database (all types)
732 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
734 FIXME: We should return \@serials.
739 my ( $subscriptionid, $count ) = @_;
740 my $dbh = C4::Context->dbh;
742 # status = 2 is "arrived"
744 $count = 5 unless ($count);
746 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
748 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
749 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
750 my $sth = $dbh->prepare($query);
751 $sth->execute($subscriptionid);
753 while ( my $line = $sth->fetchrow_hashref ) {
754 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
755 for my $datefield ( qw( planneddate publisheddate) ) {
756 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
757 $line->{$datefield} = format_date( $line->{$datefield});
759 $line->{$datefield} = q{};
762 push @serials, $line;
765 # OK, now add the last 5 issues arrives/missing
766 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
768 WHERE subscriptionid = ?
769 AND (status in (2,4,5))
770 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
772 $sth = $dbh->prepare($query);
773 $sth->execute($subscriptionid);
774 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
776 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
777 for my $datefield ( qw( planneddate publisheddate) ) {
778 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
779 $line->{$datefield} = format_date( $line->{$datefield});
781 $line->{$datefield} = q{};
785 push @serials, $line;
788 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
789 $sth = $dbh->prepare($query);
790 $sth->execute($subscriptionid);
791 my ($totalissues) = $sth->fetchrow;
792 return ( $totalissues, @serials );
797 @serials = GetSerials2($subscriptionid,$status);
798 this function returns every serial waited for a given subscription
799 as well as the number of issues registered in the database (all types)
800 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
805 my ( $subscription, $status ) = @_;
806 my $dbh = C4::Context->dbh;
808 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
810 WHERE subscriptionid=$subscription AND status IN ($status)
811 ORDER BY publisheddate,serialid DESC
813 $debug and warn "GetSerials2 query: $query";
814 my $sth = $dbh->prepare($query);
818 while ( my $line = $sth->fetchrow_hashref ) {
819 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
820 # Format dates for display
821 for my $datefield ( qw( planneddate publisheddate ) ) {
822 if ($line->{$datefield} =~m/^00/) {
823 $line->{$datefield} = q{};
826 $line->{$datefield} = format_date( $line->{$datefield} );
829 push @serials, $line;
834 =head2 GetLatestSerials
836 \@serials = GetLatestSerials($subscriptionid,$limit)
837 get the $limit's latest serials arrived or missing for a given subscription
839 a ref to an array which contains all of the latest serials stored into a hash.
843 sub GetLatestSerials {
844 my ( $subscriptionid, $limit ) = @_;
845 my $dbh = C4::Context->dbh;
847 # status = 2 is "arrived"
848 my $strsth = "SELECT serialid,serialseq, status, planneddate, publisheddate, notes
850 WHERE subscriptionid = ?
851 AND (status =2 or status=4)
852 ORDER BY publisheddate DESC LIMIT 0,$limit
854 my $sth = $dbh->prepare($strsth);
855 $sth->execute($subscriptionid);
857 while ( my $line = $sth->fetchrow_hashref ) {
858 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
859 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
860 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
861 push @serials, $line;
867 =head2 GetDistributedTo
869 $distributedto=GetDistributedTo($subscriptionid)
870 This function returns the field distributedto for the subscription matching subscriptionid
874 sub GetDistributedTo {
875 my $dbh = C4::Context->dbh;
877 my $subscriptionid = @_;
878 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
879 my $sth = $dbh->prepare($query);
880 $sth->execute($subscriptionid);
881 return ($distributedto) = $sth->fetchrow;
887 $val is a hashref containing all the attributes of the table 'subscription'
888 This function get the next issue for the subscription given on input arg
890 a list containing all the input params updated.
896 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
897 # $calculated = $val->{numberingmethod};
898 # # calculate the (expected) value of the next issue recieved.
899 # $newlastvalue1 = $val->{lastvalue1};
900 # # check if we have to increase the new value.
901 # $newinnerloop1 = $val->{innerloop1}+1;
902 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
903 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
904 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
905 # $calculated =~ s/\{X\}/$newlastvalue1/g;
907 # $newlastvalue2 = $val->{lastvalue2};
908 # # check if we have to increase the new value.
909 # $newinnerloop2 = $val->{innerloop2}+1;
910 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
911 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
912 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
913 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
915 # $newlastvalue3 = $val->{lastvalue3};
916 # # check if we have to increase the new value.
917 # $newinnerloop3 = $val->{innerloop3}+1;
918 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
919 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
920 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
921 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
922 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
927 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
928 my $pattern = $val->{numberpattern};
929 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
930 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
931 $calculated = $val->{numberingmethod};
932 $newlastvalue1 = $val->{lastvalue1};
933 $newlastvalue2 = $val->{lastvalue2};
934 $newlastvalue3 = $val->{lastvalue3};
935 $newlastvalue1 = $val->{lastvalue1};
937 # check if we have to increase the new value.
938 $newinnerloop1 = $val->{innerloop1} + 1;
939 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
940 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
941 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
942 $calculated =~ s/\{X\}/$newlastvalue1/g;
944 $newlastvalue2 = $val->{lastvalue2};
946 # check if we have to increase the new value.
947 $newinnerloop2 = $val->{innerloop2} + 1;
948 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
949 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
950 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
951 if ( $pattern == 6 ) {
952 if ( $val->{hemisphere} == 2 ) {
953 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
954 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
956 my $newlastvalue2seq = $seasons[$newlastvalue2];
957 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
960 $calculated =~ s/\{Y\}/$newlastvalue2/g;
963 $newlastvalue3 = $val->{lastvalue3};
965 # check if we have to increase the new value.
966 $newinnerloop3 = $val->{innerloop3} + 1;
967 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
968 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
969 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
970 $calculated =~ s/\{Z\}/$newlastvalue3/g;
972 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
977 $calculated = GetSeq($val)
978 $val is a hashref containing all the attributes of the table 'subscription'
979 this function transforms {X},{Y},{Z} to 150,0,0 for example.
981 the sequence in integer format
987 my $pattern = $val->{numberpattern};
988 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
989 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
990 my $calculated = $val->{numberingmethod};
991 my $x = $val->{'lastvalue1'};
992 $calculated =~ s/\{X\}/$x/g;
993 my $newlastvalue2 = $val->{'lastvalue2'};
995 if ( $pattern == 6 ) {
996 if ( $val->{hemisphere} == 2 ) {
997 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
998 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
1000 my $newlastvalue2seq = $seasons[$newlastvalue2];
1001 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
1004 $calculated =~ s/\{Y\}/$newlastvalue2/g;
1006 my $z = $val->{'lastvalue3'};
1007 $calculated =~ s/\{Z\}/$z/g;
1011 =head2 GetExpirationDate
1013 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1015 this function return the next expiration date for a subscription given on input args.
1018 the enddate or undef
1022 sub GetExpirationDate {
1023 my ( $subscriptionid, $startdate ) = @_;
1024 my $dbh = C4::Context->dbh;
1025 my $subscription = GetSubscription($subscriptionid);
1028 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1029 $enddate = $startdate || $subscription->{startdate};
1030 my @date = split( /-/, $enddate );
1031 return if ( scalar(@date) != 3 || not check_date(@date) );
1032 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1035 if ( my $length = $subscription->{numberlength} ) {
1037 #calculate the date of the last issue.
1038 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1039 $enddate = GetNextDate( $enddate, $subscription );
1041 } elsif ( $subscription->{monthlength} ) {
1042 if ( $$subscription{startdate} ) {
1043 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1044 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1046 } elsif ( $subscription->{weeklength} ) {
1047 if ( $$subscription{startdate} ) {
1048 my @date = split( /-/, $subscription->{startdate} );
1049 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1050 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1059 =head2 CountSubscriptionFromBiblionumber
1061 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1062 this returns a count of the subscriptions for a given biblionumber
1064 the number of subscriptions
1068 sub CountSubscriptionFromBiblionumber {
1069 my ($biblionumber) = @_;
1070 my $dbh = C4::Context->dbh;
1071 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1072 my $sth = $dbh->prepare($query);
1073 $sth->execute($biblionumber);
1074 my $subscriptionsnumber = $sth->fetchrow;
1075 return $subscriptionsnumber;
1078 =head2 ModSubscriptionHistory
1080 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1082 this function modifies the history of a subscription. Put your new values on input arg.
1083 returns the number of rows affected
1087 sub ModSubscriptionHistory {
1088 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
1089 my $dbh = C4::Context->dbh;
1090 my $query = "UPDATE subscriptionhistory
1091 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1092 WHERE subscriptionid=?
1094 my $sth = $dbh->prepare($query);
1095 $recievedlist =~ s/^; //;
1096 $missinglist =~ s/^; //;
1097 $opacnote =~ s/^; //;
1098 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1102 =head2 ModSerialStatus
1104 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1106 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1107 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1111 sub ModSerialStatus {
1112 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1114 #It is a usual serial
1115 # 1st, get previous status :
1116 my $dbh = C4::Context->dbh;
1117 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1118 my $sth = $dbh->prepare($query);
1119 $sth->execute($serialid);
1120 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1122 # change status & update subscriptionhistory
1124 if ( $status == 6 ) {
1125 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1129 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1130 $sth = $dbh->prepare($query);
1131 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1132 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1133 $sth = $dbh->prepare($query);
1134 $sth->execute($subscriptionid);
1135 my $val = $sth->fetchrow_hashref;
1136 unless ( $val->{manualhistory} ) {
1137 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1138 $sth = $dbh->prepare($query);
1139 $sth->execute($subscriptionid);
1140 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1141 if ( $status == 2 ) {
1142 $recievedlist .= "; $serialseq"
1143 if $recievedlist!~/(^|;)\s*$serialseq(?=;|$)/;
1145 # in case serial has been previously marked as missing
1146 if (grep /$status/, (1,2,3,7)) {
1147 $missinglist=~ s/(^|;)\s*$serialseq(?=;|$)//g;
1149 $missinglist .= "; $serialseq"
1150 if $status==4 && $missinglist!~/(^|;)\s*$serialseq(?=;|$)/;
1151 $missinglist .= "; not issued $serialseq"
1152 if $status==5 && $missinglist!~/(^|;)\s*$serialseq(?=;|$)/;
1154 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1155 $sth = $dbh->prepare($query);
1156 $recievedlist =~ s/^; //;
1157 $missinglist =~ s/^; //;
1158 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1162 # create new waited entry if needed (ie : was a "waited" and has changed)
1163 if ( $oldstatus == 1 && $status != 1 ) {
1164 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1165 $sth = $dbh->prepare($query);
1166 $sth->execute($subscriptionid);
1167 my $val = $sth->fetchrow_hashref;
1171 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1172 $newinnerloop1, $newinnerloop2, $newinnerloop3
1173 ) = GetNextSeq($val);
1175 # next date (calculated from actual date & frequency parameters)
1176 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1177 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1178 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1179 WHERE subscriptionid = ?";
1180 $sth = $dbh->prepare($query);
1181 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1183 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1184 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1185 require C4::Letters;
1186 C4::Letters::SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1192 =head2 GetNextExpected
1194 $nextexpected = GetNextExpected($subscriptionid)
1196 Get the planneddate for the current expected issue of the subscription.
1202 planneddate => C4::Dates object
1207 sub GetNextExpected {
1208 my ($subscriptionid) = @_;
1209 my $dbh = C4::Context->dbh;
1210 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1212 # Each subscription has only one 'expected' issue, with serial.status==1.
1213 $sth->execute( $subscriptionid, 1 );
1214 my ( $nextissue ) = $sth->fetchrow_hashref;
1216 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1217 $sth->execute( $subscriptionid );
1218 $nextissue = $sth->fetchrow_hashref;
1220 if (!defined $nextissue->{planneddate}) {
1221 # or should this default to 1st Jan ???
1222 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1224 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1229 =head2 ModNextExpected
1231 ModNextExpected($subscriptionid,$date)
1233 Update the planneddate for the current expected issue of the subscription.
1234 This will modify all future prediction results.
1236 C<$date> is a C4::Dates object.
1242 sub ModNextExpected {
1243 my ( $subscriptionid, $date ) = @_;
1244 my $dbh = C4::Context->dbh;
1246 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1247 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1249 # Each subscription has only one 'expected' issue, with serial.status==1.
1250 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1255 =head2 ModSubscription
1257 this function modifies a subscription. Put all new values on input args.
1258 returns the number of rows affected
1262 sub ModSubscription {
1263 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1264 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1265 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1266 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1267 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1268 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1271 # warn $irregularity;
1272 my $dbh = C4::Context->dbh;
1273 my $query = "UPDATE subscription
1274 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1275 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1276 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1277 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1278 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1279 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1280 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1281 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1283 WHERE subscriptionid = ?";
1285 #warn "query :".$query;
1286 my $sth = $dbh->prepare($query);
1288 $auser, $branchcode, $aqbooksellerid, $cost,
1289 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1290 $dow, "$irregularity", $numberpattern, $numberlength,
1291 $weeklength, $monthlength, $add1, $every1,
1292 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1293 $add2, $every2, $whenmorethan2, $setto2,
1294 $lastvalue2, $innerloop2, $add3, $every3,
1295 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1296 $numberingmethod, $status, $biblionumber, $callnumber,
1297 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1298 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1299 $graceperiod, $location, $enddate, $subscriptionid
1301 my $rows = $sth->rows;
1303 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1307 =head2 NewSubscription
1309 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1310 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1311 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1312 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1313 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1314 $numberingmethod, $status, $notes, $serialsadditems,
1315 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1317 Create a new subscription with value given on input args.
1320 the id of this new subscription
1324 sub NewSubscription {
1325 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1326 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1327 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1328 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1329 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1330 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1332 my $dbh = C4::Context->dbh;
1334 #save subscription (insert into database)
1336 INSERT INTO subscription
1337 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1338 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1339 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1340 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1341 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1342 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1343 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1344 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1345 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1347 my $sth = $dbh->prepare($query);
1349 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1350 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1351 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1352 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1353 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1354 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1357 my $subscriptionid = $dbh->{'mysql_insertid'};
1359 $enddate = GetExpirationDate($subscriptionid,$startdate);
1363 WHERE subscriptionid=?
1365 $sth = $dbh->prepare($query);
1366 $sth->execute( $enddate, $subscriptionid );
1368 #then create the 1st waited number
1370 INSERT INTO subscriptionhistory
1371 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1374 $sth = $dbh->prepare($query);
1375 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1377 # reread subscription to get a hash (for calculation of the 1st issue number)
1381 WHERE subscriptionid = ?
1383 $sth = $dbh->prepare($query);
1384 $sth->execute($subscriptionid);
1385 my $val = $sth->fetchrow_hashref;
1387 # calculate issue number
1388 my $serialseq = GetSeq($val);
1391 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1392 VALUES (?,?,?,?,?,?)
1394 $sth = $dbh->prepare($query);
1395 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1397 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1399 #set serial flag on biblio if not already set.
1400 my $bib = GetBiblio($biblionumber);
1401 if ( !$bib->{'serial'} ) {
1402 my $record = GetMarcBiblio($biblionumber);
1403 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1405 eval { $record->field($tag)->update( $subf => 1 ); };
1407 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1409 return $subscriptionid;
1412 =head2 ReNewSubscription
1414 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1416 this function renew a subscription with values given on input args.
1420 sub ReNewSubscription {
1421 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1422 my $dbh = C4::Context->dbh;
1423 my $subscription = GetSubscription($subscriptionid);
1427 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1428 WHERE biblio.biblionumber=?
1430 my $sth = $dbh->prepare($query);
1431 $sth->execute( $subscription->{biblionumber} );
1432 my $biblio = $sth->fetchrow_hashref;
1434 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1435 require C4::Suggestions;
1436 C4::Suggestions::NewSuggestion(
1437 { 'suggestedby' => $user,
1438 'title' => $subscription->{bibliotitle},
1439 'author' => $biblio->{author},
1440 'publishercode' => $biblio->{publishercode},
1441 'note' => $biblio->{note},
1442 'biblionumber' => $subscription->{biblionumber}
1447 # renew subscription
1450 SET startdate=?,numberlength=?,weeklength=?,monthlength=?,reneweddate=NOW()
1451 WHERE subscriptionid=?
1453 $sth = $dbh->prepare($query);
1454 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1455 my $enddate = GetExpirationDate($subscriptionid);
1456 $debug && warn "enddate :$enddate";
1460 WHERE subscriptionid=?
1462 $sth = $dbh->prepare($query);
1463 $sth->execute( $enddate, $subscriptionid );
1465 UPDATE subscriptionhistory
1467 WHERE subscriptionid=?
1469 $sth = $dbh->prepare($query);
1470 $sth->execute( $enddate, $subscriptionid );
1472 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1478 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1480 Create a new issue stored on the database.
1481 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1482 returns the serial id
1487 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1488 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1490 my $dbh = C4::Context->dbh;
1493 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1494 VALUES (?,?,?,?,?,?,?)
1496 my $sth = $dbh->prepare($query);
1497 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1498 my $serialid = $dbh->{'mysql_insertid'};
1500 SELECT missinglist,recievedlist
1501 FROM subscriptionhistory
1502 WHERE subscriptionid=?
1504 $sth = $dbh->prepare($query);
1505 $sth->execute($subscriptionid);
1506 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1508 if ( $status == 2 ) {
1509 ### TODO Add a feature that improves recognition and description.
1510 ### As such count (serialseq) i.e. : N18,2(N19),N20
1511 ### Would use substr and index But be careful to previous presence of ()
1512 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1514 if ( $status == 4 ) {
1515 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1518 UPDATE subscriptionhistory
1519 SET recievedlist=?, missinglist=?
1520 WHERE subscriptionid=?
1522 $sth = $dbh->prepare($query);
1523 $recievedlist =~ s/^; //;
1524 $missinglist =~ s/^; //;
1525 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1529 =head2 ItemizeSerials
1531 ItemizeSerials($serialid, $info);
1532 $info is a hashref containing barcode branch, itemcallnumber, status, location
1533 $serialid the serialid
1535 1 if the itemize is a succes.
1536 0 and @error otherwise. @error containts the list of errors found.
1540 sub ItemizeSerials {
1541 my ( $serialid, $info ) = @_;
1542 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1544 my $dbh = C4::Context->dbh;
1550 my $sth = $dbh->prepare($query);
1551 $sth->execute($serialid);
1552 my $data = $sth->fetchrow_hashref;
1553 if ( C4::Context->preference("RoutingSerials") ) {
1555 # check for existing biblioitem relating to serial issue
1556 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1558 for ( my $i = 0 ; $i < $count ; $i++ ) {
1559 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1560 $bibitemno = $results[$i]->{'biblioitemnumber'};
1564 if ( $bibitemno == 0 ) {
1565 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1566 $sth->execute( $data->{'biblionumber'} );
1567 my $biblioitem = $sth->fetchrow_hashref;
1568 $biblioitem->{'volumedate'} = $data->{planneddate};
1569 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1570 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1574 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1575 if ( $info->{barcode} ) {
1577 if ( is_barcode_in_use( $info->{barcode} ) ) {
1578 push @errors, 'barcode_not_unique';
1580 my $marcrecord = MARC::Record->new();
1581 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1582 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1583 $marcrecord->insert_fields_ordered($newField);
1584 if ( $info->{branch} ) {
1585 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1587 #warn "items.homebranch : $tag , $subfield";
1588 if ( $marcrecord->field($tag) ) {
1589 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1591 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1592 $marcrecord->insert_fields_ordered($newField);
1594 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1596 #warn "items.holdingbranch : $tag , $subfield";
1597 if ( $marcrecord->field($tag) ) {
1598 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1600 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1601 $marcrecord->insert_fields_ordered($newField);
1604 if ( $info->{itemcallnumber} ) {
1605 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1607 if ( $marcrecord->field($tag) ) {
1608 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1610 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1611 $marcrecord->insert_fields_ordered($newField);
1614 if ( $info->{notes} ) {
1615 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1617 if ( $marcrecord->field($tag) ) {
1618 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1620 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1621 $marcrecord->insert_fields_ordered($newField);
1624 if ( $info->{location} ) {
1625 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1627 if ( $marcrecord->field($tag) ) {
1628 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1630 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1631 $marcrecord->insert_fields_ordered($newField);
1634 if ( $info->{status} ) {
1635 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1637 if ( $marcrecord->field($tag) ) {
1638 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1640 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1641 $marcrecord->insert_fields_ordered($newField);
1644 if ( C4::Context->preference("RoutingSerials") ) {
1645 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1646 if ( $marcrecord->field($tag) ) {
1647 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1649 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1650 $marcrecord->insert_fields_ordered($newField);
1654 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1657 return ( 0, @errors );
1661 =head2 HasSubscriptionStrictlyExpired
1663 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1665 the subscription has stricly expired when today > the end subscription date
1668 1 if true, 0 if false, -1 if the expiration date is not set.
1672 sub HasSubscriptionStrictlyExpired {
1674 # Getting end of subscription date
1675 my ($subscriptionid) = @_;
1676 my $dbh = C4::Context->dbh;
1677 my $subscription = GetSubscription($subscriptionid);
1678 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1680 # If the expiration date is set
1681 if ( $expirationdate != 0 ) {
1682 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1684 # Getting today's date
1685 my ( $nowyear, $nowmonth, $nowday ) = Today();
1687 # if today's date > expiration date, then the subscription has stricly expired
1688 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1695 # There are some cases where the expiration date is not set
1696 # As we can't determine if the subscription has expired on a date-basis,
1702 =head2 HasSubscriptionExpired
1704 $has_expired = HasSubscriptionExpired($subscriptionid)
1706 the subscription has expired when the next issue to arrive is out of subscription limit.
1709 0 if the subscription has not expired
1710 1 if the subscription has expired
1711 2 if has subscription does not have a valid expiration date set
1715 sub HasSubscriptionExpired {
1716 my ($subscriptionid) = @_;
1717 my $dbh = C4::Context->dbh;
1718 my $subscription = GetSubscription($subscriptionid);
1719 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1720 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1721 if (!defined $expirationdate) {
1722 $expirationdate = q{};
1725 SELECT max(planneddate)
1727 WHERE subscriptionid=?
1729 my $sth = $dbh->prepare($query);
1730 $sth->execute($subscriptionid);
1731 my ($res) = $sth->fetchrow;
1732 if (!$res || $res=~m/^0000/) {
1735 my @res = split( /-/, $res );
1736 my @endofsubscriptiondate = split( /-/, $expirationdate );
1737 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1739 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1743 if ( $subscription->{'numberlength'} ) {
1744 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1745 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1751 return 0; # Notice that you'll never get here.
1754 =head2 SetDistributedto
1756 SetDistributedto($distributedto,$subscriptionid);
1757 This function update the value of distributedto for a subscription given on input arg.
1761 sub SetDistributedto {
1762 my ( $distributedto, $subscriptionid ) = @_;
1763 my $dbh = C4::Context->dbh;
1767 WHERE subscriptionid=?
1769 my $sth = $dbh->prepare($query);
1770 $sth->execute( $distributedto, $subscriptionid );
1774 =head2 DelSubscription
1776 DelSubscription($subscriptionid)
1777 this function deletes subscription which has $subscriptionid as id.
1781 sub DelSubscription {
1782 my ($subscriptionid) = @_;
1783 my $dbh = C4::Context->dbh;
1784 $subscriptionid = $dbh->quote($subscriptionid);
1785 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1786 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1787 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1789 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1794 DelIssue($serialseq,$subscriptionid)
1795 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1797 returns the number of rows affected
1802 my ($dataissue) = @_;
1803 my $dbh = C4::Context->dbh;
1804 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1809 AND subscriptionid= ?
1811 my $mainsth = $dbh->prepare($query);
1812 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1814 #Delete element from subscription history
1815 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1816 my $sth = $dbh->prepare($query);
1817 $sth->execute( $dataissue->{'subscriptionid'} );
1818 my $val = $sth->fetchrow_hashref;
1819 unless ( $val->{manualhistory} ) {
1821 SELECT * FROM subscriptionhistory
1822 WHERE subscriptionid= ?
1824 my $sth = $dbh->prepare($query);
1825 $sth->execute( $dataissue->{'subscriptionid'} );
1826 my $data = $sth->fetchrow_hashref;
1827 my $serialseq = $dataissue->{'serialseq'};
1828 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1829 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1830 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1831 $sth = $dbh->prepare($strsth);
1832 $sth->execute( $dataissue->{'subscriptionid'} );
1835 return $mainsth->rows;
1838 =head2 GetLateOrMissingIssues
1840 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1842 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1845 the issuelist as an array of hash refs. Each element of this array contains
1846 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1850 sub GetLateOrMissingIssues {
1851 my ( $supplierid, $serialid, $order ) = @_;
1852 my $dbh = C4::Context->dbh;
1856 $byserial = "and serialid = " . $serialid;
1859 $order .= ", title";
1864 $sth = $dbh->prepare(
1866 serialid, aqbooksellerid, name,
1867 biblio.title, planneddate, serialseq,
1868 serial.status, serial.subscriptionid, claimdate,
1869 subscription.branchcode
1871 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1872 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1873 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1874 WHERE subscription.subscriptionid = serial.subscriptionid
1875 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1876 AND subscription.aqbooksellerid=$supplierid
1881 $sth = $dbh->prepare(
1883 serialid, aqbooksellerid, name,
1884 biblio.title, planneddate, serialseq,
1885 serial.status, serial.subscriptionid, claimdate,
1886 subscription.branchcode
1888 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1889 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1890 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1891 WHERE subscription.subscriptionid = serial.subscriptionid
1892 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1899 while ( my $line = $sth->fetchrow_hashref ) {
1901 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1902 $line->{planneddate} = format_date( $line->{planneddate} );
1904 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1905 $line->{claimdate} = format_date( $line->{claimdate} );
1907 $line->{"status".$line->{status}} = 1;
1908 push @issuelist, $line;
1913 =head2 removeMissingIssue
1915 removeMissingIssue($subscriptionid)
1917 this function removes an issue from being part of the missing string in
1918 subscriptionlist.missinglist column
1920 called when a missing issue is found from the serials-recieve.pl file
1924 sub removeMissingIssue {
1925 my ( $sequence, $subscriptionid ) = @_;
1926 my $dbh = C4::Context->dbh;
1927 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1928 $sth->execute($subscriptionid);
1929 my $data = $sth->fetchrow_hashref;
1930 my $missinglist = $data->{'missinglist'};
1931 my $missinglistbefore = $missinglist;
1933 # warn $missinglist." before";
1934 $missinglist =~ s/($sequence)//;
1936 # warn $missinglist." after";
1937 if ( $missinglist ne $missinglistbefore ) {
1938 $missinglist =~ s/\|\s\|/\|/g;
1939 $missinglist =~ s/^\| //g;
1940 $missinglist =~ s/\|$//g;
1941 my $sth2 = $dbh->prepare(
1942 "UPDATE subscriptionhistory
1944 WHERE subscriptionid = ?"
1946 $sth2->execute( $missinglist, $subscriptionid );
1953 &updateClaim($serialid)
1955 this function updates the time when a claim is issued for late/missing items
1957 called from claims.pl file
1962 my ($serialid) = @_;
1963 my $dbh = C4::Context->dbh;
1964 my $sth = $dbh->prepare(
1965 "UPDATE serial SET claimdate = now()
1969 $sth->execute($serialid);
1973 =head2 getsupplierbyserialid
1975 $result = getsupplierbyserialid($serialid)
1977 this function is used to find the supplier id given a serial id
1980 hashref containing serialid, subscriptionid, and aqbooksellerid
1984 sub getsupplierbyserialid {
1985 my ($serialid) = @_;
1986 my $dbh = C4::Context->dbh;
1987 my $sth = $dbh->prepare(
1988 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1990 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1994 $sth->execute($serialid);
1995 my $line = $sth->fetchrow_hashref;
1996 my $result = $line->{'aqbooksellerid'};
2000 =head2 check_routing
2002 $result = &check_routing($subscriptionid)
2004 this function checks to see if a serial has a routing list and returns the count of routingid
2005 used to show either an 'add' or 'edit' link
2010 my ($subscriptionid) = @_;
2011 my $dbh = C4::Context->dbh;
2012 my $sth = $dbh->prepare(
2013 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
2014 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2015 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2018 $sth->execute($subscriptionid);
2019 my $line = $sth->fetchrow_hashref;
2020 my $result = $line->{'routingids'};
2024 =head2 addroutingmember
2026 addroutingmember($borrowernumber,$subscriptionid)
2028 this function takes a borrowernumber and subscriptionid and adds the member to the
2029 routing list for that serial subscription and gives them a rank on the list
2030 of either 1 or highest current rank + 1
2034 sub addroutingmember {
2035 my ( $borrowernumber, $subscriptionid ) = @_;
2037 my $dbh = C4::Context->dbh;
2038 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
2039 $sth->execute($subscriptionid);
2040 while ( my $line = $sth->fetchrow_hashref ) {
2041 if ( $line->{'rank'} > 0 ) {
2042 $rank = $line->{'rank'} + 1;
2047 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
2048 $sth->execute( $subscriptionid, $borrowernumber, $rank );
2051 =head2 reorder_members
2053 reorder_members($subscriptionid,$routingid,$rank)
2055 this function is used to reorder the routing list
2057 it takes the routingid of the member one wants to re-rank and the rank it is to move to
2058 - it gets all members on list puts their routingid's into an array
2059 - removes the one in the array that is $routingid
2060 - then reinjects $routingid at point indicated by $rank
2061 - then update the database with the routingids in the new order
2065 sub reorder_members {
2066 my ( $subscriptionid, $routingid, $rank ) = @_;
2067 my $dbh = C4::Context->dbh;
2068 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
2069 $sth->execute($subscriptionid);
2071 while ( my $line = $sth->fetchrow_hashref ) {
2072 push( @result, $line->{'routingid'} );
2075 # To find the matching index
2077 my $key = -1; # to allow for 0 being a valid response
2078 for ( $i = 0 ; $i < @result ; $i++ ) {
2079 if ( $routingid == $result[$i] ) {
2080 $key = $i; # save the index
2085 # if index exists in array then move it to new position
2086 if ( $key > -1 && $rank > 0 ) {
2087 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
2088 my $moving_item = splice( @result, $key, 1 );
2089 splice( @result, $new_rank, 0, $moving_item );
2091 for ( my $j = 0 ; $j < @result ; $j++ ) {
2092 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
2098 =head2 delroutingmember
2100 delroutingmember($routingid,$subscriptionid)
2102 this function either deletes one member from routing list if $routingid exists otherwise
2103 deletes all members from the routing list
2107 sub delroutingmember {
2109 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2110 my ( $routingid, $subscriptionid ) = @_;
2111 my $dbh = C4::Context->dbh;
2113 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2114 $sth->execute($routingid);
2115 reorder_members( $subscriptionid, $routingid );
2117 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2118 $sth->execute($subscriptionid);
2123 =head2 getroutinglist
2125 @routinglist = getroutinglist($subscriptionid)
2127 this gets the info from the subscriptionroutinglist for $subscriptionid
2130 the routinglist as an array. Each element of the array contains a hash_ref containing
2131 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2135 sub getroutinglist {
2136 my ($subscriptionid) = @_;
2137 my $dbh = C4::Context->dbh;
2138 my $sth = $dbh->prepare(
2139 'SELECT routingid, borrowernumber, ranking, biblionumber
2141 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2142 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2144 $sth->execute($subscriptionid);
2145 my $routinglist = $sth->fetchall_arrayref({});
2146 return @{$routinglist};
2149 =head2 countissuesfrom
2151 $result = countissuesfrom($subscriptionid,$startdate)
2153 Returns a count of serial rows matching the given subsctiptionid
2154 with published date greater than startdate
2158 sub countissuesfrom {
2159 my ( $subscriptionid, $startdate ) = @_;
2160 my $dbh = C4::Context->dbh;
2164 WHERE subscriptionid=?
2165 AND serial.publisheddate>?
2167 my $sth = $dbh->prepare($query);
2168 $sth->execute( $subscriptionid, $startdate );
2169 my ($countreceived) = $sth->fetchrow;
2170 return $countreceived;
2175 $result = CountIssues($subscriptionid)
2177 Returns a count of serial rows matching the given subsctiptionid
2182 my ($subscriptionid) = @_;
2183 my $dbh = C4::Context->dbh;
2187 WHERE subscriptionid=?
2189 my $sth = $dbh->prepare($query);
2190 $sth->execute($subscriptionid);
2191 my ($countreceived) = $sth->fetchrow;
2192 return $countreceived;
2197 $result = HasItems($subscriptionid)
2199 returns a count of items from serial matching the subscriptionid
2204 my ($subscriptionid) = @_;
2205 my $dbh = C4::Context->dbh;
2207 SELECT COUNT(serialitems.itemnumber)
2209 LEFT JOIN serialitems USING(serialid)
2210 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2212 my $sth=$dbh->prepare($query);
2213 $sth->execute($subscriptionid);
2214 my ($countitems)=$sth->fetchrow_array();
2218 =head2 abouttoexpire
2220 $result = abouttoexpire($subscriptionid)
2222 this function alerts you to the penultimate issue for a serial subscription
2224 returns 1 - if this is the penultimate issue
2230 my ($subscriptionid) = @_;
2231 my $dbh = C4::Context->dbh;
2232 my $subscription = GetSubscription($subscriptionid);
2233 my $per = $subscription->{'periodicity'};
2234 if ($per && $per % 16 > 0){
2235 my $expirationdate = GetExpirationDate($subscriptionid);
2236 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2239 @res=split (/-/,$res);
2240 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2241 } else { # default an undefined value
2242 @res=Date::Calc::Today;
2244 my @endofsubscriptiondate=split(/-/,$expirationdate);
2245 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2247 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2248 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2249 return 1 if ( @res &&
2251 Delta_Days($res[0],$res[1],$res[2],
2252 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2253 (@endofsubscriptiondate &&
2254 Delta_Days($res[0],$res[1],$res[2],
2255 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2257 } elsif ($subscription->{numberlength}>0) {
2258 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2263 sub in_array { # used in next sub down
2264 my ( $val, @elements ) = @_;
2265 foreach my $elem (@elements) {
2266 if ( $val == $elem ) {
2273 =head2 GetSubscriptionsFromBorrower
2275 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2277 this gets the info from subscriptionroutinglist for each $subscriptionid
2280 a count of the serial subscription routing lists to which a patron belongs,
2281 with the titles of those serial subscriptions as an array. Each element of the array
2282 contains a hash_ref with subscriptionID and title of subscription.
2286 sub GetSubscriptionsFromBorrower {
2287 my ($borrowernumber) = @_;
2288 my $dbh = C4::Context->dbh;
2289 my $sth = $dbh->prepare(
2290 "SELECT subscription.subscriptionid, biblio.title
2292 JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2293 JOIN subscriptionroutinglist USING (subscriptionid)
2294 WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2297 $sth->execute($borrowernumber);
2300 while ( my $line = $sth->fetchrow_hashref ) {
2302 push( @routinglist, $line );
2304 return ( $count, @routinglist );
2309 $resultdate = GetNextDate($planneddate,$subscription)
2311 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2312 exists an irregularity
2313 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2314 skipped then the returned date will be 2007-05-10
2317 $resultdate - then next date in the sequence
2319 Return 0 if periodicity==0
2324 my ( $planneddate, $subscription ) = @_;
2325 my @irreg = split( /\,/, $subscription->{irregularity} );
2327 #date supposed to be in ISO.
2329 my ( $year, $month, $day ) = split( /-/, $planneddate );
2330 $month = 1 unless ($month);
2331 $day = 1 unless ($day);
2334 # warn "DOW $dayofweek";
2335 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2340 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2341 # renaming this pattern from 1/day to " n / week ".
2342 if ( $subscription->{periodicity} == 1 ) {
2343 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2344 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2346 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2347 $dayofweek = 0 if ( $dayofweek == 7 );
2348 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2349 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2353 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2358 if ( $subscription->{periodicity} == 2 ) {
2359 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2360 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2362 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2364 #FIXME: if two consecutive irreg, do we only skip one?
2365 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2366 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2367 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2370 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2375 if ( $subscription->{periodicity} == 3 ) {
2376 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2377 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2379 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2380 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2381 ### BUGFIX was previously +1 ^
2382 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2383 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2386 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2391 if ( $subscription->{periodicity} == 4 ) {
2392 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2393 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2395 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2396 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2397 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2398 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2401 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2404 my $tmpmonth = $month;
2405 if ( $year && $month && $day ) {
2406 if ( $subscription->{periodicity} == 5 ) {
2407 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2408 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2409 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2410 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2413 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2415 if ( $subscription->{periodicity} == 6 ) {
2416 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2417 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2418 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2419 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2422 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2424 if ( $subscription->{periodicity} == 7 ) {
2425 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2426 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2427 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2428 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2431 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2433 if ( $subscription->{periodicity} == 8 ) {
2434 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2435 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2436 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2437 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2440 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2442 if ( $subscription->{periodicity} == 13 ) {
2443 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2444 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2445 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2446 $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2449 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2451 if ( $subscription->{periodicity} == 9 ) {
2452 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2453 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2454 ### BUFIX Seems to need more Than One ?
2455 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2456 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2459 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2461 if ( $subscription->{periodicity} == 10 ) {
2462 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2464 if ( $subscription->{periodicity} == 11 ) {
2465 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2468 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2470 return "$resultdate";
2473 =head2 is_barcode_in_use
2475 Returns number of occurence of the barcode in the items table
2476 Can be used as a boolean test of whether the barcode has
2477 been deployed as yet
2481 sub is_barcode_in_use {
2482 my $barcode = shift;
2483 my $dbh = C4::Context->dbh;
2484 my $occurences = $dbh->selectall_arrayref(
2485 'SELECT itemnumber from items where barcode = ?',
2490 return @{$occurences};
2493 =head2 CloseSubscription
2494 Close a subscription given a subscriptionid
2496 sub CloseSubscription {
2497 my ( $subscriptionid ) = @_;
2498 return unless $subscriptionid;
2499 my $dbh = C4::Context->dbh;
2500 my $sth = $dbh->prepare( qq{
2503 WHERE subscriptionid = ?
2505 $sth->execute( $subscriptionid );
2507 # Set status = missing when status = stopped
2508 $sth = $dbh->prepare( qq{
2511 WHERE subscriptionid = ?
2514 $sth->execute( $subscriptionid );
2517 =head2 ReopenSubscription
2518 Reopen a subscription given a subscriptionid
2520 sub ReopenSubscription {
2521 my ( $subscriptionid ) = @_;
2522 return unless $subscriptionid;
2523 my $dbh = C4::Context->dbh;
2524 my $sth = $dbh->prepare( qq{
2527 WHERE subscriptionid = ?
2529 $sth->execute( $subscriptionid );
2531 # Set status = expected when status = stopped
2532 $sth = $dbh->prepare( qq{
2535 WHERE subscriptionid = ?
2538 $sth->execute( $subscriptionid );
2541 =head2 subscriptionCurrentlyOnOrder
2543 $bool = subscriptionCurrentlyOnOrder( $subscriptionid );
2545 Return 1 if subscription is currently on order else 0.
2549 sub subscriptionCurrentlyOnOrder {
2550 my ( $subscriptionid ) = @_;
2551 my $dbh = C4::Context->dbh;
2553 SELECT COUNT(*) FROM aqorders
2554 WHERE subscriptionid = ?
2555 AND datereceived IS NULL
2556 AND datecancellationprinted IS NULL
2558 my $sth = $dbh->prepare( $query );
2559 $sth->execute($subscriptionid);
2560 return $sth->fetchrow_array;
2568 Koha Development Team <http://koha-community.org/>