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
64 C4::Serials - Serials Module Functions
72 Functions for handling subscriptions, claims routing etc.
77 =head2 GetSuppliersWithLateIssues
79 $supplierlist = GetSuppliersWithLateIssues()
81 this function get all suppliers with late issues.
84 an array_ref of suppliers each entry is a hash_ref containing id and name
85 the array is in name order
89 sub GetSuppliersWithLateIssues {
90 my $dbh = C4::Context->dbh;
92 SELECT DISTINCT id, name
94 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
95 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
98 (planneddate < now() AND serial.status=1)
99 OR serial.STATUS = 3 OR serial.STATUS = 4
101 AND subscription.closed = 0
103 return $dbh->selectall_arrayref($query, { Slice => {} });
108 @issuelist = GetLateIssues($supplierid)
110 this function selects late issues from the database
113 the issuelist as an array. Each element of this array contains a hashi_ref containing
114 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
119 my ($supplierid) = @_;
120 my $dbh = C4::Context->dbh;
124 SELECT name,title,planneddate,serialseq,serial.subscriptionid
126 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
127 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
128 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
129 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
130 AND subscription.aqbooksellerid=?
131 AND subscription.closed = 0
134 $sth = $dbh->prepare($query);
135 $sth->execute($supplierid);
138 SELECT name,title,planneddate,serialseq,serial.subscriptionid
140 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
141 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
142 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
143 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
144 AND subscription.closed = 0
147 $sth = $dbh->prepare($query);
153 while ( my $line = $sth->fetchrow_hashref ) {
154 $odd++ unless $line->{title} eq $last_title;
155 $line->{title} = "" if $line->{title} eq $last_title;
156 $last_title = $line->{title} if ( $line->{title} );
157 $line->{planneddate} = format_date( $line->{planneddate} );
158 push @issuelist, $line;
163 =head2 GetSubscriptionHistoryFromSubscriptionId
165 $sth = GetSubscriptionHistoryFromSubscriptionId()
166 this function prepares the SQL request and returns the statement handle
167 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
171 sub GetSubscriptionHistoryFromSubscriptionId {
172 my $dbh = C4::Context->dbh;
175 FROM subscriptionhistory
176 WHERE subscriptionid = ?
178 return $dbh->prepare($query);
181 =head2 GetSerialStatusFromSerialId
183 $sth = GetSerialStatusFromSerialId();
184 this function returns a statement handle
185 After this function, don't forget to execute it by using $sth->execute($serialid)
187 $sth = $dbh->prepare($query).
191 sub GetSerialStatusFromSerialId {
192 my $dbh = C4::Context->dbh;
198 return $dbh->prepare($query);
201 =head2 GetSerialInformation
204 $data = GetSerialInformation($serialid);
205 returns a hash_ref containing :
206 items : items marcrecord (can be an array)
208 subscription table field
209 + information about subscription expiration
213 sub GetSerialInformation {
215 my $dbh = C4::Context->dbh;
217 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
218 if ( C4::Context->preference('IndependantBranches')
219 && C4::Context->userenv
220 && C4::Context->userenv->{'flags'} != 1
221 && C4::Context->userenv->{'branch'} ) {
223 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
226 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
229 my $rq = $dbh->prepare($query);
230 $rq->execute($serialid);
231 my $data = $rq->fetchrow_hashref;
233 # create item information if we have serialsadditems for this subscription
234 if ( $data->{'serialsadditems'} ) {
235 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
236 $queryitem->execute($serialid);
237 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
239 if ( scalar(@$itemnumbers) > 0 ) {
240 foreach my $itemnum (@$itemnumbers) {
242 #It is ASSUMED that GetMarcItem ALWAYS WORK...
243 #Maybe GetMarcItem should return values on failure
244 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
245 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
246 $itemprocessed->{'itemnumber'} = $itemnum->[0];
247 $itemprocessed->{'itemid'} = $itemnum->[0];
248 $itemprocessed->{'serialid'} = $serialid;
249 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
250 push @{ $data->{'items'} }, $itemprocessed;
253 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
254 $itemprocessed->{'itemid'} = "N$serialid";
255 $itemprocessed->{'serialid'} = $serialid;
256 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
257 $itemprocessed->{'countitems'} = 0;
258 push @{ $data->{'items'} }, $itemprocessed;
261 $data->{ "status" . $data->{'serstatus'} } = 1;
262 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
263 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
267 =head2 AddItem2Serial
269 $rows = AddItem2Serial($serialid,$itemnumber);
270 Adds an itemnumber to Serial record
271 returns the number of rows affected
276 my ( $serialid, $itemnumber ) = @_;
277 my $dbh = C4::Context->dbh;
278 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
279 $rq->execute( $serialid, $itemnumber );
283 =head2 UpdateClaimdateIssues
285 UpdateClaimdateIssues($serialids,[$date]);
287 Update Claimdate for issues in @$serialids list with date $date
292 sub UpdateClaimdateIssues {
293 my ( $serialids, $date ) = @_;
294 my $dbh = C4::Context->dbh;
295 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
297 UPDATE serial SET claimdate = ?, status = 7
298 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
299 my $rq = $dbh->prepare($query);
300 $rq->execute($date, @$serialids);
304 =head2 GetSubscription
306 $subs = GetSubscription($subscriptionid)
307 this function returns the subscription which has $subscriptionid as id.
309 a hashref. This hash containts
310 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
314 sub GetSubscription {
315 my ($subscriptionid) = @_;
316 my $dbh = C4::Context->dbh;
318 SELECT subscription.*,
319 subscriptionhistory.*,
320 aqbooksellers.name AS aqbooksellername,
321 biblio.title AS bibliotitle,
322 subscription.biblionumber as bibnum);
323 if ( C4::Context->preference('IndependantBranches')
324 && C4::Context->userenv
325 && C4::Context->userenv->{'flags'} != 1
326 && C4::Context->userenv->{'branch'} ) {
328 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
332 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
333 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
334 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
335 WHERE subscription.subscriptionid = ?
338 # if (C4::Context->preference('IndependantBranches') &&
339 # C4::Context->userenv &&
340 # C4::Context->userenv->{'flags'} != 1){
341 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
342 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
344 $debug and warn "query : $query\nsubsid :$subscriptionid";
345 my $sth = $dbh->prepare($query);
346 $sth->execute($subscriptionid);
347 return $sth->fetchrow_hashref;
350 =head2 GetFullSubscription
352 $array_ref = GetFullSubscription($subscriptionid)
353 this function reads the serial table.
357 sub GetFullSubscription {
358 my ($subscriptionid) = @_;
359 my $dbh = C4::Context->dbh;
361 SELECT serial.serialid,
364 serial.publisheddate,
366 serial.notes as notes,
367 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
368 aqbooksellers.name as aqbooksellername,
369 biblio.title as bibliotitle,
370 subscription.branchcode AS branchcode,
371 subscription.subscriptionid AS subscriptionid |;
372 if ( C4::Context->preference('IndependantBranches')
373 && C4::Context->userenv
374 && C4::Context->userenv->{'flags'} != 1
375 && C4::Context->userenv->{'branch'} ) {
377 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
381 LEFT JOIN subscription ON
382 (serial.subscriptionid=subscription.subscriptionid )
383 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
384 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
385 WHERE serial.subscriptionid = ?
387 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
388 serial.subscriptionid
390 $debug and warn "GetFullSubscription query: $query";
391 my $sth = $dbh->prepare($query);
392 $sth->execute($subscriptionid);
393 return $sth->fetchall_arrayref( {} );
396 =head2 PrepareSerialsData
398 $array_ref = PrepareSerialsData($serialinfomation)
399 where serialinformation is a hashref array
403 sub PrepareSerialsData {
409 my $aqbooksellername;
413 my $previousnote = "";
415 foreach my $subs (@{$lines}) {
416 for my $datefield ( qw(publisheddate planneddate) ) {
417 # handle both undef and undef returned as 0000-00-00
418 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
419 $subs->{$datefield} = 'XXX';
422 $subs->{$datefield} = format_date( $subs->{$datefield} );
425 $subs->{ "status" . $subs->{'status'} } = 1;
426 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
428 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
429 $year = $subs->{'year'};
433 if ( $tmpresults{$year} ) {
434 push @{ $tmpresults{$year}->{'serials'} }, $subs;
436 $tmpresults{$year} = {
438 'aqbooksellername' => $subs->{'aqbooksellername'},
439 'bibliotitle' => $subs->{'bibliotitle'},
440 'serials' => [$subs],
445 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
446 push @res, $tmpresults{$key};
451 =head2 GetSubscriptionsFromBiblionumber
453 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
454 this function get the subscription list. it reads the subscription table.
456 reference to an array of subscriptions which have the biblionumber given on input arg.
457 each element of this array is a hashref containing
458 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
462 sub GetSubscriptionsFromBiblionumber {
463 my ($biblionumber) = @_;
464 my $dbh = C4::Context->dbh;
466 SELECT subscription.*,
468 subscriptionhistory.*,
469 aqbooksellers.name AS aqbooksellername,
470 biblio.title AS bibliotitle
472 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
473 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
474 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
475 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
476 WHERE subscription.biblionumber = ?
478 my $sth = $dbh->prepare($query);
479 $sth->execute($biblionumber);
481 while ( my $subs = $sth->fetchrow_hashref ) {
482 $subs->{startdate} = format_date( $subs->{startdate} );
483 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
484 $subs->{histenddate} = format_date( $subs->{histenddate} );
485 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
486 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
487 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
488 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
489 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
490 $subs->{ "status" . $subs->{'status'} } = 1;
491 $subs->{'cannotedit'} =
492 ( C4::Context->preference('IndependantBranches')
493 && C4::Context->userenv
494 && C4::Context->userenv->{flags} % 2 != 1
495 && C4::Context->userenv->{branch}
496 && $subs->{branchcode}
497 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
499 if ( $subs->{enddate} eq '0000-00-00' ) {
500 $subs->{enddate} = '';
502 $subs->{enddate} = format_date( $subs->{enddate} );
504 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
505 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
511 =head2 GetFullSubscriptionsFromBiblionumber
513 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
514 this function reads the serial table.
518 sub GetFullSubscriptionsFromBiblionumber {
519 my ($biblionumber) = @_;
520 my $dbh = C4::Context->dbh;
522 SELECT serial.serialid,
525 serial.publisheddate,
527 serial.notes as notes,
528 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
529 biblio.title as bibliotitle,
530 subscription.branchcode AS branchcode,
531 subscription.subscriptionid AS subscriptionid|;
532 if ( C4::Context->preference('IndependantBranches')
533 && C4::Context->userenv
534 && C4::Context->userenv->{'flags'} != 1
535 && C4::Context->userenv->{'branch'} ) {
537 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
542 LEFT JOIN subscription ON
543 (serial.subscriptionid=subscription.subscriptionid)
544 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
545 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
546 WHERE subscription.biblionumber = ?
548 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
549 serial.subscriptionid
551 my $sth = $dbh->prepare($query);
552 $sth->execute($biblionumber);
553 return $sth->fetchall_arrayref( {} );
556 =head2 GetSubscriptions
558 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
559 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
561 a table of hashref. Each hash containt the subscription.
565 sub GetSubscriptions {
566 my ( $string, $issn, $ean, $biblionumber ) = @_;
568 #return unless $title or $ISSN or $biblionumber;
569 my $dbh = C4::Context->dbh;
572 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
574 LEFT JOIN subscriptionhistory USING(subscriptionid)
575 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
576 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
581 $sqlwhere = " WHERE biblio.biblionumber=?";
582 push @bind_params, $biblionumber;
586 my @strings_to_search;
587 @strings_to_search = map { "%$_%" } split( / /, $string );
588 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
589 push @bind_params, @strings_to_search;
590 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
591 $debug && warn "$tmpstring";
592 $tmpstring =~ s/^AND //;
593 push @sqlstrings, $tmpstring;
595 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
599 my @strings_to_search;
600 @strings_to_search = map { "%$_%" } split( / /, $issn );
601 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
602 push @bind_params, @strings_to_search;
603 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
604 $debug && warn "$tmpstring";
605 $tmpstring =~ s/^OR //;
606 push @sqlstrings, $tmpstring;
608 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
612 my @strings_to_search;
613 @strings_to_search = map { "$_" } split( / /, $ean );
614 foreach my $index ( qw(biblioitems.ean) ) {
615 push @bind_params, @strings_to_search;
616 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
617 $debug && warn "$tmpstring";
618 $tmpstring =~ s/^OR //;
619 push @sqlstrings, $tmpstring;
621 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
624 $sql .= "$sqlwhere ORDER BY title";
625 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
626 $sth = $dbh->prepare($sql);
627 $sth->execute(@bind_params);
630 while ( my $line = $sth->fetchrow_hashref ) {
631 $line->{'cannotedit'} =
632 ( C4::Context->preference('IndependantBranches')
633 && C4::Context->userenv
634 && C4::Context->userenv->{flags} % 2 != 1
635 && C4::Context->userenv->{branch}
636 && $line->{branchcode}
637 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
638 push @results, $line;
643 =head2 SearchSubscriptions
645 @results = SearchSubscriptions($args);
646 $args is a hashref. Its keys can be contained: title, issn, ean, publisher, bookseller and branchcode
648 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.
651 a table of hashref. Each hash containt the subscription.
655 sub SearchSubscriptions {
659 SELECT subscription.*, subscriptionhistory.*, biblio.*, biblioitems.issn
661 LEFT JOIN subscriptionhistory USING(subscriptionid)
662 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
663 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
664 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
668 if( $args->{biblionumber} ) {
669 push @where_strs, "biblio.biblionumber = ?";
670 push @where_args, $args->{biblionumber};
672 if( $args->{title} ){
673 my @words = split / /, $args->{title};
675 foreach my $word (@words) {
676 push @strs, "biblio.title LIKE ?";
677 push @args, "%$word%";
680 push @where_strs, '(' . join (' AND ', @strs) . ')';
681 push @where_args, @args;
685 push @where_strs, "biblioitems.issn LIKE ?";
686 push @where_args, "%$args->{issn}%";
689 push @where_strs, "biblioitems.ean LIKE ?";
690 push @where_args, "%$args->{ean}%";
692 if( $args->{publisher} ){
693 push @where_strs, "biblioitems.publishercode LIKE ?";
694 push @where_args, "%$args->{publisher}%";
696 if( $args->{bookseller} ){
697 push @where_strs, "aqbooksellers.name LIKE ?";
698 push @where_args, "%$args->{bookseller}%";
700 if( $args->{branch} ){
701 push @where_strs, "subscription.branchcode = ?";
702 push @where_args, "$args->{branch}";
704 if( defined $args->{closed} ){
705 push @where_strs, "subscription.closed = ?";
706 push @where_args, "$args->{closed}";
709 $query .= " WHERE " . join(" AND ", @where_strs);
712 my $dbh = C4::Context->dbh;
713 my $sth = $dbh->prepare($query);
714 $sth->execute(@where_args);
715 my $results = $sth->fetchall_arrayref( {} );
724 ($totalissues,@serials) = GetSerials($subscriptionid);
725 this function gets every serial not arrived for a given subscription
726 as well as the number of issues registered in the database (all types)
727 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
729 FIXME: We should return \@serials.
734 my ( $subscriptionid, $count ) = @_;
735 my $dbh = C4::Context->dbh;
737 # status = 2 is "arrived"
739 $count = 5 unless ($count);
741 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
743 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
744 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
745 my $sth = $dbh->prepare($query);
746 $sth->execute($subscriptionid);
748 while ( my $line = $sth->fetchrow_hashref ) {
749 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
750 for my $datefield ( qw( planneddate publisheddate) ) {
751 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
752 $line->{$datefield} = format_date( $line->{$datefield});
754 $line->{$datefield} = q{};
757 push @serials, $line;
760 # OK, now add the last 5 issues arrives/missing
761 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
763 WHERE subscriptionid = ?
764 AND (status in (2,4,5))
765 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
767 $sth = $dbh->prepare($query);
768 $sth->execute($subscriptionid);
769 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
771 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
772 for my $datefield ( qw( planneddate publisheddate) ) {
773 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
774 $line->{$datefield} = format_date( $line->{$datefield});
776 $line->{$datefield} = q{};
780 push @serials, $line;
783 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
784 $sth = $dbh->prepare($query);
785 $sth->execute($subscriptionid);
786 my ($totalissues) = $sth->fetchrow;
787 return ( $totalissues, @serials );
792 @serials = GetSerials2($subscriptionid,$status);
793 this function returns every serial waited for a given subscription
794 as well as the number of issues registered in the database (all types)
795 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
800 my ( $subscription, $status ) = @_;
801 my $dbh = C4::Context->dbh;
803 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
805 WHERE subscriptionid=$subscription AND status IN ($status)
806 ORDER BY publisheddate,serialid DESC
808 $debug and warn "GetSerials2 query: $query";
809 my $sth = $dbh->prepare($query);
813 while ( my $line = $sth->fetchrow_hashref ) {
814 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
815 # Format dates for display
816 for my $datefield ( qw( planneddate publisheddate ) ) {
817 if ($line->{$datefield} =~m/^00/) {
818 $line->{$datefield} = q{};
821 $line->{$datefield} = format_date( $line->{$datefield} );
824 push @serials, $line;
829 =head2 GetLatestSerials
831 \@serials = GetLatestSerials($subscriptionid,$limit)
832 get the $limit's latest serials arrived or missing for a given subscription
834 a ref to an array which contains all of the latest serials stored into a hash.
838 sub GetLatestSerials {
839 my ( $subscriptionid, $limit ) = @_;
840 my $dbh = C4::Context->dbh;
842 # status = 2 is "arrived"
843 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
845 WHERE subscriptionid = ?
846 AND (status =2 or status=4)
847 ORDER BY publisheddate DESC LIMIT 0,$limit
849 my $sth = $dbh->prepare($strsth);
850 $sth->execute($subscriptionid);
852 while ( my $line = $sth->fetchrow_hashref ) {
853 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
854 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
855 push @serials, $line;
861 =head2 GetDistributedTo
863 $distributedto=GetDistributedTo($subscriptionid)
864 This function returns the field distributedto for the subscription matching subscriptionid
868 sub GetDistributedTo {
869 my $dbh = C4::Context->dbh;
871 my $subscriptionid = @_;
872 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
873 my $sth = $dbh->prepare($query);
874 $sth->execute($subscriptionid);
875 return ($distributedto) = $sth->fetchrow;
881 $val is a hashref containing all the attributes of the table 'subscription'
882 This function get the next issue for the subscription given on input arg
884 a list containing all the input params updated.
890 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
891 # $calculated = $val->{numberingmethod};
892 # # calculate the (expected) value of the next issue recieved.
893 # $newlastvalue1 = $val->{lastvalue1};
894 # # check if we have to increase the new value.
895 # $newinnerloop1 = $val->{innerloop1}+1;
896 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
897 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
898 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
899 # $calculated =~ s/\{X\}/$newlastvalue1/g;
901 # $newlastvalue2 = $val->{lastvalue2};
902 # # check if we have to increase the new value.
903 # $newinnerloop2 = $val->{innerloop2}+1;
904 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
905 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
906 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
907 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
909 # $newlastvalue3 = $val->{lastvalue3};
910 # # check if we have to increase the new value.
911 # $newinnerloop3 = $val->{innerloop3}+1;
912 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
913 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
914 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
915 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
916 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
921 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
922 my $pattern = $val->{numberpattern};
923 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
924 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
925 $calculated = $val->{numberingmethod};
926 $newlastvalue1 = $val->{lastvalue1};
927 $newlastvalue2 = $val->{lastvalue2};
928 $newlastvalue3 = $val->{lastvalue3};
929 $newlastvalue1 = $val->{lastvalue1};
931 # check if we have to increase the new value.
932 $newinnerloop1 = $val->{innerloop1} + 1;
933 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
934 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
935 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
936 $calculated =~ s/\{X\}/$newlastvalue1/g;
938 $newlastvalue2 = $val->{lastvalue2};
940 # check if we have to increase the new value.
941 $newinnerloop2 = $val->{innerloop2} + 1;
942 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
943 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
944 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
945 if ( $pattern == 6 ) {
946 if ( $val->{hemisphere} == 2 ) {
947 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
948 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
950 my $newlastvalue2seq = $seasons[$newlastvalue2];
951 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
954 $calculated =~ s/\{Y\}/$newlastvalue2/g;
957 $newlastvalue3 = $val->{lastvalue3};
959 # check if we have to increase the new value.
960 $newinnerloop3 = $val->{innerloop3} + 1;
961 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
962 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
963 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
964 $calculated =~ s/\{Z\}/$newlastvalue3/g;
966 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
971 $calculated = GetSeq($val)
972 $val is a hashref containing all the attributes of the table 'subscription'
973 this function transforms {X},{Y},{Z} to 150,0,0 for example.
975 the sequence in integer format
981 my $pattern = $val->{numberpattern};
982 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
983 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
984 my $calculated = $val->{numberingmethod};
985 my $x = $val->{'lastvalue1'};
986 $calculated =~ s/\{X\}/$x/g;
987 my $newlastvalue2 = $val->{'lastvalue2'};
989 if ( $pattern == 6 ) {
990 if ( $val->{hemisphere} == 2 ) {
991 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
992 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
994 my $newlastvalue2seq = $seasons[$newlastvalue2];
995 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
998 $calculated =~ s/\{Y\}/$newlastvalue2/g;
1000 my $z = $val->{'lastvalue3'};
1001 $calculated =~ s/\{Z\}/$z/g;
1005 =head2 GetExpirationDate
1007 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1009 this function return the next expiration date for a subscription given on input args.
1012 the enddate or undef
1016 sub GetExpirationDate {
1017 my ( $subscriptionid, $startdate ) = @_;
1018 my $dbh = C4::Context->dbh;
1019 my $subscription = GetSubscription($subscriptionid);
1022 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1023 $enddate = $startdate || $subscription->{startdate};
1024 my @date = split( /-/, $enddate );
1025 return if ( scalar(@date) != 3 || not check_date(@date) );
1026 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1029 if ( my $length = $subscription->{numberlength} ) {
1031 #calculate the date of the last issue.
1032 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1033 $enddate = GetNextDate( $enddate, $subscription );
1035 } elsif ( $subscription->{monthlength} ) {
1036 if ( $$subscription{startdate} ) {
1037 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1038 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1040 } elsif ( $subscription->{weeklength} ) {
1041 if ( $$subscription{startdate} ) {
1042 my @date = split( /-/, $subscription->{startdate} );
1043 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1044 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1053 =head2 CountSubscriptionFromBiblionumber
1055 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1056 this returns a count of the subscriptions for a given biblionumber
1058 the number of subscriptions
1062 sub CountSubscriptionFromBiblionumber {
1063 my ($biblionumber) = @_;
1064 my $dbh = C4::Context->dbh;
1065 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1066 my $sth = $dbh->prepare($query);
1067 $sth->execute($biblionumber);
1068 my $subscriptionsnumber = $sth->fetchrow;
1069 return $subscriptionsnumber;
1072 =head2 ModSubscriptionHistory
1074 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1076 this function modifies the history of a subscription. Put your new values on input arg.
1077 returns the number of rows affected
1081 sub ModSubscriptionHistory {
1082 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
1083 my $dbh = C4::Context->dbh;
1084 my $query = "UPDATE subscriptionhistory
1085 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1086 WHERE subscriptionid=?
1088 my $sth = $dbh->prepare($query);
1089 $recievedlist =~ s/^; //;
1090 $missinglist =~ s/^; //;
1091 $opacnote =~ s/^; //;
1092 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1096 =head2 ModSerialStatus
1098 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1100 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1101 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1105 sub ModSerialStatus {
1106 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1108 #It is a usual serial
1109 # 1st, get previous status :
1110 my $dbh = C4::Context->dbh;
1111 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1112 my $sth = $dbh->prepare($query);
1113 $sth->execute($serialid);
1114 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1116 # change status & update subscriptionhistory
1118 if ( $status == 6 ) {
1119 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1123 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1124 $sth = $dbh->prepare($query);
1125 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1126 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1127 $sth = $dbh->prepare($query);
1128 $sth->execute($subscriptionid);
1129 my $val = $sth->fetchrow_hashref;
1130 unless ( $val->{manualhistory} ) {
1131 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1132 $sth = $dbh->prepare($query);
1133 $sth->execute($subscriptionid);
1134 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1135 if ( $status == 2 ) {
1137 $recievedlist .= "; $serialseq"
1138 unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1141 # warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1142 $missinglist .= "; $serialseq"
1144 and not index( "$missinglist", "$serialseq" ) >= 0 );
1145 $missinglist .= "; not issued $serialseq"
1147 and index( "$missinglist", "$serialseq" ) >= 0 );
1148 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1149 $sth = $dbh->prepare($query);
1150 $recievedlist =~ s/^; //;
1151 $missinglist =~ s/^; //;
1152 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1156 # create new waited entry if needed (ie : was a "waited" and has changed)
1157 if ( $oldstatus == 1 && $status != 1 ) {
1158 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1159 $sth = $dbh->prepare($query);
1160 $sth->execute($subscriptionid);
1161 my $val = $sth->fetchrow_hashref;
1165 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1166 $newinnerloop1, $newinnerloop2, $newinnerloop3
1167 ) = GetNextSeq($val);
1169 # next date (calculated from actual date & frequency parameters)
1170 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1171 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1172 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1173 WHERE subscriptionid = ?";
1174 $sth = $dbh->prepare($query);
1175 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1177 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1178 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1179 require C4::Letters;
1180 C4::Letters::SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1186 =head2 GetNextExpected
1188 $nextexpected = GetNextExpected($subscriptionid)
1190 Get the planneddate for the current expected issue of the subscription.
1196 planneddate => C4::Dates object
1201 sub GetNextExpected {
1202 my ($subscriptionid) = @_;
1203 my $dbh = C4::Context->dbh;
1204 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1206 # Each subscription has only one 'expected' issue, with serial.status==1.
1207 $sth->execute( $subscriptionid, 1 );
1208 my ( $nextissue ) = $sth->fetchrow_hashref;
1210 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1211 $sth->execute( $subscriptionid );
1212 $nextissue = $sth->fetchrow_hashref;
1214 if (!defined $nextissue->{planneddate}) {
1215 # or should this default to 1st Jan ???
1216 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1218 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1223 =head2 ModNextExpected
1225 ModNextExpected($subscriptionid,$date)
1227 Update the planneddate for the current expected issue of the subscription.
1228 This will modify all future prediction results.
1230 C<$date> is a C4::Dates object.
1236 sub ModNextExpected {
1237 my ( $subscriptionid, $date ) = @_;
1238 my $dbh = C4::Context->dbh;
1240 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1241 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1243 # Each subscription has only one 'expected' issue, with serial.status==1.
1244 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1249 =head2 ModSubscription
1251 this function modifies a subscription. Put all new values on input args.
1252 returns the number of rows affected
1256 sub ModSubscription {
1257 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1258 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1259 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1260 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1261 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1262 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1265 # warn $irregularity;
1266 my $dbh = C4::Context->dbh;
1267 my $query = "UPDATE subscription
1268 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1269 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1270 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1271 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1272 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1273 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1274 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1275 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1277 WHERE subscriptionid = ?";
1279 #warn "query :".$query;
1280 my $sth = $dbh->prepare($query);
1282 $auser, $branchcode, $aqbooksellerid, $cost,
1283 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1284 $dow, "$irregularity", $numberpattern, $numberlength,
1285 $weeklength, $monthlength, $add1, $every1,
1286 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1287 $add2, $every2, $whenmorethan2, $setto2,
1288 $lastvalue2, $innerloop2, $add3, $every3,
1289 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1290 $numberingmethod, $status, $biblionumber, $callnumber,
1291 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1292 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1293 $graceperiod, $location, $enddate, $subscriptionid
1295 my $rows = $sth->rows;
1297 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1301 =head2 NewSubscription
1303 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1304 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1305 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1306 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1307 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1308 $numberingmethod, $status, $notes, $serialsadditems,
1309 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1311 Create a new subscription with value given on input args.
1314 the id of this new subscription
1318 sub NewSubscription {
1319 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1320 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1321 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1322 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1323 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1324 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1326 my $dbh = C4::Context->dbh;
1328 #save subscription (insert into database)
1330 INSERT INTO subscription
1331 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1332 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1333 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1334 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1335 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1336 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1337 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1338 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1339 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1341 my $sth = $dbh->prepare($query);
1343 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1344 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1345 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1346 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1347 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1348 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1351 my $subscriptionid = $dbh->{'mysql_insertid'};
1353 $enddate = GetExpirationDate($subscriptionid,$startdate);
1357 WHERE subscriptionid=?
1359 $sth = $dbh->prepare($query);
1360 $sth->execute( $enddate, $subscriptionid );
1362 #then create the 1st waited number
1364 INSERT INTO subscriptionhistory
1365 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1368 $sth = $dbh->prepare($query);
1369 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1371 # reread subscription to get a hash (for calculation of the 1st issue number)
1375 WHERE subscriptionid = ?
1377 $sth = $dbh->prepare($query);
1378 $sth->execute($subscriptionid);
1379 my $val = $sth->fetchrow_hashref;
1381 # calculate issue number
1382 my $serialseq = GetSeq($val);
1385 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1386 VALUES (?,?,?,?,?,?)
1388 $sth = $dbh->prepare($query);
1389 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1391 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1393 #set serial flag on biblio if not already set.
1394 my $bib = GetBiblio($biblionumber);
1395 if ( !$bib->{'serial'} ) {
1396 my $record = GetMarcBiblio($biblionumber);
1397 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1399 eval { $record->field($tag)->update( $subf => 1 ); };
1401 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1403 return $subscriptionid;
1406 =head2 ReNewSubscription
1408 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1410 this function renew a subscription with values given on input args.
1414 sub ReNewSubscription {
1415 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1416 my $dbh = C4::Context->dbh;
1417 my $subscription = GetSubscription($subscriptionid);
1421 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1422 WHERE biblio.biblionumber=?
1424 my $sth = $dbh->prepare($query);
1425 $sth->execute( $subscription->{biblionumber} );
1426 my $biblio = $sth->fetchrow_hashref;
1428 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1429 require C4::Suggestions;
1430 C4::Suggestions::NewSuggestion(
1431 { 'suggestedby' => $user,
1432 'title' => $subscription->{bibliotitle},
1433 'author' => $biblio->{author},
1434 'publishercode' => $biblio->{publishercode},
1435 'note' => $biblio->{note},
1436 'biblionumber' => $subscription->{biblionumber}
1441 # renew subscription
1444 SET startdate=?,numberlength=?,weeklength=?,monthlength=?
1445 WHERE subscriptionid=?
1447 $sth = $dbh->prepare($query);
1448 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1449 my $enddate = GetExpirationDate($subscriptionid);
1450 $debug && warn "enddate :$enddate";
1454 WHERE subscriptionid=?
1456 $sth = $dbh->prepare($query);
1457 $sth->execute( $enddate, $subscriptionid );
1459 UPDATE subscriptionhistory
1461 WHERE subscriptionid=?
1463 $sth = $dbh->prepare($query);
1464 $sth->execute( $enddate, $subscriptionid );
1466 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1472 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1474 Create a new issue stored on the database.
1475 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1476 returns the serial id
1481 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1482 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1484 my $dbh = C4::Context->dbh;
1487 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1488 VALUES (?,?,?,?,?,?,?)
1490 my $sth = $dbh->prepare($query);
1491 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1492 my $serialid = $dbh->{'mysql_insertid'};
1494 SELECT missinglist,recievedlist
1495 FROM subscriptionhistory
1496 WHERE subscriptionid=?
1498 $sth = $dbh->prepare($query);
1499 $sth->execute($subscriptionid);
1500 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1502 if ( $status == 2 ) {
1503 ### TODO Add a feature that improves recognition and description.
1504 ### As such count (serialseq) i.e. : N18,2(N19),N20
1505 ### Would use substr and index But be careful to previous presence of ()
1506 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1508 if ( $status == 4 ) {
1509 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1512 UPDATE subscriptionhistory
1513 SET recievedlist=?, missinglist=?
1514 WHERE subscriptionid=?
1516 $sth = $dbh->prepare($query);
1517 $recievedlist =~ s/^; //;
1518 $missinglist =~ s/^; //;
1519 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1523 =head2 ItemizeSerials
1525 ItemizeSerials($serialid, $info);
1526 $info is a hashref containing barcode branch, itemcallnumber, status, location
1527 $serialid the serialid
1529 1 if the itemize is a succes.
1530 0 and @error otherwise. @error containts the list of errors found.
1534 sub ItemizeSerials {
1535 my ( $serialid, $info ) = @_;
1536 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1538 my $dbh = C4::Context->dbh;
1544 my $sth = $dbh->prepare($query);
1545 $sth->execute($serialid);
1546 my $data = $sth->fetchrow_hashref;
1547 if ( C4::Context->preference("RoutingSerials") ) {
1549 # check for existing biblioitem relating to serial issue
1550 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1552 for ( my $i = 0 ; $i < $count ; $i++ ) {
1553 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1554 $bibitemno = $results[$i]->{'biblioitemnumber'};
1558 if ( $bibitemno == 0 ) {
1559 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1560 $sth->execute( $data->{'biblionumber'} );
1561 my $biblioitem = $sth->fetchrow_hashref;
1562 $biblioitem->{'volumedate'} = $data->{planneddate};
1563 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1564 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1568 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1569 if ( $info->{barcode} ) {
1571 if ( is_barcode_in_use( $info->{barcode} ) ) {
1572 push @errors, 'barcode_not_unique';
1574 my $marcrecord = MARC::Record->new();
1575 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1576 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1577 $marcrecord->insert_fields_ordered($newField);
1578 if ( $info->{branch} ) {
1579 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1581 #warn "items.homebranch : $tag , $subfield";
1582 if ( $marcrecord->field($tag) ) {
1583 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1585 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1586 $marcrecord->insert_fields_ordered($newField);
1588 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1590 #warn "items.holdingbranch : $tag , $subfield";
1591 if ( $marcrecord->field($tag) ) {
1592 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1594 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1595 $marcrecord->insert_fields_ordered($newField);
1598 if ( $info->{itemcallnumber} ) {
1599 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1601 if ( $marcrecord->field($tag) ) {
1602 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1604 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1605 $marcrecord->insert_fields_ordered($newField);
1608 if ( $info->{notes} ) {
1609 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1611 if ( $marcrecord->field($tag) ) {
1612 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1614 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1615 $marcrecord->insert_fields_ordered($newField);
1618 if ( $info->{location} ) {
1619 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1621 if ( $marcrecord->field($tag) ) {
1622 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1624 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1625 $marcrecord->insert_fields_ordered($newField);
1628 if ( $info->{status} ) {
1629 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1631 if ( $marcrecord->field($tag) ) {
1632 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1634 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1635 $marcrecord->insert_fields_ordered($newField);
1638 if ( C4::Context->preference("RoutingSerials") ) {
1639 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1640 if ( $marcrecord->field($tag) ) {
1641 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1643 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1644 $marcrecord->insert_fields_ordered($newField);
1648 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1651 return ( 0, @errors );
1655 =head2 HasSubscriptionStrictlyExpired
1657 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1659 the subscription has stricly expired when today > the end subscription date
1662 1 if true, 0 if false, -1 if the expiration date is not set.
1666 sub HasSubscriptionStrictlyExpired {
1668 # Getting end of subscription date
1669 my ($subscriptionid) = @_;
1670 my $dbh = C4::Context->dbh;
1671 my $subscription = GetSubscription($subscriptionid);
1672 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1674 # If the expiration date is set
1675 if ( $expirationdate != 0 ) {
1676 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1678 # Getting today's date
1679 my ( $nowyear, $nowmonth, $nowday ) = Today();
1681 # if today's date > expiration date, then the subscription has stricly expired
1682 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1689 # There are some cases where the expiration date is not set
1690 # As we can't determine if the subscription has expired on a date-basis,
1696 =head2 HasSubscriptionExpired
1698 $has_expired = HasSubscriptionExpired($subscriptionid)
1700 the subscription has expired when the next issue to arrive is out of subscription limit.
1703 0 if the subscription has not expired
1704 1 if the subscription has expired
1705 2 if has subscription does not have a valid expiration date set
1709 sub HasSubscriptionExpired {
1710 my ($subscriptionid) = @_;
1711 my $dbh = C4::Context->dbh;
1712 my $subscription = GetSubscription($subscriptionid);
1713 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1714 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1715 if (!defined $expirationdate) {
1716 $expirationdate = q{};
1719 SELECT max(planneddate)
1721 WHERE subscriptionid=?
1723 my $sth = $dbh->prepare($query);
1724 $sth->execute($subscriptionid);
1725 my ($res) = $sth->fetchrow;
1726 if (!$res || $res=~m/^0000/) {
1729 my @res = split( /-/, $res );
1730 my @endofsubscriptiondate = split( /-/, $expirationdate );
1731 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1733 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1737 if ( $subscription->{'numberlength'} ) {
1738 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1739 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1745 return 0; # Notice that you'll never get here.
1748 =head2 SetDistributedto
1750 SetDistributedto($distributedto,$subscriptionid);
1751 This function update the value of distributedto for a subscription given on input arg.
1755 sub SetDistributedto {
1756 my ( $distributedto, $subscriptionid ) = @_;
1757 my $dbh = C4::Context->dbh;
1761 WHERE subscriptionid=?
1763 my $sth = $dbh->prepare($query);
1764 $sth->execute( $distributedto, $subscriptionid );
1768 =head2 DelSubscription
1770 DelSubscription($subscriptionid)
1771 this function deletes subscription which has $subscriptionid as id.
1775 sub DelSubscription {
1776 my ($subscriptionid) = @_;
1777 my $dbh = C4::Context->dbh;
1778 $subscriptionid = $dbh->quote($subscriptionid);
1779 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1780 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1781 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1783 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1788 DelIssue($serialseq,$subscriptionid)
1789 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1791 returns the number of rows affected
1796 my ($dataissue) = @_;
1797 my $dbh = C4::Context->dbh;
1798 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1803 AND subscriptionid= ?
1805 my $mainsth = $dbh->prepare($query);
1806 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1808 #Delete element from subscription history
1809 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1810 my $sth = $dbh->prepare($query);
1811 $sth->execute( $dataissue->{'subscriptionid'} );
1812 my $val = $sth->fetchrow_hashref;
1813 unless ( $val->{manualhistory} ) {
1815 SELECT * FROM subscriptionhistory
1816 WHERE subscriptionid= ?
1818 my $sth = $dbh->prepare($query);
1819 $sth->execute( $dataissue->{'subscriptionid'} );
1820 my $data = $sth->fetchrow_hashref;
1821 my $serialseq = $dataissue->{'serialseq'};
1822 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1823 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1824 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1825 $sth = $dbh->prepare($strsth);
1826 $sth->execute( $dataissue->{'subscriptionid'} );
1829 return $mainsth->rows;
1832 =head2 GetLateOrMissingIssues
1834 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1836 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1839 the issuelist as an array of hash refs. Each element of this array contains
1840 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1844 sub GetLateOrMissingIssues {
1845 my ( $supplierid, $serialid, $order ) = @_;
1846 my $dbh = C4::Context->dbh;
1850 $byserial = "and serialid = " . $serialid;
1853 $order .= ", title";
1858 $sth = $dbh->prepare(
1860 serialid, aqbooksellerid, name,
1861 biblio.title, planneddate, serialseq,
1862 serial.status, serial.subscriptionid, claimdate,
1863 subscription.branchcode
1865 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1866 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1867 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1868 WHERE subscription.subscriptionid = serial.subscriptionid
1869 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1870 AND subscription.aqbooksellerid=$supplierid
1875 $sth = $dbh->prepare(
1877 serialid, aqbooksellerid, name,
1878 biblio.title, planneddate, serialseq,
1879 serial.status, serial.subscriptionid, claimdate,
1880 subscription.branchcode
1882 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1883 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1884 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1885 WHERE subscription.subscriptionid = serial.subscriptionid
1886 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1893 while ( my $line = $sth->fetchrow_hashref ) {
1895 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1896 $line->{planneddate} = format_date( $line->{planneddate} );
1898 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1899 $line->{claimdate} = format_date( $line->{claimdate} );
1901 $line->{"status".$line->{status}} = 1;
1902 push @issuelist, $line;
1907 =head2 removeMissingIssue
1909 removeMissingIssue($subscriptionid)
1911 this function removes an issue from being part of the missing string in
1912 subscriptionlist.missinglist column
1914 called when a missing issue is found from the serials-recieve.pl file
1918 sub removeMissingIssue {
1919 my ( $sequence, $subscriptionid ) = @_;
1920 my $dbh = C4::Context->dbh;
1921 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1922 $sth->execute($subscriptionid);
1923 my $data = $sth->fetchrow_hashref;
1924 my $missinglist = $data->{'missinglist'};
1925 my $missinglistbefore = $missinglist;
1927 # warn $missinglist." before";
1928 $missinglist =~ s/($sequence)//;
1930 # warn $missinglist." after";
1931 if ( $missinglist ne $missinglistbefore ) {
1932 $missinglist =~ s/\|\s\|/\|/g;
1933 $missinglist =~ s/^\| //g;
1934 $missinglist =~ s/\|$//g;
1935 my $sth2 = $dbh->prepare(
1936 "UPDATE subscriptionhistory
1938 WHERE subscriptionid = ?"
1940 $sth2->execute( $missinglist, $subscriptionid );
1947 &updateClaim($serialid)
1949 this function updates the time when a claim is issued for late/missing items
1951 called from claims.pl file
1956 my ($serialid) = @_;
1957 my $dbh = C4::Context->dbh;
1958 my $sth = $dbh->prepare(
1959 "UPDATE serial SET claimdate = now()
1963 $sth->execute($serialid);
1967 =head2 getsupplierbyserialid
1969 $result = getsupplierbyserialid($serialid)
1971 this function is used to find the supplier id given a serial id
1974 hashref containing serialid, subscriptionid, and aqbooksellerid
1978 sub getsupplierbyserialid {
1979 my ($serialid) = @_;
1980 my $dbh = C4::Context->dbh;
1981 my $sth = $dbh->prepare(
1982 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1984 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1988 $sth->execute($serialid);
1989 my $line = $sth->fetchrow_hashref;
1990 my $result = $line->{'aqbooksellerid'};
1994 =head2 check_routing
1996 $result = &check_routing($subscriptionid)
1998 this function checks to see if a serial has a routing list and returns the count of routingid
1999 used to show either an 'add' or 'edit' link
2004 my ($subscriptionid) = @_;
2005 my $dbh = C4::Context->dbh;
2006 my $sth = $dbh->prepare(
2007 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
2008 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2009 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2012 $sth->execute($subscriptionid);
2013 my $line = $sth->fetchrow_hashref;
2014 my $result = $line->{'routingids'};
2018 =head2 addroutingmember
2020 addroutingmember($borrowernumber,$subscriptionid)
2022 this function takes a borrowernumber and subscriptionid and adds the member to the
2023 routing list for that serial subscription and gives them a rank on the list
2024 of either 1 or highest current rank + 1
2028 sub addroutingmember {
2029 my ( $borrowernumber, $subscriptionid ) = @_;
2031 my $dbh = C4::Context->dbh;
2032 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
2033 $sth->execute($subscriptionid);
2034 while ( my $line = $sth->fetchrow_hashref ) {
2035 if ( $line->{'rank'} > 0 ) {
2036 $rank = $line->{'rank'} + 1;
2041 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
2042 $sth->execute( $subscriptionid, $borrowernumber, $rank );
2045 =head2 reorder_members
2047 reorder_members($subscriptionid,$routingid,$rank)
2049 this function is used to reorder the routing list
2051 it takes the routingid of the member one wants to re-rank and the rank it is to move to
2052 - it gets all members on list puts their routingid's into an array
2053 - removes the one in the array that is $routingid
2054 - then reinjects $routingid at point indicated by $rank
2055 - then update the database with the routingids in the new order
2059 sub reorder_members {
2060 my ( $subscriptionid, $routingid, $rank ) = @_;
2061 my $dbh = C4::Context->dbh;
2062 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
2063 $sth->execute($subscriptionid);
2065 while ( my $line = $sth->fetchrow_hashref ) {
2066 push( @result, $line->{'routingid'} );
2069 # To find the matching index
2071 my $key = -1; # to allow for 0 being a valid response
2072 for ( $i = 0 ; $i < @result ; $i++ ) {
2073 if ( $routingid == $result[$i] ) {
2074 $key = $i; # save the index
2079 # if index exists in array then move it to new position
2080 if ( $key > -1 && $rank > 0 ) {
2081 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
2082 my $moving_item = splice( @result, $key, 1 );
2083 splice( @result, $new_rank, 0, $moving_item );
2085 for ( my $j = 0 ; $j < @result ; $j++ ) {
2086 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
2092 =head2 delroutingmember
2094 delroutingmember($routingid,$subscriptionid)
2096 this function either deletes one member from routing list if $routingid exists otherwise
2097 deletes all members from the routing list
2101 sub delroutingmember {
2103 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2104 my ( $routingid, $subscriptionid ) = @_;
2105 my $dbh = C4::Context->dbh;
2107 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2108 $sth->execute($routingid);
2109 reorder_members( $subscriptionid, $routingid );
2111 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2112 $sth->execute($subscriptionid);
2117 =head2 getroutinglist
2119 @routinglist = getroutinglist($subscriptionid)
2121 this gets the info from the subscriptionroutinglist for $subscriptionid
2124 the routinglist as an array. Each element of the array contains a hash_ref containing
2125 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2129 sub getroutinglist {
2130 my ($subscriptionid) = @_;
2131 my $dbh = C4::Context->dbh;
2132 my $sth = $dbh->prepare(
2133 'SELECT routingid, borrowernumber, ranking, biblionumber
2135 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2136 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2138 $sth->execute($subscriptionid);
2139 my $routinglist = $sth->fetchall_arrayref({});
2140 return @{$routinglist};
2143 =head2 countissuesfrom
2145 $result = countissuesfrom($subscriptionid,$startdate)
2147 Returns a count of serial rows matching the given subsctiptionid
2148 with published date greater than startdate
2152 sub countissuesfrom {
2153 my ( $subscriptionid, $startdate ) = @_;
2154 my $dbh = C4::Context->dbh;
2158 WHERE subscriptionid=?
2159 AND serial.publisheddate>?
2161 my $sth = $dbh->prepare($query);
2162 $sth->execute( $subscriptionid, $startdate );
2163 my ($countreceived) = $sth->fetchrow;
2164 return $countreceived;
2169 $result = CountIssues($subscriptionid)
2171 Returns a count of serial rows matching the given subsctiptionid
2176 my ($subscriptionid) = @_;
2177 my $dbh = C4::Context->dbh;
2181 WHERE subscriptionid=?
2183 my $sth = $dbh->prepare($query);
2184 $sth->execute($subscriptionid);
2185 my ($countreceived) = $sth->fetchrow;
2186 return $countreceived;
2191 $result = HasItems($subscriptionid)
2193 returns a count of items from serial matching the subscriptionid
2198 my ($subscriptionid) = @_;
2199 my $dbh = C4::Context->dbh;
2201 SELECT COUNT(serialitems.itemnumber)
2203 LEFT JOIN serialitems USING(serialid)
2204 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2206 my $sth=$dbh->prepare($query);
2207 $sth->execute($subscriptionid);
2208 my ($countitems)=$sth->fetchrow_array();
2212 =head2 abouttoexpire
2214 $result = abouttoexpire($subscriptionid)
2216 this function alerts you to the penultimate issue for a serial subscription
2218 returns 1 - if this is the penultimate issue
2224 my ($subscriptionid) = @_;
2225 my $dbh = C4::Context->dbh;
2226 my $subscription = GetSubscription($subscriptionid);
2227 my $per = $subscription->{'periodicity'};
2228 if ($per && $per % 16 > 0){
2229 my $expirationdate = GetExpirationDate($subscriptionid);
2230 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2233 @res=split (/-/,$res);
2234 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2235 } else { # default an undefined value
2236 @res=Date::Calc::Today;
2238 my @endofsubscriptiondate=split(/-/,$expirationdate);
2239 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2241 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2242 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2243 return 1 if ( @res &&
2245 Delta_Days($res[0],$res[1],$res[2],
2246 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2247 (@endofsubscriptiondate &&
2248 Delta_Days($res[0],$res[1],$res[2],
2249 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2251 } elsif ($subscription->{numberlength}>0) {
2252 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2257 sub in_array { # used in next sub down
2258 my ( $val, @elements ) = @_;
2259 foreach my $elem (@elements) {
2260 if ( $val == $elem ) {
2267 =head2 GetSubscriptionsFromBorrower
2269 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2271 this gets the info from subscriptionroutinglist for each $subscriptionid
2274 a count of the serial subscription routing lists to which a patron belongs,
2275 with the titles of those serial subscriptions as an array. Each element of the array
2276 contains a hash_ref with subscriptionID and title of subscription.
2280 sub GetSubscriptionsFromBorrower {
2281 my ($borrowernumber) = @_;
2282 my $dbh = C4::Context->dbh;
2283 my $sth = $dbh->prepare(
2284 "SELECT subscription.subscriptionid, biblio.title
2286 JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2287 JOIN subscriptionroutinglist USING (subscriptionid)
2288 WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2291 $sth->execute($borrowernumber);
2294 while ( my $line = $sth->fetchrow_hashref ) {
2296 push( @routinglist, $line );
2298 return ( $count, @routinglist );
2303 $resultdate = GetNextDate($planneddate,$subscription)
2305 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2306 exists an irregularity
2307 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2308 skipped then the returned date will be 2007-05-10
2311 $resultdate - then next date in the sequence
2313 Return 0 if periodicity==0
2318 my ( $planneddate, $subscription ) = @_;
2319 my @irreg = split( /\,/, $subscription->{irregularity} );
2321 #date supposed to be in ISO.
2323 my ( $year, $month, $day ) = split( /-/, $planneddate );
2324 $month = 1 unless ($month);
2325 $day = 1 unless ($day);
2328 # warn "DOW $dayofweek";
2329 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2334 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2335 # renaming this pattern from 1/day to " n / week ".
2336 if ( $subscription->{periodicity} == 1 ) {
2337 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2338 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2340 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2341 $dayofweek = 0 if ( $dayofweek == 7 );
2342 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2343 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2347 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2352 if ( $subscription->{periodicity} == 2 ) {
2353 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2354 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2356 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2358 #FIXME: if two consecutive irreg, do we only skip one?
2359 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2360 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2361 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2364 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2369 if ( $subscription->{periodicity} == 3 ) {
2370 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2371 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2373 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2374 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2375 ### BUGFIX was previously +1 ^
2376 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2377 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2380 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2385 if ( $subscription->{periodicity} == 4 ) {
2386 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2387 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2389 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2390 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2391 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2392 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2395 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2398 my $tmpmonth = $month;
2399 if ( $year && $month && $day ) {
2400 if ( $subscription->{periodicity} == 5 ) {
2401 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2402 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2403 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2404 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2407 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2409 if ( $subscription->{periodicity} == 6 ) {
2410 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2411 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2412 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2413 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2416 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2418 if ( $subscription->{periodicity} == 7 ) {
2419 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2420 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2421 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2422 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2425 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2427 if ( $subscription->{periodicity} == 8 ) {
2428 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2429 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2430 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2431 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2434 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2436 if ( $subscription->{periodicity} == 13 ) {
2437 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2438 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2439 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2440 $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2443 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2445 if ( $subscription->{periodicity} == 9 ) {
2446 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2447 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2448 ### BUFIX Seems to need more Than One ?
2449 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2450 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2453 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2455 if ( $subscription->{periodicity} == 10 ) {
2456 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2458 if ( $subscription->{periodicity} == 11 ) {
2459 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2462 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2464 return "$resultdate";
2467 =head2 is_barcode_in_use
2469 Returns number of occurence of the barcode in the items table
2470 Can be used as a boolean test of whether the barcode has
2471 been deployed as yet
2475 sub is_barcode_in_use {
2476 my $barcode = shift;
2477 my $dbh = C4::Context->dbh;
2478 my $occurences = $dbh->selectall_arrayref(
2479 'SELECT itemnumber from items where barcode = ?',
2484 return @{$occurences};
2487 =head2 CloseSubscription
2488 Close a subscription given a subscriptionid
2490 sub CloseSubscription {
2491 my ( $subscriptionid ) = @_;
2492 return unless $subscriptionid;
2493 my $dbh = C4::Context->dbh;
2494 my $sth = $dbh->prepare( qq{
2497 WHERE subscriptionid = ?
2499 $sth->execute( $subscriptionid );
2501 # Set status = missing when status = stopped
2502 $sth = $dbh->prepare( qq{
2505 WHERE subscriptionid = ?
2508 $sth->execute( $subscriptionid );
2511 =head2 ReopenSubscription
2512 Reopen a subscription given a subscriptionid
2514 sub ReopenSubscription {
2515 my ( $subscriptionid ) = @_;
2516 return unless $subscriptionid;
2517 my $dbh = C4::Context->dbh;
2518 my $sth = $dbh->prepare( qq{
2521 WHERE subscriptionid = ?
2523 $sth->execute( $subscriptionid );
2525 # Set status = expected when status = stopped
2526 $sth = $dbh->prepare( qq{
2529 WHERE subscriptionid = ?
2532 $sth->execute( $subscriptionid );
2540 Koha Development Team <http://koha-community.org/>