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('IndependantBranches')
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('IndependantBranches')
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('IndependantBranches') &&
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('IndependantBranches')
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->{$datefield} = format_date( $subs->{$datefield} );
426 $subs->{ "status" . $subs->{'status'} } = 1;
427 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
429 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
430 $year = $subs->{'year'};
434 if ( $tmpresults{$year} ) {
435 push @{ $tmpresults{$year}->{'serials'} }, $subs;
437 $tmpresults{$year} = {
439 'aqbooksellername' => $subs->{'aqbooksellername'},
440 'bibliotitle' => $subs->{'bibliotitle'},
441 'serials' => [$subs],
446 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
447 push @res, $tmpresults{$key};
452 =head2 GetSubscriptionsFromBiblionumber
454 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
455 this function get the subscription list. it reads the subscription table.
457 reference to an array of subscriptions which have the biblionumber given on input arg.
458 each element of this array is a hashref containing
459 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
463 sub GetSubscriptionsFromBiblionumber {
464 my ($biblionumber) = @_;
465 my $dbh = C4::Context->dbh;
467 SELECT subscription.*,
469 subscriptionhistory.*,
470 aqbooksellers.name AS aqbooksellername,
471 biblio.title AS bibliotitle
473 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
474 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
475 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
476 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
477 WHERE subscription.biblionumber = ?
479 my $sth = $dbh->prepare($query);
480 $sth->execute($biblionumber);
482 while ( my $subs = $sth->fetchrow_hashref ) {
483 $subs->{startdate} = format_date( $subs->{startdate} );
484 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
485 $subs->{histenddate} = format_date( $subs->{histenddate} );
486 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
487 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
488 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
489 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
490 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
491 $subs->{ "status" . $subs->{'status'} } = 1;
492 $subs->{'cannotedit'} =
493 ( C4::Context->preference('IndependantBranches')
494 && C4::Context->userenv
495 && C4::Context->userenv->{flags} % 2 != 1
496 && C4::Context->userenv->{branch}
497 && $subs->{branchcode}
498 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
500 if ( $subs->{enddate} eq '0000-00-00' ) {
501 $subs->{enddate} = '';
503 $subs->{enddate} = format_date( $subs->{enddate} );
505 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
506 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
512 =head2 GetFullSubscriptionsFromBiblionumber
514 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
515 this function reads the serial table.
519 sub GetFullSubscriptionsFromBiblionumber {
520 my ($biblionumber) = @_;
521 my $dbh = C4::Context->dbh;
523 SELECT serial.serialid,
526 serial.publisheddate,
528 serial.notes as notes,
529 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
530 biblio.title as bibliotitle,
531 subscription.branchcode AS branchcode,
532 subscription.subscriptionid AS subscriptionid|;
533 if ( C4::Context->preference('IndependantBranches')
534 && C4::Context->userenv
535 && C4::Context->userenv->{'flags'} != 1
536 && C4::Context->userenv->{'branch'} ) {
538 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
543 LEFT JOIN subscription ON
544 (serial.subscriptionid=subscription.subscriptionid)
545 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
546 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
547 WHERE subscription.biblionumber = ?
549 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
550 serial.subscriptionid
552 my $sth = $dbh->prepare($query);
553 $sth->execute($biblionumber);
554 return $sth->fetchall_arrayref( {} );
557 =head2 GetSubscriptions
559 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
560 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
562 a table of hashref. Each hash containt the subscription.
566 sub GetSubscriptions {
567 my ( $string, $issn, $ean, $biblionumber ) = @_;
569 #return unless $title or $ISSN or $biblionumber;
570 my $dbh = C4::Context->dbh;
573 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
575 LEFT JOIN subscriptionhistory USING(subscriptionid)
576 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
577 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
582 $sqlwhere = " WHERE biblio.biblionumber=?";
583 push @bind_params, $biblionumber;
587 my @strings_to_search;
588 @strings_to_search = map { "%$_%" } split( / /, $string );
589 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
590 push @bind_params, @strings_to_search;
591 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
592 $debug && warn "$tmpstring";
593 $tmpstring =~ s/^AND //;
594 push @sqlstrings, $tmpstring;
596 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
600 my @strings_to_search;
601 @strings_to_search = map { "%$_%" } split( / /, $issn );
602 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
603 push @bind_params, @strings_to_search;
604 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
605 $debug && warn "$tmpstring";
606 $tmpstring =~ s/^OR //;
607 push @sqlstrings, $tmpstring;
609 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
613 my @strings_to_search;
614 @strings_to_search = map { "$_" } split( / /, $ean );
615 foreach my $index ( qw(biblioitems.ean) ) {
616 push @bind_params, @strings_to_search;
617 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
618 $debug && warn "$tmpstring";
619 $tmpstring =~ s/^OR //;
620 push @sqlstrings, $tmpstring;
622 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
625 $sql .= "$sqlwhere ORDER BY title";
626 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
627 $sth = $dbh->prepare($sql);
628 $sth->execute(@bind_params);
631 while ( my $line = $sth->fetchrow_hashref ) {
632 $line->{'cannotedit'} =
633 ( C4::Context->preference('IndependantBranches')
634 && C4::Context->userenv
635 && C4::Context->userenv->{flags} % 2 != 1
636 && C4::Context->userenv->{branch}
637 && $line->{branchcode}
638 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
639 push @results, $line;
644 =head2 SearchSubscriptions
646 @results = SearchSubscriptions($args);
647 $args is a hashref. Its keys can be contained: title, issn, ean, publisher, bookseller and branchcode
649 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.
652 a table of hashref. Each hash containt the subscription.
656 sub SearchSubscriptions {
660 SELECT subscription.*, subscriptionhistory.*, biblio.*, biblioitems.issn
662 LEFT JOIN subscriptionhistory USING(subscriptionid)
663 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
664 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
665 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
669 if( $args->{biblionumber} ) {
670 push @where_strs, "biblio.biblionumber = ?";
671 push @where_args, $args->{biblionumber};
673 if( $args->{title} ){
674 my @words = split / /, $args->{title};
676 foreach my $word (@words) {
677 push @strs, "biblio.title LIKE ?";
678 push @args, "%$word%";
681 push @where_strs, '(' . join (' AND ', @strs) . ')';
682 push @where_args, @args;
686 push @where_strs, "biblioitems.issn LIKE ?";
687 push @where_args, "%$args->{issn}%";
690 push @where_strs, "biblioitems.ean LIKE ?";
691 push @where_args, "%$args->{ean}%";
693 if( $args->{publisher} ){
694 push @where_strs, "biblioitems.publishercode LIKE ?";
695 push @where_args, "%$args->{publisher}%";
697 if( $args->{bookseller} ){
698 push @where_strs, "aqbooksellers.name LIKE ?";
699 push @where_args, "%$args->{bookseller}%";
701 if( $args->{branch} ){
702 push @where_strs, "subscription.branchcode = ?";
703 push @where_args, "$args->{branch}";
705 if( defined $args->{closed} ){
706 push @where_strs, "subscription.closed = ?";
707 push @where_args, "$args->{closed}";
710 $query .= " WHERE " . join(" AND ", @where_strs);
713 my $dbh = C4::Context->dbh;
714 my $sth = $dbh->prepare($query);
715 $sth->execute(@where_args);
716 my $results = $sth->fetchall_arrayref( {} );
725 ($totalissues,@serials) = GetSerials($subscriptionid);
726 this function gets every serial not arrived for a given subscription
727 as well as the number of issues registered in the database (all types)
728 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
730 FIXME: We should return \@serials.
735 my ( $subscriptionid, $count ) = @_;
736 my $dbh = C4::Context->dbh;
738 # status = 2 is "arrived"
740 $count = 5 unless ($count);
742 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
744 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
745 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
746 my $sth = $dbh->prepare($query);
747 $sth->execute($subscriptionid);
749 while ( my $line = $sth->fetchrow_hashref ) {
750 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
751 for my $datefield ( qw( planneddate publisheddate) ) {
752 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
753 $line->{$datefield} = format_date( $line->{$datefield});
755 $line->{$datefield} = q{};
758 push @serials, $line;
761 # OK, now add the last 5 issues arrives/missing
762 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
764 WHERE subscriptionid = ?
765 AND (status in (2,4,5))
766 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
768 $sth = $dbh->prepare($query);
769 $sth->execute($subscriptionid);
770 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
772 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
773 for my $datefield ( qw( planneddate publisheddate) ) {
774 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
775 $line->{$datefield} = format_date( $line->{$datefield});
777 $line->{$datefield} = q{};
781 push @serials, $line;
784 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
785 $sth = $dbh->prepare($query);
786 $sth->execute($subscriptionid);
787 my ($totalissues) = $sth->fetchrow;
788 return ( $totalissues, @serials );
793 @serials = GetSerials2($subscriptionid,$status);
794 this function returns every serial waited for a given subscription
795 as well as the number of issues registered in the database (all types)
796 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
801 my ( $subscription, $status ) = @_;
802 my $dbh = C4::Context->dbh;
804 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
806 WHERE subscriptionid=$subscription AND status IN ($status)
807 ORDER BY publisheddate,serialid DESC
809 $debug and warn "GetSerials2 query: $query";
810 my $sth = $dbh->prepare($query);
814 while ( my $line = $sth->fetchrow_hashref ) {
815 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
816 # Format dates for display
817 for my $datefield ( qw( planneddate publisheddate ) ) {
818 if ($line->{$datefield} =~m/^00/) {
819 $line->{$datefield} = q{};
822 $line->{$datefield} = format_date( $line->{$datefield} );
825 push @serials, $line;
830 =head2 GetLatestSerials
832 \@serials = GetLatestSerials($subscriptionid,$limit)
833 get the $limit's latest serials arrived or missing for a given subscription
835 a ref to an array which contains all of the latest serials stored into a hash.
839 sub GetLatestSerials {
840 my ( $subscriptionid, $limit ) = @_;
841 my $dbh = C4::Context->dbh;
843 # status = 2 is "arrived"
844 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
846 WHERE subscriptionid = ?
847 AND (status =2 or status=4)
848 ORDER BY publisheddate DESC LIMIT 0,$limit
850 my $sth = $dbh->prepare($strsth);
851 $sth->execute($subscriptionid);
853 while ( my $line = $sth->fetchrow_hashref ) {
854 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
855 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
856 push @serials, $line;
862 =head2 GetDistributedTo
864 $distributedto=GetDistributedTo($subscriptionid)
865 This function returns the field distributedto for the subscription matching subscriptionid
869 sub GetDistributedTo {
870 my $dbh = C4::Context->dbh;
872 my $subscriptionid = @_;
873 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
874 my $sth = $dbh->prepare($query);
875 $sth->execute($subscriptionid);
876 return ($distributedto) = $sth->fetchrow;
882 $val is a hashref containing all the attributes of the table 'subscription'
883 This function get the next issue for the subscription given on input arg
885 a list containing all the input params updated.
891 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
892 # $calculated = $val->{numberingmethod};
893 # # calculate the (expected) value of the next issue recieved.
894 # $newlastvalue1 = $val->{lastvalue1};
895 # # check if we have to increase the new value.
896 # $newinnerloop1 = $val->{innerloop1}+1;
897 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
898 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
899 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
900 # $calculated =~ s/\{X\}/$newlastvalue1/g;
902 # $newlastvalue2 = $val->{lastvalue2};
903 # # check if we have to increase the new value.
904 # $newinnerloop2 = $val->{innerloop2}+1;
905 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
906 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
907 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
908 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
910 # $newlastvalue3 = $val->{lastvalue3};
911 # # check if we have to increase the new value.
912 # $newinnerloop3 = $val->{innerloop3}+1;
913 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
914 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
915 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
916 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
917 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
922 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
923 my $pattern = $val->{numberpattern};
924 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
925 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
926 $calculated = $val->{numberingmethod};
927 $newlastvalue1 = $val->{lastvalue1};
928 $newlastvalue2 = $val->{lastvalue2};
929 $newlastvalue3 = $val->{lastvalue3};
930 $newlastvalue1 = $val->{lastvalue1};
932 # check if we have to increase the new value.
933 $newinnerloop1 = $val->{innerloop1} + 1;
934 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
935 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
936 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
937 $calculated =~ s/\{X\}/$newlastvalue1/g;
939 $newlastvalue2 = $val->{lastvalue2};
941 # check if we have to increase the new value.
942 $newinnerloop2 = $val->{innerloop2} + 1;
943 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
944 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
945 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
946 if ( $pattern == 6 ) {
947 if ( $val->{hemisphere} == 2 ) {
948 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
949 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
951 my $newlastvalue2seq = $seasons[$newlastvalue2];
952 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
955 $calculated =~ s/\{Y\}/$newlastvalue2/g;
958 $newlastvalue3 = $val->{lastvalue3};
960 # check if we have to increase the new value.
961 $newinnerloop3 = $val->{innerloop3} + 1;
962 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
963 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
964 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
965 $calculated =~ s/\{Z\}/$newlastvalue3/g;
967 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
972 $calculated = GetSeq($val)
973 $val is a hashref containing all the attributes of the table 'subscription'
974 this function transforms {X},{Y},{Z} to 150,0,0 for example.
976 the sequence in integer format
982 my $pattern = $val->{numberpattern};
983 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
984 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
985 my $calculated = $val->{numberingmethod};
986 my $x = $val->{'lastvalue1'};
987 $calculated =~ s/\{X\}/$x/g;
988 my $newlastvalue2 = $val->{'lastvalue2'};
990 if ( $pattern == 6 ) {
991 if ( $val->{hemisphere} == 2 ) {
992 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
993 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
995 my $newlastvalue2seq = $seasons[$newlastvalue2];
996 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
999 $calculated =~ s/\{Y\}/$newlastvalue2/g;
1001 my $z = $val->{'lastvalue3'};
1002 $calculated =~ s/\{Z\}/$z/g;
1006 =head2 GetExpirationDate
1008 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1010 this function return the next expiration date for a subscription given on input args.
1013 the enddate or undef
1017 sub GetExpirationDate {
1018 my ( $subscriptionid, $startdate ) = @_;
1019 my $dbh = C4::Context->dbh;
1020 my $subscription = GetSubscription($subscriptionid);
1023 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1024 $enddate = $startdate || $subscription->{startdate};
1025 my @date = split( /-/, $enddate );
1026 return if ( scalar(@date) != 3 || not check_date(@date) );
1027 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1030 if ( my $length = $subscription->{numberlength} ) {
1032 #calculate the date of the last issue.
1033 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1034 $enddate = GetNextDate( $enddate, $subscription );
1036 } elsif ( $subscription->{monthlength} ) {
1037 if ( $$subscription{startdate} ) {
1038 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1039 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1041 } elsif ( $subscription->{weeklength} ) {
1042 if ( $$subscription{startdate} ) {
1043 my @date = split( /-/, $subscription->{startdate} );
1044 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1045 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1054 =head2 CountSubscriptionFromBiblionumber
1056 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1057 this returns a count of the subscriptions for a given biblionumber
1059 the number of subscriptions
1063 sub CountSubscriptionFromBiblionumber {
1064 my ($biblionumber) = @_;
1065 my $dbh = C4::Context->dbh;
1066 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1067 my $sth = $dbh->prepare($query);
1068 $sth->execute($biblionumber);
1069 my $subscriptionsnumber = $sth->fetchrow;
1070 return $subscriptionsnumber;
1073 =head2 ModSubscriptionHistory
1075 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1077 this function modifies the history of a subscription. Put your new values on input arg.
1078 returns the number of rows affected
1082 sub ModSubscriptionHistory {
1083 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
1084 my $dbh = C4::Context->dbh;
1085 my $query = "UPDATE subscriptionhistory
1086 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1087 WHERE subscriptionid=?
1089 my $sth = $dbh->prepare($query);
1090 $recievedlist =~ s/^; //;
1091 $missinglist =~ s/^; //;
1092 $opacnote =~ s/^; //;
1093 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1097 =head2 ModSerialStatus
1099 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1101 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1102 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1106 sub ModSerialStatus {
1107 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1109 #It is a usual serial
1110 # 1st, get previous status :
1111 my $dbh = C4::Context->dbh;
1112 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1113 my $sth = $dbh->prepare($query);
1114 $sth->execute($serialid);
1115 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1117 # change status & update subscriptionhistory
1119 if ( $status == 6 ) {
1120 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1124 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1125 $sth = $dbh->prepare($query);
1126 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1127 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1128 $sth = $dbh->prepare($query);
1129 $sth->execute($subscriptionid);
1130 my $val = $sth->fetchrow_hashref;
1131 unless ( $val->{manualhistory} ) {
1132 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1133 $sth = $dbh->prepare($query);
1134 $sth->execute($subscriptionid);
1135 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1136 if ( $status == 2 ) {
1138 $recievedlist .= "; $serialseq"
1139 unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1141 # in case serial has been previously marked as missing
1142 if (grep /$status/, (1,2,3,7)) {
1143 $missinglist =~ s/[,;]?\s?$serialseq//g;
1145 # warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1146 $missinglist .= "; $serialseq"
1148 and not index( "$missinglist", "$serialseq" ) >= 0 );
1149 $missinglist .= "; not issued $serialseq"
1151 and index( "$missinglist", "$serialseq" ) >= 0 );
1152 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1153 $sth = $dbh->prepare($query);
1154 $recievedlist =~ s/^; //;
1155 $missinglist =~ s/^; //;
1156 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1160 # create new waited entry if needed (ie : was a "waited" and has changed)
1161 if ( $oldstatus == 1 && $status != 1 ) {
1162 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1163 $sth = $dbh->prepare($query);
1164 $sth->execute($subscriptionid);
1165 my $val = $sth->fetchrow_hashref;
1169 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1170 $newinnerloop1, $newinnerloop2, $newinnerloop3
1171 ) = GetNextSeq($val);
1173 # next date (calculated from actual date & frequency parameters)
1174 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1175 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1176 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1177 WHERE subscriptionid = ?";
1178 $sth = $dbh->prepare($query);
1179 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1181 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1182 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1183 require C4::Letters;
1184 C4::Letters::SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1190 =head2 GetNextExpected
1192 $nextexpected = GetNextExpected($subscriptionid)
1194 Get the planneddate for the current expected issue of the subscription.
1200 planneddate => C4::Dates object
1205 sub GetNextExpected {
1206 my ($subscriptionid) = @_;
1207 my $dbh = C4::Context->dbh;
1208 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1210 # Each subscription has only one 'expected' issue, with serial.status==1.
1211 $sth->execute( $subscriptionid, 1 );
1212 my ( $nextissue ) = $sth->fetchrow_hashref;
1214 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1215 $sth->execute( $subscriptionid );
1216 $nextissue = $sth->fetchrow_hashref;
1218 if (!defined $nextissue->{planneddate}) {
1219 # or should this default to 1st Jan ???
1220 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1222 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1227 =head2 ModNextExpected
1229 ModNextExpected($subscriptionid,$date)
1231 Update the planneddate for the current expected issue of the subscription.
1232 This will modify all future prediction results.
1234 C<$date> is a C4::Dates object.
1240 sub ModNextExpected {
1241 my ( $subscriptionid, $date ) = @_;
1242 my $dbh = C4::Context->dbh;
1244 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1245 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1247 # Each subscription has only one 'expected' issue, with serial.status==1.
1248 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1253 =head2 ModSubscription
1255 this function modifies a subscription. Put all new values on input args.
1256 returns the number of rows affected
1260 sub ModSubscription {
1261 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1262 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1263 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1264 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1265 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1266 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1269 # warn $irregularity;
1270 my $dbh = C4::Context->dbh;
1271 my $query = "UPDATE subscription
1272 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1273 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1274 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1275 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1276 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1277 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1278 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1279 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1281 WHERE subscriptionid = ?";
1283 #warn "query :".$query;
1284 my $sth = $dbh->prepare($query);
1286 $auser, $branchcode, $aqbooksellerid, $cost,
1287 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1288 $dow, "$irregularity", $numberpattern, $numberlength,
1289 $weeklength, $monthlength, $add1, $every1,
1290 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1291 $add2, $every2, $whenmorethan2, $setto2,
1292 $lastvalue2, $innerloop2, $add3, $every3,
1293 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1294 $numberingmethod, $status, $biblionumber, $callnumber,
1295 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1296 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1297 $graceperiod, $location, $enddate, $subscriptionid
1299 my $rows = $sth->rows;
1301 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1305 =head2 NewSubscription
1307 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1308 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1309 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1310 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1311 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1312 $numberingmethod, $status, $notes, $serialsadditems,
1313 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1315 Create a new subscription with value given on input args.
1318 the id of this new subscription
1322 sub NewSubscription {
1323 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1324 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1325 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1326 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1327 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1328 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1330 my $dbh = C4::Context->dbh;
1332 #save subscription (insert into database)
1334 INSERT INTO subscription
1335 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1336 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1337 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1338 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1339 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1340 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1341 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1342 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1343 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1345 my $sth = $dbh->prepare($query);
1347 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1348 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1349 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1350 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1351 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1352 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1355 my $subscriptionid = $dbh->{'mysql_insertid'};
1357 $enddate = GetExpirationDate($subscriptionid,$startdate);
1361 WHERE subscriptionid=?
1363 $sth = $dbh->prepare($query);
1364 $sth->execute( $enddate, $subscriptionid );
1366 #then create the 1st waited number
1368 INSERT INTO subscriptionhistory
1369 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1372 $sth = $dbh->prepare($query);
1373 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1375 # reread subscription to get a hash (for calculation of the 1st issue number)
1379 WHERE subscriptionid = ?
1381 $sth = $dbh->prepare($query);
1382 $sth->execute($subscriptionid);
1383 my $val = $sth->fetchrow_hashref;
1385 # calculate issue number
1386 my $serialseq = GetSeq($val);
1389 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1390 VALUES (?,?,?,?,?,?)
1392 $sth = $dbh->prepare($query);
1393 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1395 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1397 #set serial flag on biblio if not already set.
1398 my $bib = GetBiblio($biblionumber);
1399 if ( !$bib->{'serial'} ) {
1400 my $record = GetMarcBiblio($biblionumber);
1401 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1403 eval { $record->field($tag)->update( $subf => 1 ); };
1405 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1407 return $subscriptionid;
1410 =head2 ReNewSubscription
1412 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1414 this function renew a subscription with values given on input args.
1418 sub ReNewSubscription {
1419 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1420 my $dbh = C4::Context->dbh;
1421 my $subscription = GetSubscription($subscriptionid);
1425 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1426 WHERE biblio.biblionumber=?
1428 my $sth = $dbh->prepare($query);
1429 $sth->execute( $subscription->{biblionumber} );
1430 my $biblio = $sth->fetchrow_hashref;
1432 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1433 require C4::Suggestions;
1434 C4::Suggestions::NewSuggestion(
1435 { 'suggestedby' => $user,
1436 'title' => $subscription->{bibliotitle},
1437 'author' => $biblio->{author},
1438 'publishercode' => $biblio->{publishercode},
1439 'note' => $biblio->{note},
1440 'biblionumber' => $subscription->{biblionumber}
1445 # renew subscription
1448 SET startdate=?,numberlength=?,weeklength=?,monthlength=?,reneweddate=NOW()
1449 WHERE subscriptionid=?
1451 $sth = $dbh->prepare($query);
1452 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1453 my $enddate = GetExpirationDate($subscriptionid);
1454 $debug && warn "enddate :$enddate";
1458 WHERE subscriptionid=?
1460 $sth = $dbh->prepare($query);
1461 $sth->execute( $enddate, $subscriptionid );
1463 UPDATE subscriptionhistory
1465 WHERE subscriptionid=?
1467 $sth = $dbh->prepare($query);
1468 $sth->execute( $enddate, $subscriptionid );
1470 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1476 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1478 Create a new issue stored on the database.
1479 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1480 returns the serial id
1485 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1486 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1488 my $dbh = C4::Context->dbh;
1491 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1492 VALUES (?,?,?,?,?,?,?)
1494 my $sth = $dbh->prepare($query);
1495 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1496 my $serialid = $dbh->{'mysql_insertid'};
1498 SELECT missinglist,recievedlist
1499 FROM subscriptionhistory
1500 WHERE subscriptionid=?
1502 $sth = $dbh->prepare($query);
1503 $sth->execute($subscriptionid);
1504 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1506 if ( $status == 2 ) {
1507 ### TODO Add a feature that improves recognition and description.
1508 ### As such count (serialseq) i.e. : N18,2(N19),N20
1509 ### Would use substr and index But be careful to previous presence of ()
1510 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1512 if ( $status == 4 ) {
1513 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1516 UPDATE subscriptionhistory
1517 SET recievedlist=?, missinglist=?
1518 WHERE subscriptionid=?
1520 $sth = $dbh->prepare($query);
1521 $recievedlist =~ s/^; //;
1522 $missinglist =~ s/^; //;
1523 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1527 =head2 ItemizeSerials
1529 ItemizeSerials($serialid, $info);
1530 $info is a hashref containing barcode branch, itemcallnumber, status, location
1531 $serialid the serialid
1533 1 if the itemize is a succes.
1534 0 and @error otherwise. @error containts the list of errors found.
1538 sub ItemizeSerials {
1539 my ( $serialid, $info ) = @_;
1540 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1542 my $dbh = C4::Context->dbh;
1548 my $sth = $dbh->prepare($query);
1549 $sth->execute($serialid);
1550 my $data = $sth->fetchrow_hashref;
1551 if ( C4::Context->preference("RoutingSerials") ) {
1553 # check for existing biblioitem relating to serial issue
1554 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1556 for ( my $i = 0 ; $i < $count ; $i++ ) {
1557 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1558 $bibitemno = $results[$i]->{'biblioitemnumber'};
1562 if ( $bibitemno == 0 ) {
1563 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1564 $sth->execute( $data->{'biblionumber'} );
1565 my $biblioitem = $sth->fetchrow_hashref;
1566 $biblioitem->{'volumedate'} = $data->{planneddate};
1567 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1568 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1572 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1573 if ( $info->{barcode} ) {
1575 if ( is_barcode_in_use( $info->{barcode} ) ) {
1576 push @errors, 'barcode_not_unique';
1578 my $marcrecord = MARC::Record->new();
1579 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1580 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1581 $marcrecord->insert_fields_ordered($newField);
1582 if ( $info->{branch} ) {
1583 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1585 #warn "items.homebranch : $tag , $subfield";
1586 if ( $marcrecord->field($tag) ) {
1587 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1589 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1590 $marcrecord->insert_fields_ordered($newField);
1592 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1594 #warn "items.holdingbranch : $tag , $subfield";
1595 if ( $marcrecord->field($tag) ) {
1596 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1598 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1599 $marcrecord->insert_fields_ordered($newField);
1602 if ( $info->{itemcallnumber} ) {
1603 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1605 if ( $marcrecord->field($tag) ) {
1606 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1608 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1609 $marcrecord->insert_fields_ordered($newField);
1612 if ( $info->{notes} ) {
1613 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1615 if ( $marcrecord->field($tag) ) {
1616 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1618 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1619 $marcrecord->insert_fields_ordered($newField);
1622 if ( $info->{location} ) {
1623 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1625 if ( $marcrecord->field($tag) ) {
1626 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1628 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1629 $marcrecord->insert_fields_ordered($newField);
1632 if ( $info->{status} ) {
1633 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1635 if ( $marcrecord->field($tag) ) {
1636 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1638 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1639 $marcrecord->insert_fields_ordered($newField);
1642 if ( C4::Context->preference("RoutingSerials") ) {
1643 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1644 if ( $marcrecord->field($tag) ) {
1645 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1647 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1648 $marcrecord->insert_fields_ordered($newField);
1652 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1655 return ( 0, @errors );
1659 =head2 HasSubscriptionStrictlyExpired
1661 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1663 the subscription has stricly expired when today > the end subscription date
1666 1 if true, 0 if false, -1 if the expiration date is not set.
1670 sub HasSubscriptionStrictlyExpired {
1672 # Getting end of subscription date
1673 my ($subscriptionid) = @_;
1674 my $dbh = C4::Context->dbh;
1675 my $subscription = GetSubscription($subscriptionid);
1676 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1678 # If the expiration date is set
1679 if ( $expirationdate != 0 ) {
1680 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1682 # Getting today's date
1683 my ( $nowyear, $nowmonth, $nowday ) = Today();
1685 # if today's date > expiration date, then the subscription has stricly expired
1686 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1693 # There are some cases where the expiration date is not set
1694 # As we can't determine if the subscription has expired on a date-basis,
1700 =head2 HasSubscriptionExpired
1702 $has_expired = HasSubscriptionExpired($subscriptionid)
1704 the subscription has expired when the next issue to arrive is out of subscription limit.
1707 0 if the subscription has not expired
1708 1 if the subscription has expired
1709 2 if has subscription does not have a valid expiration date set
1713 sub HasSubscriptionExpired {
1714 my ($subscriptionid) = @_;
1715 my $dbh = C4::Context->dbh;
1716 my $subscription = GetSubscription($subscriptionid);
1717 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1718 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1719 if (!defined $expirationdate) {
1720 $expirationdate = q{};
1723 SELECT max(planneddate)
1725 WHERE subscriptionid=?
1727 my $sth = $dbh->prepare($query);
1728 $sth->execute($subscriptionid);
1729 my ($res) = $sth->fetchrow;
1730 if (!$res || $res=~m/^0000/) {
1733 my @res = split( /-/, $res );
1734 my @endofsubscriptiondate = split( /-/, $expirationdate );
1735 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1737 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1741 if ( $subscription->{'numberlength'} ) {
1742 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1743 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1749 return 0; # Notice that you'll never get here.
1752 =head2 SetDistributedto
1754 SetDistributedto($distributedto,$subscriptionid);
1755 This function update the value of distributedto for a subscription given on input arg.
1759 sub SetDistributedto {
1760 my ( $distributedto, $subscriptionid ) = @_;
1761 my $dbh = C4::Context->dbh;
1765 WHERE subscriptionid=?
1767 my $sth = $dbh->prepare($query);
1768 $sth->execute( $distributedto, $subscriptionid );
1772 =head2 DelSubscription
1774 DelSubscription($subscriptionid)
1775 this function deletes subscription which has $subscriptionid as id.
1779 sub DelSubscription {
1780 my ($subscriptionid) = @_;
1781 my $dbh = C4::Context->dbh;
1782 $subscriptionid = $dbh->quote($subscriptionid);
1783 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1784 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1785 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1787 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1792 DelIssue($serialseq,$subscriptionid)
1793 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1795 returns the number of rows affected
1800 my ($dataissue) = @_;
1801 my $dbh = C4::Context->dbh;
1802 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1807 AND subscriptionid= ?
1809 my $mainsth = $dbh->prepare($query);
1810 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1812 #Delete element from subscription history
1813 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1814 my $sth = $dbh->prepare($query);
1815 $sth->execute( $dataissue->{'subscriptionid'} );
1816 my $val = $sth->fetchrow_hashref;
1817 unless ( $val->{manualhistory} ) {
1819 SELECT * FROM subscriptionhistory
1820 WHERE subscriptionid= ?
1822 my $sth = $dbh->prepare($query);
1823 $sth->execute( $dataissue->{'subscriptionid'} );
1824 my $data = $sth->fetchrow_hashref;
1825 my $serialseq = $dataissue->{'serialseq'};
1826 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1827 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1828 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1829 $sth = $dbh->prepare($strsth);
1830 $sth->execute( $dataissue->{'subscriptionid'} );
1833 return $mainsth->rows;
1836 =head2 GetLateOrMissingIssues
1838 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1840 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1843 the issuelist as an array of hash refs. Each element of this array contains
1844 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1848 sub GetLateOrMissingIssues {
1849 my ( $supplierid, $serialid, $order ) = @_;
1850 my $dbh = C4::Context->dbh;
1854 $byserial = "and serialid = " . $serialid;
1857 $order .= ", title";
1862 $sth = $dbh->prepare(
1864 serialid, aqbooksellerid, name,
1865 biblio.title, planneddate, serialseq,
1866 serial.status, serial.subscriptionid, claimdate,
1867 subscription.branchcode
1869 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1870 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1871 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1872 WHERE subscription.subscriptionid = serial.subscriptionid
1873 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1874 AND subscription.aqbooksellerid=$supplierid
1879 $sth = $dbh->prepare(
1881 serialid, aqbooksellerid, name,
1882 biblio.title, planneddate, serialseq,
1883 serial.status, serial.subscriptionid, claimdate,
1884 subscription.branchcode
1886 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1887 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1888 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1889 WHERE subscription.subscriptionid = serial.subscriptionid
1890 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1897 while ( my $line = $sth->fetchrow_hashref ) {
1899 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1900 $line->{planneddate} = format_date( $line->{planneddate} );
1902 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1903 $line->{claimdate} = format_date( $line->{claimdate} );
1905 $line->{"status".$line->{status}} = 1;
1906 push @issuelist, $line;
1911 =head2 removeMissingIssue
1913 removeMissingIssue($subscriptionid)
1915 this function removes an issue from being part of the missing string in
1916 subscriptionlist.missinglist column
1918 called when a missing issue is found from the serials-recieve.pl file
1922 sub removeMissingIssue {
1923 my ( $sequence, $subscriptionid ) = @_;
1924 my $dbh = C4::Context->dbh;
1925 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1926 $sth->execute($subscriptionid);
1927 my $data = $sth->fetchrow_hashref;
1928 my $missinglist = $data->{'missinglist'};
1929 my $missinglistbefore = $missinglist;
1931 # warn $missinglist." before";
1932 $missinglist =~ s/($sequence)//;
1934 # warn $missinglist." after";
1935 if ( $missinglist ne $missinglistbefore ) {
1936 $missinglist =~ s/\|\s\|/\|/g;
1937 $missinglist =~ s/^\| //g;
1938 $missinglist =~ s/\|$//g;
1939 my $sth2 = $dbh->prepare(
1940 "UPDATE subscriptionhistory
1942 WHERE subscriptionid = ?"
1944 $sth2->execute( $missinglist, $subscriptionid );
1951 &updateClaim($serialid)
1953 this function updates the time when a claim is issued for late/missing items
1955 called from claims.pl file
1960 my ($serialid) = @_;
1961 my $dbh = C4::Context->dbh;
1962 my $sth = $dbh->prepare(
1963 "UPDATE serial SET claimdate = now()
1967 $sth->execute($serialid);
1971 =head2 getsupplierbyserialid
1973 $result = getsupplierbyserialid($serialid)
1975 this function is used to find the supplier id given a serial id
1978 hashref containing serialid, subscriptionid, and aqbooksellerid
1982 sub getsupplierbyserialid {
1983 my ($serialid) = @_;
1984 my $dbh = C4::Context->dbh;
1985 my $sth = $dbh->prepare(
1986 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1988 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1992 $sth->execute($serialid);
1993 my $line = $sth->fetchrow_hashref;
1994 my $result = $line->{'aqbooksellerid'};
1998 =head2 check_routing
2000 $result = &check_routing($subscriptionid)
2002 this function checks to see if a serial has a routing list and returns the count of routingid
2003 used to show either an 'add' or 'edit' link
2008 my ($subscriptionid) = @_;
2009 my $dbh = C4::Context->dbh;
2010 my $sth = $dbh->prepare(
2011 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
2012 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2013 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2016 $sth->execute($subscriptionid);
2017 my $line = $sth->fetchrow_hashref;
2018 my $result = $line->{'routingids'};
2022 =head2 addroutingmember
2024 addroutingmember($borrowernumber,$subscriptionid)
2026 this function takes a borrowernumber and subscriptionid and adds the member to the
2027 routing list for that serial subscription and gives them a rank on the list
2028 of either 1 or highest current rank + 1
2032 sub addroutingmember {
2033 my ( $borrowernumber, $subscriptionid ) = @_;
2035 my $dbh = C4::Context->dbh;
2036 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
2037 $sth->execute($subscriptionid);
2038 while ( my $line = $sth->fetchrow_hashref ) {
2039 if ( $line->{'rank'} > 0 ) {
2040 $rank = $line->{'rank'} + 1;
2045 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
2046 $sth->execute( $subscriptionid, $borrowernumber, $rank );
2049 =head2 reorder_members
2051 reorder_members($subscriptionid,$routingid,$rank)
2053 this function is used to reorder the routing list
2055 it takes the routingid of the member one wants to re-rank and the rank it is to move to
2056 - it gets all members on list puts their routingid's into an array
2057 - removes the one in the array that is $routingid
2058 - then reinjects $routingid at point indicated by $rank
2059 - then update the database with the routingids in the new order
2063 sub reorder_members {
2064 my ( $subscriptionid, $routingid, $rank ) = @_;
2065 my $dbh = C4::Context->dbh;
2066 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
2067 $sth->execute($subscriptionid);
2069 while ( my $line = $sth->fetchrow_hashref ) {
2070 push( @result, $line->{'routingid'} );
2073 # To find the matching index
2075 my $key = -1; # to allow for 0 being a valid response
2076 for ( $i = 0 ; $i < @result ; $i++ ) {
2077 if ( $routingid == $result[$i] ) {
2078 $key = $i; # save the index
2083 # if index exists in array then move it to new position
2084 if ( $key > -1 && $rank > 0 ) {
2085 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
2086 my $moving_item = splice( @result, $key, 1 );
2087 splice( @result, $new_rank, 0, $moving_item );
2089 for ( my $j = 0 ; $j < @result ; $j++ ) {
2090 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
2096 =head2 delroutingmember
2098 delroutingmember($routingid,$subscriptionid)
2100 this function either deletes one member from routing list if $routingid exists otherwise
2101 deletes all members from the routing list
2105 sub delroutingmember {
2107 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2108 my ( $routingid, $subscriptionid ) = @_;
2109 my $dbh = C4::Context->dbh;
2111 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2112 $sth->execute($routingid);
2113 reorder_members( $subscriptionid, $routingid );
2115 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2116 $sth->execute($subscriptionid);
2121 =head2 getroutinglist
2123 @routinglist = getroutinglist($subscriptionid)
2125 this gets the info from the subscriptionroutinglist for $subscriptionid
2128 the routinglist as an array. Each element of the array contains a hash_ref containing
2129 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2133 sub getroutinglist {
2134 my ($subscriptionid) = @_;
2135 my $dbh = C4::Context->dbh;
2136 my $sth = $dbh->prepare(
2137 'SELECT routingid, borrowernumber, ranking, biblionumber
2139 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2140 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2142 $sth->execute($subscriptionid);
2143 my $routinglist = $sth->fetchall_arrayref({});
2144 return @{$routinglist};
2147 =head2 countissuesfrom
2149 $result = countissuesfrom($subscriptionid,$startdate)
2151 Returns a count of serial rows matching the given subsctiptionid
2152 with published date greater than startdate
2156 sub countissuesfrom {
2157 my ( $subscriptionid, $startdate ) = @_;
2158 my $dbh = C4::Context->dbh;
2162 WHERE subscriptionid=?
2163 AND serial.publisheddate>?
2165 my $sth = $dbh->prepare($query);
2166 $sth->execute( $subscriptionid, $startdate );
2167 my ($countreceived) = $sth->fetchrow;
2168 return $countreceived;
2173 $result = CountIssues($subscriptionid)
2175 Returns a count of serial rows matching the given subsctiptionid
2180 my ($subscriptionid) = @_;
2181 my $dbh = C4::Context->dbh;
2185 WHERE subscriptionid=?
2187 my $sth = $dbh->prepare($query);
2188 $sth->execute($subscriptionid);
2189 my ($countreceived) = $sth->fetchrow;
2190 return $countreceived;
2195 $result = HasItems($subscriptionid)
2197 returns a count of items from serial matching the subscriptionid
2202 my ($subscriptionid) = @_;
2203 my $dbh = C4::Context->dbh;
2205 SELECT COUNT(serialitems.itemnumber)
2207 LEFT JOIN serialitems USING(serialid)
2208 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2210 my $sth=$dbh->prepare($query);
2211 $sth->execute($subscriptionid);
2212 my ($countitems)=$sth->fetchrow_array();
2216 =head2 abouttoexpire
2218 $result = abouttoexpire($subscriptionid)
2220 this function alerts you to the penultimate issue for a serial subscription
2222 returns 1 - if this is the penultimate issue
2228 my ($subscriptionid) = @_;
2229 my $dbh = C4::Context->dbh;
2230 my $subscription = GetSubscription($subscriptionid);
2231 my $per = $subscription->{'periodicity'};
2232 if ($per && $per % 16 > 0){
2233 my $expirationdate = GetExpirationDate($subscriptionid);
2234 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2237 @res=split (/-/,$res);
2238 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2239 } else { # default an undefined value
2240 @res=Date::Calc::Today;
2242 my @endofsubscriptiondate=split(/-/,$expirationdate);
2243 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2245 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2246 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2247 return 1 if ( @res &&
2249 Delta_Days($res[0],$res[1],$res[2],
2250 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2251 (@endofsubscriptiondate &&
2252 Delta_Days($res[0],$res[1],$res[2],
2253 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2255 } elsif ($subscription->{numberlength}>0) {
2256 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2261 sub in_array { # used in next sub down
2262 my ( $val, @elements ) = @_;
2263 foreach my $elem (@elements) {
2264 if ( $val == $elem ) {
2271 =head2 GetSubscriptionsFromBorrower
2273 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2275 this gets the info from subscriptionroutinglist for each $subscriptionid
2278 a count of the serial subscription routing lists to which a patron belongs,
2279 with the titles of those serial subscriptions as an array. Each element of the array
2280 contains a hash_ref with subscriptionID and title of subscription.
2284 sub GetSubscriptionsFromBorrower {
2285 my ($borrowernumber) = @_;
2286 my $dbh = C4::Context->dbh;
2287 my $sth = $dbh->prepare(
2288 "SELECT subscription.subscriptionid, biblio.title
2290 JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2291 JOIN subscriptionroutinglist USING (subscriptionid)
2292 WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2295 $sth->execute($borrowernumber);
2298 while ( my $line = $sth->fetchrow_hashref ) {
2300 push( @routinglist, $line );
2302 return ( $count, @routinglist );
2307 $resultdate = GetNextDate($planneddate,$subscription)
2309 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2310 exists an irregularity
2311 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2312 skipped then the returned date will be 2007-05-10
2315 $resultdate - then next date in the sequence
2317 Return 0 if periodicity==0
2322 my ( $planneddate, $subscription ) = @_;
2323 my @irreg = split( /\,/, $subscription->{irregularity} );
2325 #date supposed to be in ISO.
2327 my ( $year, $month, $day ) = split( /-/, $planneddate );
2328 $month = 1 unless ($month);
2329 $day = 1 unless ($day);
2332 # warn "DOW $dayofweek";
2333 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2338 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2339 # renaming this pattern from 1/day to " n / week ".
2340 if ( $subscription->{periodicity} == 1 ) {
2341 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2342 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2344 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2345 $dayofweek = 0 if ( $dayofweek == 7 );
2346 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2347 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2351 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2356 if ( $subscription->{periodicity} == 2 ) {
2357 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2358 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2360 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2362 #FIXME: if two consecutive irreg, do we only skip one?
2363 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2364 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2365 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2368 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2373 if ( $subscription->{periodicity} == 3 ) {
2374 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2375 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2377 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2378 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2379 ### BUGFIX was previously +1 ^
2380 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2381 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2384 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2389 if ( $subscription->{periodicity} == 4 ) {
2390 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2391 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2393 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2394 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2395 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2396 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2399 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2402 my $tmpmonth = $month;
2403 if ( $year && $month && $day ) {
2404 if ( $subscription->{periodicity} == 5 ) {
2405 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2406 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2407 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2408 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2411 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2413 if ( $subscription->{periodicity} == 6 ) {
2414 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2415 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2416 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2417 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2420 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2422 if ( $subscription->{periodicity} == 7 ) {
2423 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2424 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2425 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2426 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2429 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2431 if ( $subscription->{periodicity} == 8 ) {
2432 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2433 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2434 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2435 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2438 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2440 if ( $subscription->{periodicity} == 13 ) {
2441 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2442 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2443 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2444 $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2447 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2449 if ( $subscription->{periodicity} == 9 ) {
2450 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2451 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2452 ### BUFIX Seems to need more Than One ?
2453 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2454 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2457 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2459 if ( $subscription->{periodicity} == 10 ) {
2460 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2462 if ( $subscription->{periodicity} == 11 ) {
2463 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2466 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2468 return "$resultdate";
2471 =head2 is_barcode_in_use
2473 Returns number of occurence of the barcode in the items table
2474 Can be used as a boolean test of whether the barcode has
2475 been deployed as yet
2479 sub is_barcode_in_use {
2480 my $barcode = shift;
2481 my $dbh = C4::Context->dbh;
2482 my $occurences = $dbh->selectall_arrayref(
2483 'SELECT itemnumber from items where barcode = ?',
2488 return @{$occurences};
2491 =head2 CloseSubscription
2492 Close a subscription given a subscriptionid
2494 sub CloseSubscription {
2495 my ( $subscriptionid ) = @_;
2496 return unless $subscriptionid;
2497 my $dbh = C4::Context->dbh;
2498 my $sth = $dbh->prepare( qq{
2501 WHERE subscriptionid = ?
2503 $sth->execute( $subscriptionid );
2505 # Set status = missing when status = stopped
2506 $sth = $dbh->prepare( qq{
2509 WHERE subscriptionid = ?
2512 $sth->execute( $subscriptionid );
2515 =head2 ReopenSubscription
2516 Reopen a subscription given a subscriptionid
2518 sub ReopenSubscription {
2519 my ( $subscriptionid ) = @_;
2520 return unless $subscriptionid;
2521 my $dbh = C4::Context->dbh;
2522 my $sth = $dbh->prepare( qq{
2525 WHERE subscriptionid = ?
2527 $sth->execute( $subscriptionid );
2529 # Set status = expected when status = stopped
2530 $sth = $dbh->prepare( qq{
2533 WHERE subscriptionid = ?
2536 $sth->execute( $subscriptionid );
2539 =head2 subscriptionCurrentlyOnOrder
2541 $bool = subscriptionCurrentlyOnOrder( $subscriptionid );
2543 Return 1 if subscription is currently on order else 0.
2547 sub subscriptionCurrentlyOnOrder {
2548 my ( $subscriptionid ) = @_;
2549 my $dbh = C4::Context->dbh;
2551 SELECT COUNT(*) FROM aqorders
2552 WHERE subscriptionid = ?
2553 AND datereceived IS NULL
2554 AND datecancellationprinted IS NULL
2556 my $sth = $dbh->prepare( $query );
2557 $sth->execute($subscriptionid);
2558 return $sth->fetchrow_array;
2566 Koha Development Team <http://koha-community.org/>