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.01; # set version for version checking
37 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
38 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
39 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
40 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
42 &GetNextSeq &NewIssue &ItemizeSerials &GetSerials
43 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
44 &ReNewSubscription &GetLateIssues &GetLateOrMissingIssues
45 &GetSerialInformation &AddItem2Serial
46 &PrepareSerialsData &GetNextExpected &ModNextExpected
48 &UpdateClaimdateIssues
49 &GetSuppliersWithLateIssues &getsupplierbyserialid
50 &GetDistributedTo &SetDistributedTo
51 &getroutinglist &delroutingmember &addroutingmember
53 &check_routing &updateClaim &removeMissingIssue
62 C4::Serials - Serials Module Functions
70 Functions for handling subscriptions, claims routing etc.
75 =head2 GetSuppliersWithLateIssues
77 $supplierlist = GetSuppliersWithLateIssues()
79 this function get all suppliers with late issues.
82 an array_ref of suppliers each entry is a hash_ref containing id and name
83 the array is in name order
87 sub GetSuppliersWithLateIssues {
88 my $dbh = C4::Context->dbh;
90 SELECT DISTINCT id, name
92 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
93 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
94 WHERE id > 0 AND ((planneddate < now() AND serial.status=1) OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
95 return $dbh->selectall_arrayref($query, { Slice => {} });
100 @issuelist = GetLateIssues($supplierid)
102 this function selects late issues from the database
105 the issuelist as an array. Each element of this array contains a hashi_ref containing
106 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
111 my ($supplierid) = @_;
112 my $dbh = C4::Context->dbh;
116 SELECT name,title,planneddate,serialseq,serial.subscriptionid
118 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
119 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
120 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
121 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
122 AND subscription.aqbooksellerid=?
125 $sth = $dbh->prepare($query);
126 $sth->execute($supplierid);
129 SELECT name,title,planneddate,serialseq,serial.subscriptionid
131 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
132 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
133 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
134 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
137 $sth = $dbh->prepare($query);
143 while ( my $line = $sth->fetchrow_hashref ) {
144 $odd++ unless $line->{title} eq $last_title;
145 $line->{title} = "" if $line->{title} eq $last_title;
146 $last_title = $line->{title} if ( $line->{title} );
147 $line->{planneddate} = format_date( $line->{planneddate} );
148 push @issuelist, $line;
153 =head2 GetSubscriptionHistoryFromSubscriptionId
155 $sth = GetSubscriptionHistoryFromSubscriptionId()
156 this function prepares the SQL request and returns the statement handle
157 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
161 sub GetSubscriptionHistoryFromSubscriptionId() {
162 my $dbh = C4::Context->dbh;
165 FROM subscriptionhistory
166 WHERE subscriptionid = ?
168 return $dbh->prepare($query);
171 =head2 GetSerialStatusFromSerialId
173 $sth = GetSerialStatusFromSerialId();
174 this function returns a statement handle
175 After this function, don't forget to execute it by using $sth->execute($serialid)
177 $sth = $dbh->prepare($query).
181 sub GetSerialStatusFromSerialId() {
182 my $dbh = C4::Context->dbh;
188 return $dbh->prepare($query);
191 =head2 GetSerialInformation
194 $data = GetSerialInformation($serialid);
195 returns a hash_ref containing :
196 items : items marcrecord (can be an array)
198 subscription table field
199 + information about subscription expiration
203 sub GetSerialInformation {
205 my $dbh = C4::Context->dbh;
207 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
208 if ( C4::Context->preference('IndependantBranches')
209 && C4::Context->userenv
210 && C4::Context->userenv->{'flags'} != 1
211 && C4::Context->userenv->{'branch'} ) {
213 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
216 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
219 my $rq = $dbh->prepare($query);
220 $rq->execute($serialid);
221 my $data = $rq->fetchrow_hashref;
223 # create item information if we have serialsadditems for this subscription
224 if ( $data->{'serialsadditems'} ) {
225 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
226 $queryitem->execute($serialid);
227 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
228 if ( scalar(@$itemnumbers) > 0 ) {
229 foreach my $itemnum (@$itemnumbers) {
231 #It is ASSUMED that GetMarcItem ALWAYS WORK...
232 #Maybe GetMarcItem should return values on failure
233 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
234 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
235 $itemprocessed->{'itemnumber'} = $itemnum->[0];
236 $itemprocessed->{'itemid'} = $itemnum->[0];
237 $itemprocessed->{'serialid'} = $serialid;
238 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
239 push @{ $data->{'items'} }, $itemprocessed;
242 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
243 $itemprocessed->{'itemid'} = "N$serialid";
244 $itemprocessed->{'serialid'} = $serialid;
245 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
246 $itemprocessed->{'countitems'} = 0;
247 push @{ $data->{'items'} }, $itemprocessed;
250 $data->{ "status" . $data->{'serstatus'} } = 1;
251 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
252 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
256 =head2 AddItem2Serial
258 $rows = AddItem2Serial($serialid,$itemnumber);
259 Adds an itemnumber to Serial record
260 returns the number of rows affected
265 my ( $serialid, $itemnumber ) = @_;
266 my $dbh = C4::Context->dbh;
267 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
268 $rq->execute( $serialid, $itemnumber );
272 =head2 UpdateClaimdateIssues
274 UpdateClaimdateIssues($serialids,[$date]);
276 Update Claimdate for issues in @$serialids list with date $date
281 sub UpdateClaimdateIssues {
282 my ( $serialids, $date ) = @_;
283 my $dbh = C4::Context->dbh;
284 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
286 UPDATE serial SET claimdate = ?, status = 7
287 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
288 my $rq = $dbh->prepare($query);
289 $rq->execute($date, @$serialids);
293 =head2 GetSubscription
295 $subs = GetSubscription($subscriptionid)
296 this function returns the subscription which has $subscriptionid as id.
298 a hashref. This hash containts
299 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
303 sub GetSubscription {
304 my ($subscriptionid) = @_;
305 my $dbh = C4::Context->dbh;
307 SELECT subscription.*,
308 subscriptionhistory.*,
309 aqbooksellers.name AS aqbooksellername,
310 biblio.title AS bibliotitle,
311 subscription.biblionumber as bibnum);
312 if ( C4::Context->preference('IndependantBranches')
313 && C4::Context->userenv
314 && C4::Context->userenv->{'flags'} != 1
315 && C4::Context->userenv->{'branch'} ) {
317 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
321 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
322 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
323 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
324 WHERE subscription.subscriptionid = ?
327 # if (C4::Context->preference('IndependantBranches') &&
328 # C4::Context->userenv &&
329 # C4::Context->userenv->{'flags'} != 1){
330 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
331 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
333 $debug and warn "query : $query\nsubsid :$subscriptionid";
334 my $sth = $dbh->prepare($query);
335 $sth->execute($subscriptionid);
336 return $sth->fetchrow_hashref;
339 =head2 GetFullSubscription
341 $array_ref = GetFullSubscription($subscriptionid)
342 this function reads the serial table.
346 sub GetFullSubscription {
347 my ($subscriptionid) = @_;
348 my $dbh = C4::Context->dbh;
350 SELECT serial.serialid,
353 serial.publisheddate,
355 serial.notes as notes,
356 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
357 aqbooksellers.name as aqbooksellername,
358 biblio.title as bibliotitle,
359 subscription.branchcode AS branchcode,
360 subscription.subscriptionid AS subscriptionid |;
361 if ( C4::Context->preference('IndependantBranches')
362 && C4::Context->userenv
363 && C4::Context->userenv->{'flags'} != 1
364 && C4::Context->userenv->{'branch'} ) {
366 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
370 LEFT JOIN subscription ON
371 (serial.subscriptionid=subscription.subscriptionid )
372 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
373 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
374 WHERE serial.subscriptionid = ?
376 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
377 serial.subscriptionid
379 $debug and warn "GetFullSubscription query: $query";
380 my $sth = $dbh->prepare($query);
381 $sth->execute($subscriptionid);
382 return $sth->fetchall_arrayref( {} );
385 =head2 PrepareSerialsData
387 $array_ref = PrepareSerialsData($serialinfomation)
388 where serialinformation is a hashref array
392 sub PrepareSerialsData {
398 my $aqbooksellername;
402 my $previousnote = "";
404 foreach my $subs (@{$lines}) {
405 for my $datefield ( qw(publisheddate planneddate) ) {
406 # handle both undef and undef returned as 0000-00-00
407 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
408 $subs->{$datefield} = 'XXX';
411 $subs->{$datefield} = format_date( $subs->{$datefield} );
414 $subs->{ "status" . $subs->{'status'} } = 1;
415 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
417 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
418 $year = $subs->{'year'};
422 if ( $tmpresults{$year} ) {
423 push @{ $tmpresults{$year}->{'serials'} }, $subs;
425 $tmpresults{$year} = {
427 'aqbooksellername' => $subs->{'aqbooksellername'},
428 'bibliotitle' => $subs->{'bibliotitle'},
429 'serials' => [$subs],
434 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
435 push @res, $tmpresults{$key};
440 =head2 GetSubscriptionsFromBiblionumber
442 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
443 this function get the subscription list. it reads the subscription table.
445 reference to an array of subscriptions which have the biblionumber given on input arg.
446 each element of this array is a hashref containing
447 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
451 sub GetSubscriptionsFromBiblionumber {
452 my ($biblionumber) = @_;
453 my $dbh = C4::Context->dbh;
455 SELECT subscription.*,
457 subscriptionhistory.*,
458 aqbooksellers.name AS aqbooksellername,
459 biblio.title AS bibliotitle
461 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
462 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
463 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
464 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
465 WHERE subscription.biblionumber = ?
467 my $sth = $dbh->prepare($query);
468 $sth->execute($biblionumber);
470 while ( my $subs = $sth->fetchrow_hashref ) {
471 $subs->{startdate} = format_date( $subs->{startdate} );
472 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
473 $subs->{histenddate} = format_date( $subs->{histenddate} );
474 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
475 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
476 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
477 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
478 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
479 $subs->{ "status" . $subs->{'status'} } = 1;
480 $subs->{'cannotedit'} =
481 ( C4::Context->preference('IndependantBranches')
482 && C4::Context->userenv
483 && C4::Context->userenv->{flags} % 2 != 1
484 && C4::Context->userenv->{branch}
485 && $subs->{branchcode}
486 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
488 if ( $subs->{enddate} eq '0000-00-00' ) {
489 $subs->{enddate} = '';
491 $subs->{enddate} = format_date( $subs->{enddate} );
493 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
494 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
500 =head2 GetFullSubscriptionsFromBiblionumber
502 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
503 this function reads the serial table.
507 sub GetFullSubscriptionsFromBiblionumber {
508 my ($biblionumber) = @_;
509 my $dbh = C4::Context->dbh;
511 SELECT serial.serialid,
514 serial.publisheddate,
516 serial.notes as notes,
517 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
518 biblio.title as bibliotitle,
519 subscription.branchcode AS branchcode,
520 subscription.subscriptionid AS subscriptionid|;
521 if ( C4::Context->preference('IndependantBranches')
522 && C4::Context->userenv
523 && C4::Context->userenv->{'flags'} != 1
524 && C4::Context->userenv->{'branch'} ) {
526 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
531 LEFT JOIN subscription ON
532 (serial.subscriptionid=subscription.subscriptionid)
533 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
534 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
535 WHERE subscription.biblionumber = ?
537 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
538 serial.subscriptionid
540 my $sth = $dbh->prepare($query);
541 $sth->execute($biblionumber);
542 return $sth->fetchall_arrayref( {} );
545 =head2 GetSubscriptions
547 @results = GetSubscriptions($title,$ISSN,$biblionumber);
548 this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
550 a table of hashref. Each hash containt the subscription.
554 sub GetSubscriptions {
555 my ( $string, $issn, $biblionumber ) = @_;
557 #return unless $title or $ISSN or $biblionumber;
558 my $dbh = C4::Context->dbh;
561 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
563 LEFT JOIN subscriptionhistory USING(subscriptionid)
564 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
565 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
570 $sqlwhere = " WHERE biblio.biblionumber=?";
571 push @bind_params, $biblionumber;
575 my @strings_to_search;
576 @strings_to_search = map { "%$_%" } split( / /, $string );
577 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
578 push @bind_params, @strings_to_search;
579 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
580 $debug && warn "$tmpstring";
581 $tmpstring =~ s/^AND //;
582 push @sqlstrings, $tmpstring;
584 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
588 my @strings_to_search;
589 @strings_to_search = map { "%$_%" } split( / /, $issn );
590 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
591 push @bind_params, @strings_to_search;
592 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
593 $debug && warn "$tmpstring";
594 $tmpstring =~ s/^OR //;
595 push @sqlstrings, $tmpstring;
597 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
599 $sql .= "$sqlwhere ORDER BY title";
600 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
601 $sth = $dbh->prepare($sql);
602 $sth->execute(@bind_params);
605 while ( my $line = $sth->fetchrow_hashref ) {
606 $line->{'cannotedit'} =
607 ( C4::Context->preference('IndependantBranches')
608 && C4::Context->userenv
609 && C4::Context->userenv->{flags} % 2 != 1
610 && C4::Context->userenv->{branch}
611 && $line->{branchcode}
612 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
613 push @results, $line;
620 ($totalissues,@serials) = GetSerials($subscriptionid);
621 this function gets every serial not arrived for a given subscription
622 as well as the number of issues registered in the database (all types)
623 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
625 FIXME: We should return \@serials.
630 my ( $subscriptionid, $count ) = @_;
631 my $dbh = C4::Context->dbh;
633 # status = 2 is "arrived"
635 $count = 5 unless ($count);
637 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
639 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
640 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
641 my $sth = $dbh->prepare($query);
642 $sth->execute($subscriptionid);
644 while ( my $line = $sth->fetchrow_hashref ) {
645 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
646 for my $datefield ( qw( planneddate publisheddate) ) {
647 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
648 $line->{$datefield} = format_date( $line->{$datefield});
650 $line->{$datefield} = q{};
653 push @serials, $line;
656 # OK, now add the last 5 issues arrives/missing
657 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
659 WHERE subscriptionid = ?
660 AND (status in (2,4,5))
661 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
663 $sth = $dbh->prepare($query);
664 $sth->execute($subscriptionid);
665 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
667 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
668 for my $datefield ( qw( planneddate publisheddate) ) {
669 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
670 $line->{$datefield} = format_date( $line->{$datefield});
672 $line->{$datefield} = q{};
676 push @serials, $line;
679 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
680 $sth = $dbh->prepare($query);
681 $sth->execute($subscriptionid);
682 my ($totalissues) = $sth->fetchrow;
683 return ( $totalissues, @serials );
688 @serials = GetSerials2($subscriptionid,$status);
689 this function returns every serial waited for a given subscription
690 as well as the number of issues registered in the database (all types)
691 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
696 my ( $subscription, $status ) = @_;
697 my $dbh = C4::Context->dbh;
699 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
701 WHERE subscriptionid=$subscription AND status IN ($status)
702 ORDER BY publisheddate,serialid DESC
704 $debug and warn "GetSerials2 query: $query";
705 my $sth = $dbh->prepare($query);
709 while ( my $line = $sth->fetchrow_hashref ) {
710 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
711 # Format dates for display
712 for my $datefield ( qw( planneddate publisheddate ) ) {
713 if ($line->{$datefield} =~m/^00/) {
714 $line->{$datefield} = q{};
717 $line->{$datefield} = format_date( $line->{$datefield} );
720 push @serials, $line;
725 =head2 GetLatestSerials
727 \@serials = GetLatestSerials($subscriptionid,$limit)
728 get the $limit's latest serials arrived or missing for a given subscription
730 a ref to an array which contains all of the latest serials stored into a hash.
734 sub GetLatestSerials {
735 my ( $subscriptionid, $limit ) = @_;
736 my $dbh = C4::Context->dbh;
738 # status = 2 is "arrived"
739 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
741 WHERE subscriptionid = ?
742 AND (status =2 or status=4)
743 ORDER BY planneddate DESC LIMIT 0,$limit
745 my $sth = $dbh->prepare($strsth);
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 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
751 push @serials, $line;
757 =head2 GetDistributedTo
759 $distributedto=GetDistributedTo($subscriptionid)
760 This function returns the field distributedto for the subscription matching subscriptionid
764 sub GetDistributedTo {
765 my $dbh = C4::Context->dbh;
767 my $subscriptionid = @_;
768 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
769 my $sth = $dbh->prepare($query);
770 $sth->execute($subscriptionid);
771 return ($distributedto) = $sth->fetchrow;
777 $val is a hashref containing all the attributes of the table 'subscription'
778 This function get the next issue for the subscription given on input arg
780 a list containing all the input params updated.
786 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
787 # $calculated = $val->{numberingmethod};
788 # # calculate the (expected) value of the next issue recieved.
789 # $newlastvalue1 = $val->{lastvalue1};
790 # # check if we have to increase the new value.
791 # $newinnerloop1 = $val->{innerloop1}+1;
792 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
793 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
794 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
795 # $calculated =~ s/\{X\}/$newlastvalue1/g;
797 # $newlastvalue2 = $val->{lastvalue2};
798 # # check if we have to increase the new value.
799 # $newinnerloop2 = $val->{innerloop2}+1;
800 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
801 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
802 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
803 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
805 # $newlastvalue3 = $val->{lastvalue3};
806 # # check if we have to increase the new value.
807 # $newinnerloop3 = $val->{innerloop3}+1;
808 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
809 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
810 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
811 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
812 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
817 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
818 my $pattern = $val->{numberpattern};
819 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
820 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
821 $calculated = $val->{numberingmethod};
822 $newlastvalue1 = $val->{lastvalue1};
823 $newlastvalue2 = $val->{lastvalue2};
824 $newlastvalue3 = $val->{lastvalue3};
825 $newlastvalue1 = $val->{lastvalue1};
827 # check if we have to increase the new value.
828 $newinnerloop1 = $val->{innerloop1} + 1;
829 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
830 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
831 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
832 $calculated =~ s/\{X\}/$newlastvalue1/g;
834 $newlastvalue2 = $val->{lastvalue2};
836 # check if we have to increase the new value.
837 $newinnerloop2 = $val->{innerloop2} + 1;
838 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
839 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
840 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
841 if ( $pattern == 6 ) {
842 if ( $val->{hemisphere} == 2 ) {
843 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
844 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
846 my $newlastvalue2seq = $seasons[$newlastvalue2];
847 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
850 $calculated =~ s/\{Y\}/$newlastvalue2/g;
853 $newlastvalue3 = $val->{lastvalue3};
855 # check if we have to increase the new value.
856 $newinnerloop3 = $val->{innerloop3} + 1;
857 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
858 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
859 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
860 $calculated =~ s/\{Z\}/$newlastvalue3/g;
862 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
867 $calculated = GetSeq($val)
868 $val is a hashref containing all the attributes of the table 'subscription'
869 this function transforms {X},{Y},{Z} to 150,0,0 for example.
871 the sequence in integer format
877 my $pattern = $val->{numberpattern};
878 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
879 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
880 my $calculated = $val->{numberingmethod};
881 my $x = $val->{'lastvalue1'};
882 $calculated =~ s/\{X\}/$x/g;
883 my $newlastvalue2 = $val->{'lastvalue2'};
885 if ( $pattern == 6 ) {
886 if ( $val->{hemisphere} == 2 ) {
887 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
888 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
890 my $newlastvalue2seq = $seasons[$newlastvalue2];
891 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
894 $calculated =~ s/\{Y\}/$newlastvalue2/g;
896 my $z = $val->{'lastvalue3'};
897 $calculated =~ s/\{Z\}/$z/g;
901 =head2 GetExpirationDate
903 $enddate = GetExpirationDate($subscriptionid, [$startdate])
905 this function return the next expiration date for a subscription given on input args.
912 sub GetExpirationDate {
913 my ( $subscriptionid, $startdate ) = @_;
914 my $dbh = C4::Context->dbh;
915 my $subscription = GetSubscription($subscriptionid);
918 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
919 $enddate = $startdate || $subscription->{startdate};
920 my @date = split( /-/, $enddate );
921 return if ( scalar(@date) != 3 || not check_date(@date) );
922 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
925 if ( my $length = $subscription->{numberlength} ) {
927 #calculate the date of the last issue.
928 for ( my $i = 1 ; $i <= $length ; $i++ ) {
929 $enddate = GetNextDate( $enddate, $subscription );
931 } elsif ( $subscription->{monthlength} ) {
932 if ( $$subscription{startdate} ) {
933 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
934 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
936 } elsif ( $subscription->{weeklength} ) {
937 if ( $$subscription{startdate} ) {
938 my @date = split( /-/, $subscription->{startdate} );
939 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
940 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
949 =head2 CountSubscriptionFromBiblionumber
951 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
952 this returns a count of the subscriptions for a given biblionumber
954 the number of subscriptions
958 sub CountSubscriptionFromBiblionumber {
959 my ($biblionumber) = @_;
960 my $dbh = C4::Context->dbh;
961 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
962 my $sth = $dbh->prepare($query);
963 $sth->execute($biblionumber);
964 my $subscriptionsnumber = $sth->fetchrow;
965 return $subscriptionsnumber;
968 =head2 ModSubscriptionHistory
970 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
972 this function modifies the history of a subscription. Put your new values on input arg.
973 returns the number of rows affected
977 sub ModSubscriptionHistory {
978 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
979 my $dbh = C4::Context->dbh;
980 my $query = "UPDATE subscriptionhistory
981 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
982 WHERE subscriptionid=?
984 my $sth = $dbh->prepare($query);
985 $recievedlist =~ s/^; //;
986 $missinglist =~ s/^; //;
987 $opacnote =~ s/^; //;
988 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
992 =head2 ModSerialStatus
994 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
996 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
997 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1001 sub ModSerialStatus {
1002 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1004 #It is a usual serial
1005 # 1st, get previous status :
1006 my $dbh = C4::Context->dbh;
1007 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1008 my $sth = $dbh->prepare($query);
1009 $sth->execute($serialid);
1010 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1012 # change status & update subscriptionhistory
1014 if ( $status == 6 ) {
1015 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1019 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1020 $sth = $dbh->prepare($query);
1021 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1022 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1023 $sth = $dbh->prepare($query);
1024 $sth->execute($subscriptionid);
1025 my $val = $sth->fetchrow_hashref;
1026 unless ( $val->{manualhistory} ) {
1027 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1028 $sth = $dbh->prepare($query);
1029 $sth->execute($subscriptionid);
1030 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1031 if ( $status == 2 ) {
1033 $recievedlist .= "; $serialseq"
1034 unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1037 # warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1038 $missinglist .= "; $serialseq"
1040 and not index( "$missinglist", "$serialseq" ) >= 0 );
1041 $missinglist .= "; not issued $serialseq"
1043 and index( "$missinglist", "$serialseq" ) >= 0 );
1044 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1045 $sth = $dbh->prepare($query);
1046 $recievedlist =~ s/^; //;
1047 $missinglist =~ s/^; //;
1048 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1052 # create new waited entry if needed (ie : was a "waited" and has changed)
1053 if ( $oldstatus == 1 && $status != 1 ) {
1054 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1055 $sth = $dbh->prepare($query);
1056 $sth->execute($subscriptionid);
1057 my $val = $sth->fetchrow_hashref;
1061 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1062 $newinnerloop1, $newinnerloop2, $newinnerloop3
1063 ) = GetNextSeq($val);
1065 # next date (calculated from actual date & frequency parameters)
1066 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1067 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1068 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1069 WHERE subscriptionid = ?";
1070 $sth = $dbh->prepare($query);
1071 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1073 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1074 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1075 SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1081 =head2 GetNextExpected
1083 $nextexpected = GetNextExpected($subscriptionid)
1085 Get the planneddate for the current expected issue of the subscription.
1091 planneddate => C4::Dates object
1096 sub GetNextExpected($) {
1097 my ($subscriptionid) = @_;
1098 my $dbh = C4::Context->dbh;
1099 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1101 # Each subscription has only one 'expected' issue, with serial.status==1.
1102 $sth->execute( $subscriptionid, 1 );
1103 my ( $nextissue ) = $sth->fetchrow_hashref;
1105 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1106 $sth->execute( $subscriptionid );
1107 $nextissue = $sth->fetchrow_hashref;
1109 if (!defined $nextissue->{planneddate}) {
1110 # or should this default to 1st Jan ???
1111 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1113 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1118 =head2 ModNextExpected
1120 ModNextExpected($subscriptionid,$date)
1122 Update the planneddate for the current expected issue of the subscription.
1123 This will modify all future prediction results.
1125 C<$date> is a C4::Dates object.
1131 sub ModNextExpected($$) {
1132 my ( $subscriptionid, $date ) = @_;
1133 my $dbh = C4::Context->dbh;
1135 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1136 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1138 # Each subscription has only one 'expected' issue, with serial.status==1.
1139 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1144 =head2 ModSubscription
1146 this function modifies a subscription. Put all new values on input args.
1147 returns the number of rows affected
1151 sub ModSubscription {
1152 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1153 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1154 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1155 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1156 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1157 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1160 # warn $irregularity;
1161 my $dbh = C4::Context->dbh;
1162 my $query = "UPDATE subscription
1163 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1164 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1165 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1166 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1167 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1168 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1169 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1170 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1172 WHERE subscriptionid = ?";
1174 #warn "query :".$query;
1175 my $sth = $dbh->prepare($query);
1177 $auser, $branchcode, $aqbooksellerid, $cost,
1178 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1179 $dow, "$irregularity", $numberpattern, $numberlength,
1180 $weeklength, $monthlength, $add1, $every1,
1181 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1182 $add2, $every2, $whenmorethan2, $setto2,
1183 $lastvalue2, $innerloop2, $add3, $every3,
1184 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1185 $numberingmethod, $status, $biblionumber, $callnumber,
1186 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1187 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1188 $graceperiod, $location, $enddate, $subscriptionid
1190 my $rows = $sth->rows;
1192 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1196 =head2 NewSubscription
1198 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1199 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1200 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1201 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1202 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1203 $numberingmethod, $status, $notes, $serialsadditems,
1204 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1206 Create a new subscription with value given on input args.
1209 the id of this new subscription
1213 sub NewSubscription {
1214 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1215 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1216 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1217 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1218 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1219 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1221 my $dbh = C4::Context->dbh;
1223 #save subscription (insert into database)
1225 INSERT INTO subscription
1226 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1227 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1228 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1229 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1230 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1231 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1232 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1233 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1234 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1236 my $sth = $dbh->prepare($query);
1238 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1239 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1240 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1241 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1242 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1243 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1246 my $subscriptionid = $dbh->{'mysql_insertid'};
1248 $enddate = GetExpirationDate($subscriptionid,$startdate);
1252 WHERE subscriptionid=?
1254 $sth = $dbh->prepare($query);
1255 $sth->execute( $enddate, $subscriptionid );
1257 #then create the 1st waited number
1259 INSERT INTO subscriptionhistory
1260 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1263 $sth = $dbh->prepare($query);
1264 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1266 # reread subscription to get a hash (for calculation of the 1st issue number)
1270 WHERE subscriptionid = ?
1272 $sth = $dbh->prepare($query);
1273 $sth->execute($subscriptionid);
1274 my $val = $sth->fetchrow_hashref;
1276 # calculate issue number
1277 my $serialseq = GetSeq($val);
1280 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1281 VALUES (?,?,?,?,?,?)
1283 $sth = $dbh->prepare($query);
1284 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1286 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1288 #set serial flag on biblio if not already set.
1289 my ( $null, ($bib) ) = GetBiblio($biblionumber);
1290 if ( !$bib->{'serial'} ) {
1291 my $record = GetMarcBiblio($biblionumber);
1292 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1294 eval { $record->field($tag)->update( $subf => 1 ); };
1296 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1298 return $subscriptionid;
1301 =head2 ReNewSubscription
1303 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1305 this function renew a subscription with values given on input args.
1309 sub ReNewSubscription {
1310 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1311 my $dbh = C4::Context->dbh;
1312 my $subscription = GetSubscription($subscriptionid);
1316 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1317 WHERE biblio.biblionumber=?
1319 my $sth = $dbh->prepare($query);
1320 $sth->execute( $subscription->{biblionumber} );
1321 my $biblio = $sth->fetchrow_hashref;
1323 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1324 require C4::Suggestions;
1325 C4::Suggestions::NewSuggestion(
1326 { 'suggestedby' => $user,
1327 'title' => $subscription->{bibliotitle},
1328 'author' => $biblio->{author},
1329 'publishercode' => $biblio->{publishercode},
1330 'note' => $biblio->{note},
1331 'biblionumber' => $subscription->{biblionumber}
1336 # renew subscription
1339 SET startdate=?,numberlength=?,weeklength=?,monthlength=?
1340 WHERE subscriptionid=?
1342 $sth = $dbh->prepare($query);
1343 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1344 my $enddate = GetExpirationDate($subscriptionid);
1345 $debug && warn "enddate :$enddate";
1349 WHERE subscriptionid=?
1351 $sth = $dbh->prepare($query);
1352 $sth->execute( $enddate, $subscriptionid );
1354 UPDATE subscriptionhistory
1356 WHERE subscriptionid=?
1358 $sth = $dbh->prepare($query);
1359 $sth->execute( $enddate, $subscriptionid );
1361 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1367 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1369 Create a new issue stored on the database.
1370 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1371 returns the serial id
1376 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1377 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1379 my $dbh = C4::Context->dbh;
1382 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1383 VALUES (?,?,?,?,?,?,?)
1385 my $sth = $dbh->prepare($query);
1386 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1387 my $serialid = $dbh->{'mysql_insertid'};
1389 SELECT missinglist,recievedlist
1390 FROM subscriptionhistory
1391 WHERE subscriptionid=?
1393 $sth = $dbh->prepare($query);
1394 $sth->execute($subscriptionid);
1395 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1397 if ( $status == 2 ) {
1398 ### TODO Add a feature that improves recognition and description.
1399 ### As such count (serialseq) i.e. : N18,2(N19),N20
1400 ### Would use substr and index But be careful to previous presence of ()
1401 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1403 if ( $status == 4 ) {
1404 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1407 UPDATE subscriptionhistory
1408 SET recievedlist=?, missinglist=?
1409 WHERE subscriptionid=?
1411 $sth = $dbh->prepare($query);
1412 $recievedlist =~ s/^; //;
1413 $missinglist =~ s/^; //;
1414 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1418 =head2 ItemizeSerials
1420 ItemizeSerials($serialid, $info);
1421 $info is a hashref containing barcode branch, itemcallnumber, status, location
1422 $serialid the serialid
1424 1 if the itemize is a succes.
1425 0 and @error otherwise. @error containts the list of errors found.
1429 sub ItemizeSerials {
1430 my ( $serialid, $info ) = @_;
1431 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1433 my $dbh = C4::Context->dbh;
1439 my $sth = $dbh->prepare($query);
1440 $sth->execute($serialid);
1441 my $data = $sth->fetchrow_hashref;
1442 if ( C4::Context->preference("RoutingSerials") ) {
1444 # check for existing biblioitem relating to serial issue
1445 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1447 for ( my $i = 0 ; $i < $count ; $i++ ) {
1448 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1449 $bibitemno = $results[$i]->{'biblioitemnumber'};
1453 if ( $bibitemno == 0 ) {
1454 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1455 $sth->execute( $data->{'biblionumber'} );
1456 my $biblioitem = $sth->fetchrow_hashref;
1457 $biblioitem->{'volumedate'} = $data->{planneddate};
1458 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1459 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1463 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1464 if ( $info->{barcode} ) {
1466 if ( is_barcode_in_use( $info->{barcode} ) ) {
1467 push @errors, 'barcode_not_unique';
1469 my $marcrecord = MARC::Record->new();
1470 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1471 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1472 $marcrecord->insert_fields_ordered($newField);
1473 if ( $info->{branch} ) {
1474 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1476 #warn "items.homebranch : $tag , $subfield";
1477 if ( $marcrecord->field($tag) ) {
1478 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1480 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1481 $marcrecord->insert_fields_ordered($newField);
1483 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1485 #warn "items.holdingbranch : $tag , $subfield";
1486 if ( $marcrecord->field($tag) ) {
1487 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1489 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1490 $marcrecord->insert_fields_ordered($newField);
1493 if ( $info->{itemcallnumber} ) {
1494 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1496 if ( $marcrecord->field($tag) ) {
1497 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1499 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1500 $marcrecord->insert_fields_ordered($newField);
1503 if ( $info->{notes} ) {
1504 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1506 if ( $marcrecord->field($tag) ) {
1507 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1509 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1510 $marcrecord->insert_fields_ordered($newField);
1513 if ( $info->{location} ) {
1514 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1516 if ( $marcrecord->field($tag) ) {
1517 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1519 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1520 $marcrecord->insert_fields_ordered($newField);
1523 if ( $info->{status} ) {
1524 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1526 if ( $marcrecord->field($tag) ) {
1527 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1529 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1530 $marcrecord->insert_fields_ordered($newField);
1533 if ( C4::Context->preference("RoutingSerials") ) {
1534 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1535 if ( $marcrecord->field($tag) ) {
1536 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1538 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1539 $marcrecord->insert_fields_ordered($newField);
1543 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1546 return ( 0, @errors );
1550 =head2 HasSubscriptionStrictlyExpired
1552 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1554 the subscription has stricly expired when today > the end subscription date
1557 1 if true, 0 if false, -1 if the expiration date is not set.
1561 sub HasSubscriptionStrictlyExpired {
1563 # Getting end of subscription date
1564 my ($subscriptionid) = @_;
1565 my $dbh = C4::Context->dbh;
1566 my $subscription = GetSubscription($subscriptionid);
1567 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1569 # If the expiration date is set
1570 if ( $expirationdate != 0 ) {
1571 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1573 # Getting today's date
1574 my ( $nowyear, $nowmonth, $nowday ) = Today();
1576 # if today's date > expiration date, then the subscription has stricly expired
1577 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1584 # There are some cases where the expiration date is not set
1585 # As we can't determine if the subscription has expired on a date-basis,
1591 =head2 HasSubscriptionExpired
1593 $has_expired = HasSubscriptionExpired($subscriptionid)
1595 the subscription has expired when the next issue to arrive is out of subscription limit.
1598 0 if the subscription has not expired
1599 1 if the subscription has expired
1600 2 if has subscription does not have a valid expiration date set
1604 sub HasSubscriptionExpired {
1605 my ($subscriptionid) = @_;
1606 my $dbh = C4::Context->dbh;
1607 my $subscription = GetSubscription($subscriptionid);
1608 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1609 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1610 if (!defined $expirationdate) {
1611 $expirationdate = q{};
1614 SELECT max(planneddate)
1616 WHERE subscriptionid=?
1618 my $sth = $dbh->prepare($query);
1619 $sth->execute($subscriptionid);
1620 my ($res) = $sth->fetchrow;
1621 if (!$res || $res=~m/^0000/) {
1624 my @res = split( /-/, $res );
1625 my @endofsubscriptiondate = split( /-/, $expirationdate );
1626 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1628 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1632 if ( $subscription->{'numberlength'} ) {
1633 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1634 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1640 return 0; # Notice that you'll never get here.
1643 =head2 SetDistributedto
1645 SetDistributedto($distributedto,$subscriptionid);
1646 This function update the value of distributedto for a subscription given on input arg.
1650 sub SetDistributedto {
1651 my ( $distributedto, $subscriptionid ) = @_;
1652 my $dbh = C4::Context->dbh;
1656 WHERE subscriptionid=?
1658 my $sth = $dbh->prepare($query);
1659 $sth->execute( $distributedto, $subscriptionid );
1663 =head2 DelSubscription
1665 DelSubscription($subscriptionid)
1666 this function deletes subscription which has $subscriptionid as id.
1670 sub DelSubscription {
1671 my ($subscriptionid) = @_;
1672 my $dbh = C4::Context->dbh;
1673 $subscriptionid = $dbh->quote($subscriptionid);
1674 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1675 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1676 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1678 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1683 DelIssue($serialseq,$subscriptionid)
1684 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1686 returns the number of rows affected
1691 my ($dataissue) = @_;
1692 my $dbh = C4::Context->dbh;
1693 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1698 AND subscriptionid= ?
1700 my $mainsth = $dbh->prepare($query);
1701 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1703 #Delete element from subscription history
1704 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1705 my $sth = $dbh->prepare($query);
1706 $sth->execute( $dataissue->{'subscriptionid'} );
1707 my $val = $sth->fetchrow_hashref;
1708 unless ( $val->{manualhistory} ) {
1710 SELECT * FROM subscriptionhistory
1711 WHERE subscriptionid= ?
1713 my $sth = $dbh->prepare($query);
1714 $sth->execute( $dataissue->{'subscriptionid'} );
1715 my $data = $sth->fetchrow_hashref;
1716 my $serialseq = $dataissue->{'serialseq'};
1717 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1718 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1719 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1720 $sth = $dbh->prepare($strsth);
1721 $sth->execute( $dataissue->{'subscriptionid'} );
1724 return $mainsth->rows;
1727 =head2 GetLateOrMissingIssues
1729 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1731 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1734 the issuelist as an array of hash refs. Each element of this array contains
1735 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1739 sub GetLateOrMissingIssues {
1740 my ( $supplierid, $serialid, $order ) = @_;
1741 my $dbh = C4::Context->dbh;
1745 $byserial = "and serialid = " . $serialid;
1748 $order .= ", title";
1753 $sth = $dbh->prepare(
1755 serialid, aqbooksellerid, name,
1756 biblio.title, planneddate, serialseq,
1757 serial.status, serial.subscriptionid, claimdate,
1758 subscription.branchcode
1760 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1761 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1762 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1763 WHERE subscription.subscriptionid = serial.subscriptionid
1764 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1765 AND subscription.aqbooksellerid=$supplierid
1770 $sth = $dbh->prepare(
1772 serialid, aqbooksellerid, name,
1773 biblio.title, planneddate, serialseq,
1774 serial.status, serial.subscriptionid, claimdate,
1775 subscription.branchcode
1777 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1778 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1779 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1780 WHERE subscription.subscriptionid = serial.subscriptionid
1781 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1788 while ( my $line = $sth->fetchrow_hashref ) {
1790 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1791 $line->{planneddate} = format_date( $line->{planneddate} );
1793 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1794 $line->{claimdate} = format_date( $line->{claimdate} );
1796 $line->{"status".$line->{status}} = 1;
1797 push @issuelist, $line;
1802 =head2 removeMissingIssue
1804 removeMissingIssue($subscriptionid)
1806 this function removes an issue from being part of the missing string in
1807 subscriptionlist.missinglist column
1809 called when a missing issue is found from the serials-recieve.pl file
1813 sub removeMissingIssue {
1814 my ( $sequence, $subscriptionid ) = @_;
1815 my $dbh = C4::Context->dbh;
1816 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1817 $sth->execute($subscriptionid);
1818 my $data = $sth->fetchrow_hashref;
1819 my $missinglist = $data->{'missinglist'};
1820 my $missinglistbefore = $missinglist;
1822 # warn $missinglist." before";
1823 $missinglist =~ s/($sequence)//;
1825 # warn $missinglist." after";
1826 if ( $missinglist ne $missinglistbefore ) {
1827 $missinglist =~ s/\|\s\|/\|/g;
1828 $missinglist =~ s/^\| //g;
1829 $missinglist =~ s/\|$//g;
1830 my $sth2 = $dbh->prepare(
1831 "UPDATE subscriptionhistory
1833 WHERE subscriptionid = ?"
1835 $sth2->execute( $missinglist, $subscriptionid );
1842 &updateClaim($serialid)
1844 this function updates the time when a claim is issued for late/missing items
1846 called from claims.pl file
1851 my ($serialid) = @_;
1852 my $dbh = C4::Context->dbh;
1853 my $sth = $dbh->prepare(
1854 "UPDATE serial SET claimdate = now()
1858 $sth->execute($serialid);
1862 =head2 getsupplierbyserialid
1864 $result = getsupplierbyserialid($serialid)
1866 this function is used to find the supplier id given a serial id
1869 hashref containing serialid, subscriptionid, and aqbooksellerid
1873 sub getsupplierbyserialid {
1874 my ($serialid) = @_;
1875 my $dbh = C4::Context->dbh;
1876 my $sth = $dbh->prepare(
1877 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1879 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1883 $sth->execute($serialid);
1884 my $line = $sth->fetchrow_hashref;
1885 my $result = $line->{'aqbooksellerid'};
1889 =head2 check_routing
1891 $result = &check_routing($subscriptionid)
1893 this function checks to see if a serial has a routing list and returns the count of routingid
1894 used to show either an 'add' or 'edit' link
1899 my ($subscriptionid) = @_;
1900 my $dbh = C4::Context->dbh;
1901 my $sth = $dbh->prepare(
1902 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
1903 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1904 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1907 $sth->execute($subscriptionid);
1908 my $line = $sth->fetchrow_hashref;
1909 my $result = $line->{'routingids'};
1913 =head2 addroutingmember
1915 addroutingmember($borrowernumber,$subscriptionid)
1917 this function takes a borrowernumber and subscriptionid and adds the member to the
1918 routing list for that serial subscription and gives them a rank on the list
1919 of either 1 or highest current rank + 1
1923 sub addroutingmember {
1924 my ( $borrowernumber, $subscriptionid ) = @_;
1926 my $dbh = C4::Context->dbh;
1927 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1928 $sth->execute($subscriptionid);
1929 while ( my $line = $sth->fetchrow_hashref ) {
1930 if ( $line->{'rank'} > 0 ) {
1931 $rank = $line->{'rank'} + 1;
1936 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1937 $sth->execute( $subscriptionid, $borrowernumber, $rank );
1940 =head2 reorder_members
1942 reorder_members($subscriptionid,$routingid,$rank)
1944 this function is used to reorder the routing list
1946 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1947 - it gets all members on list puts their routingid's into an array
1948 - removes the one in the array that is $routingid
1949 - then reinjects $routingid at point indicated by $rank
1950 - then update the database with the routingids in the new order
1954 sub reorder_members {
1955 my ( $subscriptionid, $routingid, $rank ) = @_;
1956 my $dbh = C4::Context->dbh;
1957 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1958 $sth->execute($subscriptionid);
1960 while ( my $line = $sth->fetchrow_hashref ) {
1961 push( @result, $line->{'routingid'} );
1964 # To find the matching index
1966 my $key = -1; # to allow for 0 being a valid response
1967 for ( $i = 0 ; $i < @result ; $i++ ) {
1968 if ( $routingid == $result[$i] ) {
1969 $key = $i; # save the index
1974 # if index exists in array then move it to new position
1975 if ( $key > -1 && $rank > 0 ) {
1976 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1977 my $moving_item = splice( @result, $key, 1 );
1978 splice( @result, $new_rank, 0, $moving_item );
1980 for ( my $j = 0 ; $j < @result ; $j++ ) {
1981 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1987 =head2 delroutingmember
1989 delroutingmember($routingid,$subscriptionid)
1991 this function either deletes one member from routing list if $routingid exists otherwise
1992 deletes all members from the routing list
1996 sub delroutingmember {
1998 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
1999 my ( $routingid, $subscriptionid ) = @_;
2000 my $dbh = C4::Context->dbh;
2002 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2003 $sth->execute($routingid);
2004 reorder_members( $subscriptionid, $routingid );
2006 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2007 $sth->execute($subscriptionid);
2012 =head2 getroutinglist
2014 @routinglist = getroutinglist($subscriptionid)
2016 this gets the info from the subscriptionroutinglist for $subscriptionid
2019 the routinglist as an array. Each element of the array contains a hash_ref containing
2020 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2024 sub getroutinglist {
2025 my ($subscriptionid) = @_;
2026 my $dbh = C4::Context->dbh;
2027 my $sth = $dbh->prepare(
2028 'SELECT routingid, borrowernumber, ranking, biblionumber
2030 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2031 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2033 $sth->execute($subscriptionid);
2034 my $routinglist = $sth->fetchall_arrayref({});
2035 return @{$routinglist};
2038 =head2 countissuesfrom
2040 $result = countissuesfrom($subscriptionid,$startdate)
2042 Returns a count of serial rows matching the given subsctiptionid
2043 with published date greater than startdate
2047 sub countissuesfrom {
2048 my ( $subscriptionid, $startdate ) = @_;
2049 my $dbh = C4::Context->dbh;
2053 WHERE subscriptionid=?
2054 AND serial.publisheddate>?
2056 my $sth = $dbh->prepare($query);
2057 $sth->execute( $subscriptionid, $startdate );
2058 my ($countreceived) = $sth->fetchrow;
2059 return $countreceived;
2064 $result = CountIssues($subscriptionid)
2066 Returns a count of serial rows matching the given subsctiptionid
2071 my ($subscriptionid) = @_;
2072 my $dbh = C4::Context->dbh;
2076 WHERE subscriptionid=?
2078 my $sth = $dbh->prepare($query);
2079 $sth->execute($subscriptionid);
2080 my ($countreceived) = $sth->fetchrow;
2081 return $countreceived;
2086 $result = HasItems($subscriptionid)
2088 returns a count of items from serial matching the subscriptionid
2093 my ($subscriptionid) = @_;
2094 my $dbh = C4::Context->dbh;
2096 SELECT COUNT(serialitems.itemnumber)
2098 LEFT JOIN serialitems USING(serialid)
2099 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2101 my $sth=$dbh->prepare($query);
2102 $sth->execute($subscriptionid);
2103 my ($countitems)=$sth->fetchrow_array();
2107 =head2 abouttoexpire
2109 $result = abouttoexpire($subscriptionid)
2111 this function alerts you to the penultimate issue for a serial subscription
2113 returns 1 - if this is the penultimate issue
2119 my ($subscriptionid) = @_;
2120 my $dbh = C4::Context->dbh;
2121 my $subscription = GetSubscription($subscriptionid);
2122 my $per = $subscription->{'periodicity'};
2123 if ($per && $per % 16 > 0){
2124 my $expirationdate = GetExpirationDate($subscriptionid);
2125 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2128 @res=split (/-/,$res);
2129 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2130 } else { # default an undefined value
2131 @res=Date::Calc::Today;
2133 my @endofsubscriptiondate=split(/-/,$expirationdate);
2134 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2136 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2137 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2138 return 1 if ( @res &&
2140 Delta_Days($res[0],$res[1],$res[2],
2141 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2142 (@endofsubscriptiondate &&
2143 Delta_Days($res[0],$res[1],$res[2],
2144 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2146 } elsif ($subscription->{numberlength}>0) {
2147 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2152 sub in_array { # used in next sub down
2153 my ( $val, @elements ) = @_;
2154 foreach my $elem (@elements) {
2155 if ( $val == $elem ) {
2164 $resultdate = GetNextDate($planneddate,$subscription)
2166 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2167 exists an irregularity
2168 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2169 skipped then the returned date will be 2007-05-10
2172 $resultdate - then next date in the sequence
2174 Return 0 if periodicity==0
2178 sub GetNextDate(@) {
2179 my ( $planneddate, $subscription ) = @_;
2180 my @irreg = split( /\,/, $subscription->{irregularity} );
2182 #date supposed to be in ISO.
2184 my ( $year, $month, $day ) = split( /-/, $planneddate );
2185 $month = 1 unless ($month);
2186 $day = 1 unless ($day);
2189 # warn "DOW $dayofweek";
2190 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2195 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2196 # renaming this pattern from 1/day to " n / week ".
2197 if ( $subscription->{periodicity} == 1 ) {
2198 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2199 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2201 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2202 $dayofweek = 0 if ( $dayofweek == 7 );
2203 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2204 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2208 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2213 if ( $subscription->{periodicity} == 2 ) {
2214 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2215 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2217 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2219 #FIXME: if two consecutive irreg, do we only skip one?
2220 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2221 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2222 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2225 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2230 if ( $subscription->{periodicity} == 3 ) {
2231 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2232 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2234 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2235 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2236 ### BUGFIX was previously +1 ^
2237 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2238 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2241 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2246 if ( $subscription->{periodicity} == 4 ) {
2247 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2248 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2250 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2251 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2252 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2253 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2256 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2259 my $tmpmonth = $month;
2260 if ( $year && $month && $day ) {
2261 if ( $subscription->{periodicity} == 5 ) {
2262 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2263 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2264 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2265 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2268 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2270 if ( $subscription->{periodicity} == 6 ) {
2271 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2272 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2273 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2274 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2277 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2279 if ( $subscription->{periodicity} == 7 ) {
2280 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2281 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2282 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2283 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2286 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2288 if ( $subscription->{periodicity} == 8 ) {
2289 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2290 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2291 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2292 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2295 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2297 if ( $subscription->{periodicity} == 13 ) {
2298 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2299 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2300 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2301 $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2304 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2306 if ( $subscription->{periodicity} == 9 ) {
2307 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2308 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2309 ### BUFIX Seems to need more Than One ?
2310 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2311 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2314 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2316 if ( $subscription->{periodicity} == 10 ) {
2317 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2319 if ( $subscription->{periodicity} == 11 ) {
2320 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2323 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2325 return "$resultdate";
2328 =head2 is_barcode_in_use
2330 Returns number of occurence of the barcode in the items table
2331 Can be used as a boolean test of whether the barcode has
2332 been deployed as yet
2336 sub is_barcode_in_use {
2337 my $barcode = shift;
2338 my $dbh = C4::Context->dbh;
2339 my $occurences = $dbh->selectall_arrayref(
2340 'SELECT itemnumber from items where barcode = ?',
2345 return @{$occurences};
2353 Koha Development Team <http://koha-community.org/>