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);
33 use C4::Log; # logaction
36 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
39 $VERSION = 3.01; # set version for version checking
43 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
44 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
45 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
46 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
48 &GetNextSeq &NewIssue &ItemizeSerials &GetSerials
49 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
50 &ReNewSubscription &GetLateIssues &GetLateOrMissingIssues
51 &GetSerialInformation &AddItem2Serial
52 &PrepareSerialsData &GetNextExpected &ModNextExpected
54 &UpdateClaimdateIssues
55 &GetSuppliersWithLateIssues &getsupplierbyserialid
56 &GetDistributedTo &SetDistributedTo
57 &getroutinglist &delroutingmember &addroutingmember
59 &check_routing &updateClaim &removeMissingIssue
68 C4::Serials - Serials Module Functions
76 Functions for handling subscriptions, claims routing etc.
81 =head2 GetSuppliersWithLateIssues
83 $supplierlist = GetSuppliersWithLateIssues()
85 this function get all suppliers with late issues.
88 an array_ref of suppliers each entry is a hash_ref containing id and name
89 the array is in name order
93 sub GetSuppliersWithLateIssues {
94 my $dbh = C4::Context->dbh;
96 SELECT DISTINCT id, name
98 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
99 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
100 WHERE id > 0 AND ((planneddate < now() AND serial.status=1) OR serial.STATUS = 3 OR serial.STATUS = 4) ORDER BY name|;
101 return $dbh->selectall_arrayref($query, { Slice => {} });
106 @issuelist = GetLateIssues($supplierid)
108 this function selects late issues from the database
111 the issuelist as an array. Each element of this array contains a hashi_ref containing
112 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
117 my ($supplierid) = @_;
118 my $dbh = C4::Context->dbh;
122 SELECT name,title,planneddate,serialseq,serial.subscriptionid
124 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
125 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
126 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
127 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
128 AND subscription.aqbooksellerid=?
131 $sth = $dbh->prepare($query);
132 $sth->execute($supplierid);
135 SELECT name,title,planneddate,serialseq,serial.subscriptionid
137 LEFT JOIN serial ON subscription.subscriptionid = serial.subscriptionid
138 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
139 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
140 WHERE ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3)
143 $sth = $dbh->prepare($query);
149 while ( my $line = $sth->fetchrow_hashref ) {
150 $odd++ unless $line->{title} eq $last_title;
151 $line->{title} = "" if $line->{title} eq $last_title;
152 $last_title = $line->{title} if ( $line->{title} );
153 $line->{planneddate} = format_date( $line->{planneddate} );
154 push @issuelist, $line;
159 =head2 GetSubscriptionHistoryFromSubscriptionId
161 $sth = GetSubscriptionHistoryFromSubscriptionId()
162 this function prepares the SQL request and returns the statement handle
163 After this function, don't forget to execute it by using $sth->execute($subscriptionid)
167 sub GetSubscriptionHistoryFromSubscriptionId() {
168 my $dbh = C4::Context->dbh;
171 FROM subscriptionhistory
172 WHERE subscriptionid = ?
174 return $dbh->prepare($query);
177 =head2 GetSerialStatusFromSerialId
179 $sth = GetSerialStatusFromSerialId();
180 this function returns a statement handle
181 After this function, don't forget to execute it by using $sth->execute($serialid)
183 $sth = $dbh->prepare($query).
187 sub GetSerialStatusFromSerialId() {
188 my $dbh = C4::Context->dbh;
194 return $dbh->prepare($query);
197 =head2 GetSerialInformation
200 $data = GetSerialInformation($serialid);
201 returns a hash_ref containing :
202 items : items marcrecord (can be an array)
204 subscription table field
205 + information about subscription expiration
209 sub GetSerialInformation {
211 my $dbh = C4::Context->dbh;
213 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid |;
214 if ( C4::Context->preference('IndependantBranches')
215 && C4::Context->userenv
216 && C4::Context->userenv->{'flags'} != 1
217 && C4::Context->userenv->{'branch'} ) {
219 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
222 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
225 my $rq = $dbh->prepare($query);
226 $rq->execute($serialid);
227 my $data = $rq->fetchrow_hashref;
229 # create item information if we have serialsadditems for this subscription
230 if ( $data->{'serialsadditems'} ) {
231 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
232 $queryitem->execute($serialid);
233 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
234 if ( scalar(@$itemnumbers) > 0 ) {
235 foreach my $itemnum (@$itemnumbers) {
237 #It is ASSUMED that GetMarcItem ALWAYS WORK...
238 #Maybe GetMarcItem should return values on failure
239 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
240 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
241 $itemprocessed->{'itemnumber'} = $itemnum->[0];
242 $itemprocessed->{'itemid'} = $itemnum->[0];
243 $itemprocessed->{'serialid'} = $serialid;
244 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
245 push @{ $data->{'items'} }, $itemprocessed;
248 my $itemprocessed = PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
249 $itemprocessed->{'itemid'} = "N$serialid";
250 $itemprocessed->{'serialid'} = $serialid;
251 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
252 $itemprocessed->{'countitems'} = 0;
253 push @{ $data->{'items'} }, $itemprocessed;
256 $data->{ "status" . $data->{'serstatus'} } = 1;
257 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
258 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
262 =head2 AddItem2Serial
264 $rows = AddItem2Serial($serialid,$itemnumber);
265 Adds an itemnumber to Serial record
266 returns the number of rows affected
271 my ( $serialid, $itemnumber ) = @_;
272 my $dbh = C4::Context->dbh;
273 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
274 $rq->execute( $serialid, $itemnumber );
278 =head2 UpdateClaimdateIssues
280 UpdateClaimdateIssues($serialids,[$date]);
282 Update Claimdate for issues in @$serialids list with date $date
287 sub UpdateClaimdateIssues {
288 my ( $serialids, $date ) = @_;
289 my $dbh = C4::Context->dbh;
290 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
292 UPDATE serial SET claimdate = ?, status = 7
293 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")";
294 my $rq = $dbh->prepare($query);
295 $rq->execute($date, @$serialids);
299 =head2 GetSubscription
301 $subs = GetSubscription($subscriptionid)
302 this function returns the subscription which has $subscriptionid as id.
304 a hashref. This hash containts
305 subscription, subscriptionhistory, aqbudget.bookfundid, biblio.title
309 sub GetSubscription {
310 my ($subscriptionid) = @_;
311 my $dbh = C4::Context->dbh;
313 SELECT subscription.*,
314 subscriptionhistory.*,
315 aqbooksellers.name AS aqbooksellername,
316 biblio.title AS bibliotitle,
317 subscription.biblionumber as bibnum);
318 if ( C4::Context->preference('IndependantBranches')
319 && C4::Context->userenv
320 && C4::Context->userenv->{'flags'} != 1
321 && C4::Context->userenv->{'branch'} ) {
323 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
327 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
328 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
329 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
330 WHERE subscription.subscriptionid = ?
333 # if (C4::Context->preference('IndependantBranches') &&
334 # C4::Context->userenv &&
335 # C4::Context->userenv->{'flags'} != 1){
336 # # $debug and warn "flags: ".C4::Context->userenv->{'flags'};
337 # $query.=" AND subscription.branchcode IN ('".C4::Context->userenv->{'branch'}."',\"\")";
339 $debug and warn "query : $query\nsubsid :$subscriptionid";
340 my $sth = $dbh->prepare($query);
341 $sth->execute($subscriptionid);
342 return $sth->fetchrow_hashref;
345 =head2 GetFullSubscription
347 $array_ref = GetFullSubscription($subscriptionid)
348 this function reads the serial table.
352 sub GetFullSubscription {
353 my ($subscriptionid) = @_;
354 my $dbh = C4::Context->dbh;
356 SELECT serial.serialid,
359 serial.publisheddate,
361 serial.notes as notes,
362 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
363 aqbooksellers.name as aqbooksellername,
364 biblio.title as bibliotitle,
365 subscription.branchcode AS branchcode,
366 subscription.subscriptionid AS subscriptionid |;
367 if ( C4::Context->preference('IndependantBranches')
368 && C4::Context->userenv
369 && C4::Context->userenv->{'flags'} != 1
370 && C4::Context->userenv->{'branch'} ) {
372 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
376 LEFT JOIN subscription ON
377 (serial.subscriptionid=subscription.subscriptionid )
378 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
379 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
380 WHERE serial.subscriptionid = ?
382 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
383 serial.subscriptionid
385 $debug and warn "GetFullSubscription query: $query";
386 my $sth = $dbh->prepare($query);
387 $sth->execute($subscriptionid);
388 return $sth->fetchall_arrayref( {} );
391 =head2 PrepareSerialsData
393 $array_ref = PrepareSerialsData($serialinfomation)
394 where serialinformation is a hashref array
398 sub PrepareSerialsData {
404 my $aqbooksellername;
408 my $previousnote = "";
410 foreach my $subs (@{$lines}) {
411 for my $datefield ( qw(publisheddate planneddate) ) {
412 # handle both undef and undef returned as 0000-00-00
413 if (!defined $subs->{$datefield} or $subs->{$datefield}=~m/^00/) {
414 $subs->{$datefield} = 'XXX';
417 $subs->{$datefield} = format_date( $subs->{$datefield} );
420 $subs->{'branchname'} = GetBranchName( $subs->{'branchcode'} );
421 $subs->{ "status" . $subs->{'status'} } = 1;
422 $subs->{"checked"} = $subs->{'status'} =~ /1|3|4|7/;
424 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
425 $year = $subs->{'year'};
429 if ( $tmpresults{$year} ) {
430 push @{ $tmpresults{$year}->{'serials'} }, $subs;
432 $tmpresults{$year} = {
434 'aqbooksellername' => $subs->{'aqbooksellername'},
435 'bibliotitle' => $subs->{'bibliotitle'},
436 'serials' => [$subs],
441 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
442 push @res, $tmpresults{$key};
447 =head2 GetSubscriptionsFromBiblionumber
449 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
450 this function get the subscription list. it reads the subscription table.
452 reference to an array of subscriptions which have the biblionumber given on input arg.
453 each element of this array is a hashref containing
454 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
458 sub GetSubscriptionsFromBiblionumber {
459 my ($biblionumber) = @_;
460 my $dbh = C4::Context->dbh;
462 SELECT subscription.*,
464 subscriptionhistory.*,
465 aqbooksellers.name AS aqbooksellername,
466 biblio.title AS bibliotitle
468 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
469 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
470 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
471 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
472 WHERE subscription.biblionumber = ?
474 my $sth = $dbh->prepare($query);
475 $sth->execute($biblionumber);
477 while ( my $subs = $sth->fetchrow_hashref ) {
478 $subs->{startdate} = format_date( $subs->{startdate} );
479 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
480 $subs->{histenddate} = format_date( $subs->{histenddate} );
481 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
482 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
483 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
484 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
485 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
486 $subs->{ "status" . $subs->{'status'} } = 1;
487 $subs->{'cannotedit'} =
488 ( C4::Context->preference('IndependantBranches')
489 && C4::Context->userenv
490 && C4::Context->userenv->{flags} % 2 != 1
491 && C4::Context->userenv->{branch}
492 && $subs->{branchcode}
493 && ( C4::Context->userenv->{branch} ne $subs->{branchcode} ) );
495 if ( $subs->{enddate} eq '0000-00-00' ) {
496 $subs->{enddate} = '';
498 $subs->{enddate} = format_date( $subs->{enddate} );
500 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
501 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
507 =head2 GetFullSubscriptionsFromBiblionumber
509 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
510 this function reads the serial table.
514 sub GetFullSubscriptionsFromBiblionumber {
515 my ($biblionumber) = @_;
516 my $dbh = C4::Context->dbh;
518 SELECT serial.serialid,
521 serial.publisheddate,
523 serial.notes as notes,
524 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
525 biblio.title as bibliotitle,
526 subscription.branchcode AS branchcode,
527 subscription.subscriptionid AS subscriptionid|;
528 if ( C4::Context->preference('IndependantBranches')
529 && C4::Context->userenv
530 && C4::Context->userenv->{'flags'} != 1
531 && C4::Context->userenv->{'branch'} ) {
533 , ((subscription.branchcode <>\"" . C4::Context->userenv->{'branch'} . "\") and subscription.branchcode <>\"\" and subscription.branchcode IS NOT NULL) as cannotedit ";
538 LEFT JOIN subscription ON
539 (serial.subscriptionid=subscription.subscriptionid)
540 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
541 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
542 WHERE subscription.biblionumber = ?
544 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
545 serial.subscriptionid
547 my $sth = $dbh->prepare($query);
548 $sth->execute($biblionumber);
549 return $sth->fetchall_arrayref( {} );
552 =head2 GetSubscriptions
554 @results = GetSubscriptions($title,$ISSN,$biblionumber);
555 this function gets all subscriptions which have title like $title,ISSN like $ISSN and biblionumber like $biblionumber.
557 a table of hashref. Each hash containt the subscription.
561 sub GetSubscriptions {
562 my ( $string, $issn, $biblionumber ) = @_;
564 #return unless $title or $ISSN or $biblionumber;
565 my $dbh = C4::Context->dbh;
568 SELECT subscription.*, subscriptionhistory.*, biblio.title,biblioitems.issn,biblio.biblionumber
570 LEFT JOIN subscriptionhistory USING(subscriptionid)
571 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
572 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
577 $sqlwhere = " WHERE biblio.biblionumber=?";
578 push @bind_params, $biblionumber;
582 my @strings_to_search;
583 @strings_to_search = map { "%$_%" } split( / /, $string );
584 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
585 push @bind_params, @strings_to_search;
586 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
587 $debug && warn "$tmpstring";
588 $tmpstring =~ s/^AND //;
589 push @sqlstrings, $tmpstring;
591 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
595 my @strings_to_search;
596 @strings_to_search = map { "%$_%" } split( / /, $issn );
597 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
598 push @bind_params, @strings_to_search;
599 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
600 $debug && warn "$tmpstring";
601 $tmpstring =~ s/^OR //;
602 push @sqlstrings, $tmpstring;
604 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
606 $sql .= "$sqlwhere ORDER BY title";
607 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
608 $sth = $dbh->prepare($sql);
609 $sth->execute(@bind_params);
612 while ( my $line = $sth->fetchrow_hashref ) {
613 $line->{'cannotedit'} =
614 ( C4::Context->preference('IndependantBranches')
615 && C4::Context->userenv
616 && C4::Context->userenv->{flags} % 2 != 1
617 && C4::Context->userenv->{branch}
618 && $line->{branchcode}
619 && ( C4::Context->userenv->{branch} ne $line->{branchcode} ) );
620 push @results, $line;
627 ($totalissues,@serials) = GetSerials($subscriptionid);
628 this function gets every serial not arrived for a given subscription
629 as well as the number of issues registered in the database (all types)
630 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
632 FIXME: We should return \@serials.
637 my ( $subscriptionid, $count ) = @_;
638 my $dbh = C4::Context->dbh;
640 # status = 2 is "arrived"
642 $count = 5 unless ($count);
644 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
646 WHERE subscriptionid = ? AND status NOT IN (2,4,5)
647 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
648 my $sth = $dbh->prepare($query);
649 $sth->execute($subscriptionid);
651 while ( my $line = $sth->fetchrow_hashref ) {
652 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
653 for my $datefield ( qw( planneddate publisheddate) ) {
654 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
655 $line->{$datefield} = format_date( $line->{$datefield});
657 $line->{$datefield} = q{};
660 push @serials, $line;
663 # OK, now add the last 5 issues arrives/missing
664 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
666 WHERE subscriptionid = ?
667 AND (status in (2,4,5))
668 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
670 $sth = $dbh->prepare($query);
671 $sth->execute($subscriptionid);
672 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
674 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
675 for my $datefield ( qw( planneddate publisheddate) ) {
676 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
677 $line->{$datefield} = format_date( $line->{$datefield});
679 $line->{$datefield} = q{};
683 push @serials, $line;
686 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
687 $sth = $dbh->prepare($query);
688 $sth->execute($subscriptionid);
689 my ($totalissues) = $sth->fetchrow;
690 return ( $totalissues, @serials );
695 @serials = GetSerials2($subscriptionid,$status);
696 this function returns every serial waited for a given subscription
697 as well as the number of issues registered in the database (all types)
698 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
703 my ( $subscription, $status ) = @_;
704 my $dbh = C4::Context->dbh;
706 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
708 WHERE subscriptionid=$subscription AND status IN ($status)
709 ORDER BY publisheddate,serialid DESC
711 $debug and warn "GetSerials2 query: $query";
712 my $sth = $dbh->prepare($query);
716 while ( my $line = $sth->fetchrow_hashref ) {
717 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
718 # Format dates for display
719 for my $datefield ( qw( planneddate publisheddate ) ) {
720 if ($line->{$datefield} =~m/^00/) {
721 $line->{$datefield} = q{};
724 $line->{$datefield} = format_date( $line->{$datefield} );
727 push @serials, $line;
732 =head2 GetLatestSerials
734 \@serials = GetLatestSerials($subscriptionid,$limit)
735 get the $limit's latest serials arrived or missing for a given subscription
737 a ref to an array which contains all of the latest serials stored into a hash.
741 sub GetLatestSerials {
742 my ( $subscriptionid, $limit ) = @_;
743 my $dbh = C4::Context->dbh;
745 # status = 2 is "arrived"
746 my $strsth = "SELECT serialid,serialseq, status, planneddate, notes
748 WHERE subscriptionid = ?
749 AND (status =2 or status=4)
750 ORDER BY planneddate DESC LIMIT 0,$limit
752 my $sth = $dbh->prepare($strsth);
753 $sth->execute($subscriptionid);
755 while ( my $line = $sth->fetchrow_hashref ) {
756 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
757 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
758 push @serials, $line;
764 =head2 GetDistributedTo
766 $distributedto=GetDistributedTo($subscriptionid)
767 This function returns the field distributedto for the subscription matching subscriptionid
771 sub GetDistributedTo {
772 my $dbh = C4::Context->dbh;
774 my $subscriptionid = @_;
775 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
776 my $sth = $dbh->prepare($query);
777 $sth->execute($subscriptionid);
778 return ($distributedto) = $sth->fetchrow;
784 $val is a hashref containing all the attributes of the table 'subscription'
785 This function get the next issue for the subscription given on input arg
787 a list containing all the input params updated.
793 # my ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
794 # $calculated = $val->{numberingmethod};
795 # # calculate the (expected) value of the next issue recieved.
796 # $newlastvalue1 = $val->{lastvalue1};
797 # # check if we have to increase the new value.
798 # $newinnerloop1 = $val->{innerloop1}+1;
799 # $newinnerloop1=0 if ($newinnerloop1 >= $val->{every1});
800 # $newlastvalue1 += $val->{add1} if ($newinnerloop1<1); # <1 to be true when 0 or empty.
801 # $newlastvalue1=$val->{setto1} if ($newlastvalue1>$val->{whenmorethan1}); # reset counter if needed.
802 # $calculated =~ s/\{X\}/$newlastvalue1/g;
804 # $newlastvalue2 = $val->{lastvalue2};
805 # # check if we have to increase the new value.
806 # $newinnerloop2 = $val->{innerloop2}+1;
807 # $newinnerloop2=0 if ($newinnerloop2 >= $val->{every2});
808 # $newlastvalue2 += $val->{add2} if ($newinnerloop2<1); # <1 to be true when 0 or empty.
809 # $newlastvalue2=$val->{setto2} if ($newlastvalue2>$val->{whenmorethan2}); # reset counter if needed.
810 # $calculated =~ s/\{Y\}/$newlastvalue2/g;
812 # $newlastvalue3 = $val->{lastvalue3};
813 # # check if we have to increase the new value.
814 # $newinnerloop3 = $val->{innerloop3}+1;
815 # $newinnerloop3=0 if ($newinnerloop3 >= $val->{every3});
816 # $newlastvalue3 += $val->{add3} if ($newinnerloop3<1); # <1 to be true when 0 or empty.
817 # $newlastvalue3=$val->{setto3} if ($newlastvalue3>$val->{whenmorethan3}); # reset counter if needed.
818 # $calculated =~ s/\{Z\}/$newlastvalue3/g;
819 # return ($calculated,$newlastvalue1,$newlastvalue2,$newlastvalue3,$newinnerloop1,$newinnerloop2,$newinnerloop3);
824 my ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
825 my $pattern = $val->{numberpattern};
826 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
827 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
828 $calculated = $val->{numberingmethod};
829 $newlastvalue1 = $val->{lastvalue1};
830 $newlastvalue2 = $val->{lastvalue2};
831 $newlastvalue3 = $val->{lastvalue3};
832 $newlastvalue1 = $val->{lastvalue1};
834 # check if we have to increase the new value.
835 $newinnerloop1 = $val->{innerloop1} + 1;
836 $newinnerloop1 = 0 if ( $newinnerloop1 >= $val->{every1} );
837 $newlastvalue1 += $val->{add1} if ( $newinnerloop1 < 1 ); # <1 to be true when 0 or empty.
838 $newlastvalue1 = $val->{setto1} if ( $newlastvalue1 > $val->{whenmorethan1} ); # reset counter if needed.
839 $calculated =~ s/\{X\}/$newlastvalue1/g;
841 $newlastvalue2 = $val->{lastvalue2};
843 # check if we have to increase the new value.
844 $newinnerloop2 = $val->{innerloop2} + 1;
845 $newinnerloop2 = 0 if ( $newinnerloop2 >= $val->{every2} );
846 $newlastvalue2 += $val->{add2} if ( $newinnerloop2 < 1 ); # <1 to be true when 0 or empty.
847 $newlastvalue2 = $val->{setto2} if ( $newlastvalue2 > $val->{whenmorethan2} ); # reset counter if needed.
848 if ( $pattern == 6 ) {
849 if ( $val->{hemisphere} == 2 ) {
850 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
851 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
853 my $newlastvalue2seq = $seasons[$newlastvalue2];
854 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
857 $calculated =~ s/\{Y\}/$newlastvalue2/g;
860 $newlastvalue3 = $val->{lastvalue3};
862 # check if we have to increase the new value.
863 $newinnerloop3 = $val->{innerloop3} + 1;
864 $newinnerloop3 = 0 if ( $newinnerloop3 >= $val->{every3} );
865 $newlastvalue3 += $val->{add3} if ( $newinnerloop3 < 1 ); # <1 to be true when 0 or empty.
866 $newlastvalue3 = $val->{setto3} if ( $newlastvalue3 > $val->{whenmorethan3} ); # reset counter if needed.
867 $calculated =~ s/\{Z\}/$newlastvalue3/g;
869 return ( $calculated, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 );
874 $calculated = GetSeq($val)
875 $val is a hashref containing all the attributes of the table 'subscription'
876 this function transforms {X},{Y},{Z} to 150,0,0 for example.
878 the sequence in integer format
884 my $pattern = $val->{numberpattern};
885 my @seasons = ( 'nothing', 'Winter', 'Spring', 'Summer', 'Autumn' );
886 my @southern_seasons = ( '', 'Summer', 'Autumn', 'Winter', 'Spring' );
887 my $calculated = $val->{numberingmethod};
888 my $x = $val->{'lastvalue1'};
889 $calculated =~ s/\{X\}/$x/g;
890 my $newlastvalue2 = $val->{'lastvalue2'};
892 if ( $pattern == 6 ) {
893 if ( $val->{hemisphere} == 2 ) {
894 my $newlastvalue2seq = $southern_seasons[$newlastvalue2];
895 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
897 my $newlastvalue2seq = $seasons[$newlastvalue2];
898 $calculated =~ s/\{Y\}/$newlastvalue2seq/g;
901 $calculated =~ s/\{Y\}/$newlastvalue2/g;
903 my $z = $val->{'lastvalue3'};
904 $calculated =~ s/\{Z\}/$z/g;
908 =head2 GetExpirationDate
910 $enddate = GetExpirationDate($subscriptionid, [$startdate])
912 this function return the next expiration date for a subscription given on input args.
919 sub GetExpirationDate {
920 my ( $subscriptionid, $startdate ) = @_;
921 my $dbh = C4::Context->dbh;
922 my $subscription = GetSubscription($subscriptionid);
925 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
926 $enddate = $startdate || $subscription->{startdate};
927 my @date = split( /-/, $enddate );
928 return if ( scalar(@date) != 3 || not check_date(@date) );
929 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
932 if ( my $length = $subscription->{numberlength} ) {
934 #calculate the date of the last issue.
935 for ( my $i = 1 ; $i <= $length ; $i++ ) {
936 $enddate = GetNextDate( $enddate, $subscription );
938 } elsif ( $subscription->{monthlength} ) {
939 if ( $$subscription{startdate} ) {
940 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
941 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
943 } elsif ( $subscription->{weeklength} ) {
944 if ( $$subscription{startdate} ) {
945 my @date = split( /-/, $subscription->{startdate} );
946 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
947 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
956 =head2 CountSubscriptionFromBiblionumber
958 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
959 this returns a count of the subscriptions for a given biblionumber
961 the number of subscriptions
965 sub CountSubscriptionFromBiblionumber {
966 my ($biblionumber) = @_;
967 my $dbh = C4::Context->dbh;
968 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
969 my $sth = $dbh->prepare($query);
970 $sth->execute($biblionumber);
971 my $subscriptionsnumber = $sth->fetchrow;
972 return $subscriptionsnumber;
975 =head2 ModSubscriptionHistory
977 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
979 this function modifies the history of a subscription. Put your new values on input arg.
980 returns the number of rows affected
984 sub ModSubscriptionHistory {
985 my ( $subscriptionid, $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote ) = @_;
986 my $dbh = C4::Context->dbh;
987 my $query = "UPDATE subscriptionhistory
988 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
989 WHERE subscriptionid=?
991 my $sth = $dbh->prepare($query);
992 $recievedlist =~ s/^; //;
993 $missinglist =~ s/^; //;
994 $opacnote =~ s/^; //;
995 $sth->execute( $histstartdate, $enddate, $recievedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
999 =head2 ModSerialStatus
1001 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1003 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1004 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1008 sub ModSerialStatus {
1009 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1011 #It is a usual serial
1012 # 1st, get previous status :
1013 my $dbh = C4::Context->dbh;
1014 my $query = "SELECT subscriptionid,status FROM serial WHERE serialid=?";
1015 my $sth = $dbh->prepare($query);
1016 $sth->execute($serialid);
1017 my ( $subscriptionid, $oldstatus ) = $sth->fetchrow;
1019 # change status & update subscriptionhistory
1021 if ( $status == 6 ) {
1022 DelIssue( {'serialid'=>$serialid, 'subscriptionid'=>$subscriptionid,'serialseq'=>$serialseq} );
1026 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1027 $sth = $dbh->prepare($query);
1028 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1029 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1030 $sth = $dbh->prepare($query);
1031 $sth->execute($subscriptionid);
1032 my $val = $sth->fetchrow_hashref;
1033 unless ( $val->{manualhistory} ) {
1034 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1035 $sth = $dbh->prepare($query);
1036 $sth->execute($subscriptionid);
1037 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1038 if ( $status == 2 ) {
1040 $recievedlist .= "; $serialseq"
1041 unless ( index( "$recievedlist", "$serialseq" ) >= 0 );
1044 # warn "missinglist : $missinglist serialseq :$serialseq, ".index("$missinglist","$serialseq");
1045 $missinglist .= "; $serialseq"
1047 and not index( "$missinglist", "$serialseq" ) >= 0 );
1048 $missinglist .= "; not issued $serialseq"
1050 and index( "$missinglist", "$serialseq" ) >= 0 );
1051 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1052 $sth = $dbh->prepare($query);
1053 $recievedlist =~ s/^; //;
1054 $missinglist =~ s/^; //;
1055 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1059 # create new waited entry if needed (ie : was a "waited" and has changed)
1060 if ( $oldstatus == 1 && $status != 1 ) {
1061 my $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1062 $sth = $dbh->prepare($query);
1063 $sth->execute($subscriptionid);
1064 my $val = $sth->fetchrow_hashref;
1068 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1069 $newinnerloop1, $newinnerloop2, $newinnerloop3
1070 ) = GetNextSeq($val);
1072 # next date (calculated from actual date & frequency parameters)
1073 my $nextpublisheddate = GetNextDate( $publisheddate, $val );
1074 NewIssue( $newserialseq, $subscriptionid, $val->{'biblionumber'}, 1, $nextpublisheddate, $nextpublisheddate );
1075 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1076 WHERE subscriptionid = ?";
1077 $sth = $dbh->prepare($query);
1078 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1080 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1081 if ( $val->{letter} && $status == 2 && $oldstatus != 2 ) {
1082 SendAlerts( 'issue', $val->{subscriptionid}, $val->{letter} );
1088 =head2 GetNextExpected
1090 $nextexpected = GetNextExpected($subscriptionid)
1092 Get the planneddate for the current expected issue of the subscription.
1098 planneddate => C4::Dates object
1103 sub GetNextExpected($) {
1104 my ($subscriptionid) = @_;
1105 my $dbh = C4::Context->dbh;
1106 my $sth = $dbh->prepare('SELECT serialid, planneddate FROM serial WHERE subscriptionid=? AND status=?');
1108 # Each subscription has only one 'expected' issue, with serial.status==1.
1109 $sth->execute( $subscriptionid, 1 );
1110 my ( $nextissue ) = $sth->fetchrow_hashref;
1112 $sth = $dbh->prepare('SELECT serialid,planneddate FROM serial WHERE subscriptionid = ? ORDER BY planneddate DESC LIMIT 1');
1113 $sth->execute( $subscriptionid );
1114 $nextissue = $sth->fetchrow_hashref;
1116 if (!defined $nextissue->{planneddate}) {
1117 # or should this default to 1st Jan ???
1118 $nextissue->{planneddate} = strftime('%Y-%m-%d',localtime);
1120 $nextissue->{planneddate} = C4::Dates->new($nextissue->{planneddate},'iso');
1125 =head2 ModNextExpected
1127 ModNextExpected($subscriptionid,$date)
1129 Update the planneddate for the current expected issue of the subscription.
1130 This will modify all future prediction results.
1132 C<$date> is a C4::Dates object.
1138 sub ModNextExpected($$) {
1139 my ( $subscriptionid, $date ) = @_;
1140 my $dbh = C4::Context->dbh;
1142 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1143 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1145 # Each subscription has only one 'expected' issue, with serial.status==1.
1146 $sth->execute( $date->output('iso'), $date->output('iso'), $subscriptionid, 1 );
1151 =head2 ModSubscription
1153 this function modifies a subscription. Put all new values on input args.
1154 returns the number of rows affected
1158 sub ModSubscription {
1159 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1160 $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $add1, $every1,
1161 $whenmorethan1, $setto1, $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2,
1162 $lastvalue2, $innerloop2, $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1163 $numberingmethod, $status, $biblionumber, $callnumber, $notes, $letter, $hemisphere, $manualhistory,
1164 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid
1167 # warn $irregularity;
1168 my $dbh = C4::Context->dbh;
1169 my $query = "UPDATE subscription
1170 SET librarian=?, branchcode=?,aqbooksellerid=?,cost=?,aqbudgetid=?,startdate=?,
1171 periodicity=?,firstacquidate=?,dow=?,irregularity=?, numberpattern=?, numberlength=?,weeklength=?,monthlength=?,
1172 add1=?,every1=?,whenmorethan1=?,setto1=?,lastvalue1=?,innerloop1=?,
1173 add2=?,every2=?,whenmorethan2=?,setto2=?,lastvalue2=?,innerloop2=?,
1174 add3=?,every3=?,whenmorethan3=?,setto3=?,lastvalue3=?,innerloop3=?,
1175 numberingmethod=?, status=?, biblionumber=?, callnumber=?, notes=?,
1176 letter=?, hemisphere=?,manualhistory=?,internalnotes=?,serialsadditems=?,
1177 staffdisplaycount = ?,opacdisplaycount = ?, graceperiod = ?, location = ?
1179 WHERE subscriptionid = ?";
1181 #warn "query :".$query;
1182 my $sth = $dbh->prepare($query);
1184 $auser, $branchcode, $aqbooksellerid, $cost,
1185 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1186 $dow, "$irregularity", $numberpattern, $numberlength,
1187 $weeklength, $monthlength, $add1, $every1,
1188 $whenmorethan1, $setto1, $lastvalue1, $innerloop1,
1189 $add2, $every2, $whenmorethan2, $setto2,
1190 $lastvalue2, $innerloop2, $add3, $every3,
1191 $whenmorethan3, $setto3, $lastvalue3, $innerloop3,
1192 $numberingmethod, $status, $biblionumber, $callnumber,
1193 $notes, $letter, $hemisphere, ( $manualhistory ? $manualhistory : 0 ),
1194 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1195 $graceperiod, $location, $enddate, $subscriptionid
1197 my $rows = $sth->rows;
1199 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1203 =head2 NewSubscription
1205 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1206 $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
1207 $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
1208 $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
1209 $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
1210 $numberingmethod, $status, $notes, $serialsadditems,
1211 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate);
1213 Create a new subscription with value given on input args.
1216 the id of this new subscription
1220 sub NewSubscription {
1221 my ($auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1222 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1223 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1224 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, $status,
1225 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1226 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1228 my $dbh = C4::Context->dbh;
1230 #save subscription (insert into database)
1232 INSERT INTO subscription
1233 (librarian,branchcode,aqbooksellerid,cost,aqbudgetid,biblionumber,
1234 startdate,periodicity,dow,numberlength,weeklength,monthlength,
1235 add1,every1,whenmorethan1,setto1,lastvalue1,innerloop1,
1236 add2,every2,whenmorethan2,setto2,lastvalue2,innerloop2,
1237 add3,every3,whenmorethan3,setto3,lastvalue3,innerloop3,
1238 numberingmethod, status, notes, letter,firstacquidate,irregularity,
1239 numberpattern, callnumber, hemisphere,manualhistory,internalnotes,serialsadditems,
1240 staffdisplaycount,opacdisplaycount,graceperiod,location,enddate)
1241 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1243 my $sth = $dbh->prepare($query);
1245 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, $startdate, $periodicity,
1246 $dow, $numberlength, $weeklength, $monthlength, $add1, $every1, $whenmorethan1, $setto1,
1247 $lastvalue1, $innerloop1, $add2, $every2, $whenmorethan2, $setto2, $lastvalue2, $innerloop2,
1248 $add3, $every3, $whenmorethan3, $setto3, $lastvalue3, $innerloop3, $numberingmethod, "$status",
1249 $notes, $letter, $firstacquidate, $irregularity, $numberpattern, $callnumber, $hemisphere, $manualhistory,
1250 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate
1253 my $subscriptionid = $dbh->{'mysql_insertid'};
1255 $enddate = GetExpirationDate($subscriptionid,$startdate);
1259 WHERE subscriptionid=?
1261 $sth = $dbh->prepare($query);
1262 $sth->execute( $enddate, $subscriptionid );
1264 #then create the 1st waited number
1266 INSERT INTO subscriptionhistory
1267 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1270 $sth = $dbh->prepare($query);
1271 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1273 # reread subscription to get a hash (for calculation of the 1st issue number)
1277 WHERE subscriptionid = ?
1279 $sth = $dbh->prepare($query);
1280 $sth->execute($subscriptionid);
1281 my $val = $sth->fetchrow_hashref;
1283 # calculate issue number
1284 my $serialseq = GetSeq($val);
1287 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1288 VALUES (?,?,?,?,?,?)
1290 $sth = $dbh->prepare($query);
1291 $sth->execute( "$serialseq", $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1293 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1295 #set serial flag on biblio if not already set.
1296 my ( $null, ($bib) ) = GetBiblio($biblionumber);
1297 if ( !$bib->{'serial'} ) {
1298 my $record = GetMarcBiblio($biblionumber);
1299 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1301 eval { $record->field($tag)->update( $subf => 1 ); };
1303 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1305 return $subscriptionid;
1308 =head2 ReNewSubscription
1310 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1312 this function renew a subscription with values given on input args.
1316 sub ReNewSubscription {
1317 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1318 my $dbh = C4::Context->dbh;
1319 my $subscription = GetSubscription($subscriptionid);
1323 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1324 WHERE biblio.biblionumber=?
1326 my $sth = $dbh->prepare($query);
1327 $sth->execute( $subscription->{biblionumber} );
1328 my $biblio = $sth->fetchrow_hashref;
1330 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1333 { 'suggestedby' => $user,
1334 'title' => $subscription->{bibliotitle},
1335 'author' => $biblio->{author},
1336 'publishercode' => $biblio->{publishercode},
1337 'note' => $biblio->{note},
1338 'biblionumber' => $subscription->{biblionumber}
1343 # renew subscription
1346 SET startdate=?,numberlength=?,weeklength=?,monthlength=?
1347 WHERE subscriptionid=?
1349 $sth = $dbh->prepare($query);
1350 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1351 my $enddate = GetExpirationDate($subscriptionid);
1352 $debug && warn "enddate :$enddate";
1356 WHERE subscriptionid=?
1358 $sth = $dbh->prepare($query);
1359 $sth->execute( $enddate, $subscriptionid );
1361 UPDATE subscriptionhistory
1363 WHERE subscriptionid=?
1365 $sth = $dbh->prepare($query);
1366 $sth->execute( $enddate, $subscriptionid );
1368 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1374 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1376 Create a new issue stored on the database.
1377 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1378 returns the serial id
1383 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1384 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1386 my $dbh = C4::Context->dbh;
1389 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1390 VALUES (?,?,?,?,?,?,?)
1392 my $sth = $dbh->prepare($query);
1393 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1394 my $serialid = $dbh->{'mysql_insertid'};
1396 SELECT missinglist,recievedlist
1397 FROM subscriptionhistory
1398 WHERE subscriptionid=?
1400 $sth = $dbh->prepare($query);
1401 $sth->execute($subscriptionid);
1402 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1404 if ( $status == 2 ) {
1405 ### TODO Add a feature that improves recognition and description.
1406 ### As such count (serialseq) i.e. : N18,2(N19),N20
1407 ### Would use substr and index But be careful to previous presence of ()
1408 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1410 if ( $status == 4 ) {
1411 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1414 UPDATE subscriptionhistory
1415 SET recievedlist=?, missinglist=?
1416 WHERE subscriptionid=?
1418 $sth = $dbh->prepare($query);
1419 $recievedlist =~ s/^; //;
1420 $missinglist =~ s/^; //;
1421 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1425 =head2 ItemizeSerials
1427 ItemizeSerials($serialid, $info);
1428 $info is a hashref containing barcode branch, itemcallnumber, status, location
1429 $serialid the serialid
1431 1 if the itemize is a succes.
1432 0 and @error otherwise. @error containts the list of errors found.
1436 sub ItemizeSerials {
1437 my ( $serialid, $info ) = @_;
1438 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1440 my $dbh = C4::Context->dbh;
1446 my $sth = $dbh->prepare($query);
1447 $sth->execute($serialid);
1448 my $data = $sth->fetchrow_hashref;
1449 if ( C4::Context->preference("RoutingSerials") ) {
1451 # check for existing biblioitem relating to serial issue
1452 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1454 for ( my $i = 0 ; $i < $count ; $i++ ) {
1455 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1456 $bibitemno = $results[$i]->{'biblioitemnumber'};
1460 if ( $bibitemno == 0 ) {
1461 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1462 $sth->execute( $data->{'biblionumber'} );
1463 my $biblioitem = $sth->fetchrow_hashref;
1464 $biblioitem->{'volumedate'} = $data->{planneddate};
1465 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1466 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1470 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1471 if ( $info->{barcode} ) {
1473 if ( is_barcode_in_use( $info->{barcode} ) ) {
1474 push @errors, 'barcode_not_unique';
1476 my $marcrecord = MARC::Record->new();
1477 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1478 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1479 $marcrecord->insert_fields_ordered($newField);
1480 if ( $info->{branch} ) {
1481 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1483 #warn "items.homebranch : $tag , $subfield";
1484 if ( $marcrecord->field($tag) ) {
1485 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1487 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1488 $marcrecord->insert_fields_ordered($newField);
1490 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1492 #warn "items.holdingbranch : $tag , $subfield";
1493 if ( $marcrecord->field($tag) ) {
1494 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1496 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1497 $marcrecord->insert_fields_ordered($newField);
1500 if ( $info->{itemcallnumber} ) {
1501 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1503 if ( $marcrecord->field($tag) ) {
1504 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1506 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1507 $marcrecord->insert_fields_ordered($newField);
1510 if ( $info->{notes} ) {
1511 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1513 if ( $marcrecord->field($tag) ) {
1514 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1516 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1517 $marcrecord->insert_fields_ordered($newField);
1520 if ( $info->{location} ) {
1521 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1523 if ( $marcrecord->field($tag) ) {
1524 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1526 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1527 $marcrecord->insert_fields_ordered($newField);
1530 if ( $info->{status} ) {
1531 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1533 if ( $marcrecord->field($tag) ) {
1534 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1536 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1537 $marcrecord->insert_fields_ordered($newField);
1540 if ( C4::Context->preference("RoutingSerials") ) {
1541 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1542 if ( $marcrecord->field($tag) ) {
1543 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1545 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1546 $marcrecord->insert_fields_ordered($newField);
1549 AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1552 return ( 0, @errors );
1556 =head2 HasSubscriptionStrictlyExpired
1558 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1560 the subscription has stricly expired when today > the end subscription date
1563 1 if true, 0 if false, -1 if the expiration date is not set.
1567 sub HasSubscriptionStrictlyExpired {
1569 # Getting end of subscription date
1570 my ($subscriptionid) = @_;
1571 my $dbh = C4::Context->dbh;
1572 my $subscription = GetSubscription($subscriptionid);
1573 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1575 # If the expiration date is set
1576 if ( $expirationdate != 0 ) {
1577 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1579 # Getting today's date
1580 my ( $nowyear, $nowmonth, $nowday ) = Today();
1582 # if today's date > expiration date, then the subscription has stricly expired
1583 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1590 # There are some cases where the expiration date is not set
1591 # As we can't determine if the subscription has expired on a date-basis,
1597 =head2 HasSubscriptionExpired
1599 $has_expired = HasSubscriptionExpired($subscriptionid)
1601 the subscription has expired when the next issue to arrive is out of subscription limit.
1604 0 if the subscription has not expired
1605 1 if the subscription has expired
1606 2 if has subscription does not have a valid expiration date set
1610 sub HasSubscriptionExpired {
1611 my ($subscriptionid) = @_;
1612 my $dbh = C4::Context->dbh;
1613 my $subscription = GetSubscription($subscriptionid);
1614 if ( ( $subscription->{periodicity} % 16 ) > 0 ) {
1615 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1616 if (!defined $expirationdate) {
1617 $expirationdate = q{};
1620 SELECT max(planneddate)
1622 WHERE subscriptionid=?
1624 my $sth = $dbh->prepare($query);
1625 $sth->execute($subscriptionid);
1626 my ($res) = $sth->fetchrow;
1627 if (!$res || $res=~m/^0000/) {
1630 my @res = split( /-/, $res );
1631 my @endofsubscriptiondate = split( /-/, $expirationdate );
1632 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1634 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1638 if ( $subscription->{'numberlength'} ) {
1639 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1640 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1646 return 0; # Notice that you'll never get here.
1649 =head2 SetDistributedto
1651 SetDistributedto($distributedto,$subscriptionid);
1652 This function update the value of distributedto for a subscription given on input arg.
1656 sub SetDistributedto {
1657 my ( $distributedto, $subscriptionid ) = @_;
1658 my $dbh = C4::Context->dbh;
1662 WHERE subscriptionid=?
1664 my $sth = $dbh->prepare($query);
1665 $sth->execute( $distributedto, $subscriptionid );
1669 =head2 DelSubscription
1671 DelSubscription($subscriptionid)
1672 this function deletes subscription which has $subscriptionid as id.
1676 sub DelSubscription {
1677 my ($subscriptionid) = @_;
1678 my $dbh = C4::Context->dbh;
1679 $subscriptionid = $dbh->quote($subscriptionid);
1680 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1681 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1682 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1684 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1689 DelIssue($serialseq,$subscriptionid)
1690 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1692 returns the number of rows affected
1697 my ($dataissue) = @_;
1698 my $dbh = C4::Context->dbh;
1699 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1704 AND subscriptionid= ?
1706 my $mainsth = $dbh->prepare($query);
1707 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1709 #Delete element from subscription history
1710 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1711 my $sth = $dbh->prepare($query);
1712 $sth->execute( $dataissue->{'subscriptionid'} );
1713 my $val = $sth->fetchrow_hashref;
1714 unless ( $val->{manualhistory} ) {
1716 SELECT * FROM subscriptionhistory
1717 WHERE subscriptionid= ?
1719 my $sth = $dbh->prepare($query);
1720 $sth->execute( $dataissue->{'subscriptionid'} );
1721 my $data = $sth->fetchrow_hashref;
1722 my $serialseq = $dataissue->{'serialseq'};
1723 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1724 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1725 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1726 $sth = $dbh->prepare($strsth);
1727 $sth->execute( $dataissue->{'subscriptionid'} );
1730 return $mainsth->rows;
1733 =head2 GetLateOrMissingIssues
1735 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1737 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1740 the issuelist as an array of hash refs. Each element of this array contains
1741 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1745 sub GetLateOrMissingIssues {
1746 my ( $supplierid, $serialid, $order ) = @_;
1747 my $dbh = C4::Context->dbh;
1751 $byserial = "and serialid = " . $serialid;
1754 $order .= ", title";
1759 $sth = $dbh->prepare(
1761 serialid, aqbooksellerid, name,
1762 biblio.title, planneddate, serialseq,
1763 serial.status, serial.subscriptionid, claimdate,
1764 subscription.branchcode
1766 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1767 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1768 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1769 WHERE subscription.subscriptionid = serial.subscriptionid
1770 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1771 AND subscription.aqbooksellerid=$supplierid
1776 $sth = $dbh->prepare(
1778 serialid, aqbooksellerid, name,
1779 biblio.title, planneddate, serialseq,
1780 serial.status, serial.subscriptionid, claimdate,
1781 subscription.branchcode
1783 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1784 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1785 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1786 WHERE subscription.subscriptionid = serial.subscriptionid
1787 AND (serial.STATUS = 4 OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1794 while ( my $line = $sth->fetchrow_hashref ) {
1796 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1797 $line->{planneddate} = format_date( $line->{planneddate} );
1799 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1800 $line->{claimdate} = format_date( $line->{claimdate} );
1802 $line->{"status".$line->{status}} = 1;
1803 push @issuelist, $line;
1808 =head2 removeMissingIssue
1810 removeMissingIssue($subscriptionid)
1812 this function removes an issue from being part of the missing string in
1813 subscriptionlist.missinglist column
1815 called when a missing issue is found from the serials-recieve.pl file
1819 sub removeMissingIssue {
1820 my ( $sequence, $subscriptionid ) = @_;
1821 my $dbh = C4::Context->dbh;
1822 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
1823 $sth->execute($subscriptionid);
1824 my $data = $sth->fetchrow_hashref;
1825 my $missinglist = $data->{'missinglist'};
1826 my $missinglistbefore = $missinglist;
1828 # warn $missinglist." before";
1829 $missinglist =~ s/($sequence)//;
1831 # warn $missinglist." after";
1832 if ( $missinglist ne $missinglistbefore ) {
1833 $missinglist =~ s/\|\s\|/\|/g;
1834 $missinglist =~ s/^\| //g;
1835 $missinglist =~ s/\|$//g;
1836 my $sth2 = $dbh->prepare(
1837 "UPDATE subscriptionhistory
1839 WHERE subscriptionid = ?"
1841 $sth2->execute( $missinglist, $subscriptionid );
1848 &updateClaim($serialid)
1850 this function updates the time when a claim is issued for late/missing items
1852 called from claims.pl file
1857 my ($serialid) = @_;
1858 my $dbh = C4::Context->dbh;
1859 my $sth = $dbh->prepare(
1860 "UPDATE serial SET claimdate = now()
1864 $sth->execute($serialid);
1868 =head2 getsupplierbyserialid
1870 $result = getsupplierbyserialid($serialid)
1872 this function is used to find the supplier id given a serial id
1875 hashref containing serialid, subscriptionid, and aqbooksellerid
1879 sub getsupplierbyserialid {
1880 my ($serialid) = @_;
1881 my $dbh = C4::Context->dbh;
1882 my $sth = $dbh->prepare(
1883 "SELECT serialid, serial.subscriptionid, aqbooksellerid
1885 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
1889 $sth->execute($serialid);
1890 my $line = $sth->fetchrow_hashref;
1891 my $result = $line->{'aqbooksellerid'};
1895 =head2 check_routing
1897 $result = &check_routing($subscriptionid)
1899 this function checks to see if a serial has a routing list and returns the count of routingid
1900 used to show either an 'add' or 'edit' link
1905 my ($subscriptionid) = @_;
1906 my $dbh = C4::Context->dbh;
1907 my $sth = $dbh->prepare(
1908 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
1909 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
1910 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
1913 $sth->execute($subscriptionid);
1914 my $line = $sth->fetchrow_hashref;
1915 my $result = $line->{'routingids'};
1919 =head2 addroutingmember
1921 addroutingmember($borrowernumber,$subscriptionid)
1923 this function takes a borrowernumber and subscriptionid and adds the member to the
1924 routing list for that serial subscription and gives them a rank on the list
1925 of either 1 or highest current rank + 1
1929 sub addroutingmember {
1930 my ( $borrowernumber, $subscriptionid ) = @_;
1932 my $dbh = C4::Context->dbh;
1933 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
1934 $sth->execute($subscriptionid);
1935 while ( my $line = $sth->fetchrow_hashref ) {
1936 if ( $line->{'rank'} > 0 ) {
1937 $rank = $line->{'rank'} + 1;
1942 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
1943 $sth->execute( $subscriptionid, $borrowernumber, $rank );
1946 =head2 reorder_members
1948 reorder_members($subscriptionid,$routingid,$rank)
1950 this function is used to reorder the routing list
1952 it takes the routingid of the member one wants to re-rank and the rank it is to move to
1953 - it gets all members on list puts their routingid's into an array
1954 - removes the one in the array that is $routingid
1955 - then reinjects $routingid at point indicated by $rank
1956 - then update the database with the routingids in the new order
1960 sub reorder_members {
1961 my ( $subscriptionid, $routingid, $rank ) = @_;
1962 my $dbh = C4::Context->dbh;
1963 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
1964 $sth->execute($subscriptionid);
1966 while ( my $line = $sth->fetchrow_hashref ) {
1967 push( @result, $line->{'routingid'} );
1970 # To find the matching index
1972 my $key = -1; # to allow for 0 being a valid response
1973 for ( $i = 0 ; $i < @result ; $i++ ) {
1974 if ( $routingid == $result[$i] ) {
1975 $key = $i; # save the index
1980 # if index exists in array then move it to new position
1981 if ( $key > -1 && $rank > 0 ) {
1982 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1983 my $moving_item = splice( @result, $key, 1 );
1984 splice( @result, $new_rank, 0, $moving_item );
1986 for ( my $j = 0 ; $j < @result ; $j++ ) {
1987 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
1993 =head2 delroutingmember
1995 delroutingmember($routingid,$subscriptionid)
1997 this function either deletes one member from routing list if $routingid exists otherwise
1998 deletes all members from the routing list
2002 sub delroutingmember {
2004 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2005 my ( $routingid, $subscriptionid ) = @_;
2006 my $dbh = C4::Context->dbh;
2008 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2009 $sth->execute($routingid);
2010 reorder_members( $subscriptionid, $routingid );
2012 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2013 $sth->execute($subscriptionid);
2018 =head2 getroutinglist
2020 @routinglist = getroutinglist($subscriptionid)
2022 this gets the info from the subscriptionroutinglist for $subscriptionid
2025 the routinglist as an array. Each element of the array contains a hash_ref containing
2026 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2030 sub getroutinglist {
2031 my ($subscriptionid) = @_;
2032 my $dbh = C4::Context->dbh;
2033 my $sth = $dbh->prepare(
2034 'SELECT routingid, borrowernumber, ranking, biblionumber
2036 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2037 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2039 $sth->execute($subscriptionid);
2040 my $routinglist = $sth->fetchall_arrayref({});
2041 return @{$routinglist};
2044 =head2 countissuesfrom
2046 $result = countissuesfrom($subscriptionid,$startdate)
2048 Returns a count of serial rows matching the given subsctiptionid
2049 with published date greater than startdate
2053 sub countissuesfrom {
2054 my ( $subscriptionid, $startdate ) = @_;
2055 my $dbh = C4::Context->dbh;
2059 WHERE subscriptionid=?
2060 AND serial.publisheddate>?
2062 my $sth = $dbh->prepare($query);
2063 $sth->execute( $subscriptionid, $startdate );
2064 my ($countreceived) = $sth->fetchrow;
2065 return $countreceived;
2070 $result = CountIssues($subscriptionid)
2072 Returns a count of serial rows matching the given subsctiptionid
2077 my ($subscriptionid) = @_;
2078 my $dbh = C4::Context->dbh;
2082 WHERE subscriptionid=?
2084 my $sth = $dbh->prepare($query);
2085 $sth->execute($subscriptionid);
2086 my ($countreceived) = $sth->fetchrow;
2087 return $countreceived;
2092 $result = HasItems($subscriptionid)
2094 returns a count of items from serial matching the subscriptionid
2099 my ($subscriptionid) = @_;
2100 my $dbh = C4::Context->dbh;
2102 SELECT COUNT(serialitems.itemnumber)
2104 LEFT JOIN serialitems USING(serialid)
2105 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2107 my $sth=$dbh->prepare($query);
2108 $sth->execute($subscriptionid);
2109 my ($countitems)=$sth->fetchrow_array();
2113 =head2 abouttoexpire
2115 $result = abouttoexpire($subscriptionid)
2117 this function alerts you to the penultimate issue for a serial subscription
2119 returns 1 - if this is the penultimate issue
2125 my ($subscriptionid) = @_;
2126 my $dbh = C4::Context->dbh;
2127 my $subscription = GetSubscription($subscriptionid);
2128 my $per = $subscription->{'periodicity'};
2129 if ($per && $per % 16 > 0){
2130 my $expirationdate = GetExpirationDate($subscriptionid);
2131 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2134 @res=split (/-/,$res);
2135 @res=Date::Calc::Today if ($res[0]*$res[1]==0);
2136 } else { # default an undefined value
2137 @res=Date::Calc::Today;
2139 my @endofsubscriptiondate=split(/-/,$expirationdate);
2140 my @per_list = (0, 7, 7, 14, 21, 31, 62, 93, 93, 190, 365, 730, 0, 124, 0, 0);
2142 @datebeforeend = Add_Delta_Days( $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2],
2143 - (3 * $per_list[$per])) if (@endofsubscriptiondate && $endofsubscriptiondate[0]*$endofsubscriptiondate[1]*$endofsubscriptiondate[2]);
2144 return 1 if ( @res &&
2146 Delta_Days($res[0],$res[1],$res[2],
2147 $datebeforeend[0],$datebeforeend[1],$datebeforeend[2]) <= 0) &&
2148 (@endofsubscriptiondate &&
2149 Delta_Days($res[0],$res[1],$res[2],
2150 $endofsubscriptiondate[0],$endofsubscriptiondate[1],$endofsubscriptiondate[2]) >= 0) );
2152 } elsif ($subscription->{numberlength}>0) {
2153 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2158 sub in_array { # used in next sub down
2159 my ( $val, @elements ) = @_;
2160 foreach my $elem (@elements) {
2161 if ( $val == $elem ) {
2170 $resultdate = GetNextDate($planneddate,$subscription)
2172 this function it takes the planneddate and will return the next issue's date and will skip dates if there
2173 exists an irregularity
2174 - eg if periodicity is monthly and $planneddate is 2007-02-10 but if March and April is to be
2175 skipped then the returned date will be 2007-05-10
2178 $resultdate - then next date in the sequence
2180 Return 0 if periodicity==0
2184 sub GetNextDate(@) {
2185 my ( $planneddate, $subscription ) = @_;
2186 my @irreg = split( /\,/, $subscription->{irregularity} );
2188 #date supposed to be in ISO.
2190 my ( $year, $month, $day ) = split( /-/, $planneddate );
2191 $month = 1 unless ($month);
2192 $day = 1 unless ($day);
2195 # warn "DOW $dayofweek";
2196 if ( $subscription->{periodicity} % 16 == 0 ) { # 'without regularity' || 'irregular'
2201 # Since we're interpreting irregularity here as which days of the week to skip an issue,
2202 # renaming this pattern from 1/day to " n / week ".
2203 if ( $subscription->{periodicity} == 1 ) {
2204 my $dayofweek = eval { Day_of_Week( $year, $month, $day ) };
2205 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2207 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2208 $dayofweek = 0 if ( $dayofweek == 7 );
2209 if ( in_array( ( $dayofweek + 1 ), @irreg ) ) {
2210 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 1 );
2214 @resultdate = Add_Delta_Days( $year, $month, $day, 1 );
2219 if ( $subscription->{periodicity} == 2 ) {
2220 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2221 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2223 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2225 #FIXME: if two consecutive irreg, do we only skip one?
2226 if ( $irreg[$i] == ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 ) ) {
2227 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 7 );
2228 $wkno = ( ( $wkno != 51 ) ? ( $wkno + 1 ) % 52 : 52 );
2231 @resultdate = Add_Delta_Days( $year, $month, $day, 7 );
2236 if ( $subscription->{periodicity} == 3 ) {
2237 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2238 if ($@) { warn "year month day : $year $month $day $subscription->{subscriptionid} : $@"; }
2240 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2241 if ( $irreg[$i] == ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 ) ) {
2242 ### BUGFIX was previously +1 ^
2243 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 14 );
2244 $wkno = ( ( $wkno != 50 ) ? ( $wkno + 2 ) % 52 : 52 );
2247 @resultdate = Add_Delta_Days( $year, $month, $day, 14 );
2252 if ( $subscription->{periodicity} == 4 ) {
2253 my ( $wkno, $year ) = eval { Week_of_Year( $year, $month, $day ) };
2254 if ($@) { warn "année mois jour : $year $month $day $subscription->{subscriptionid} : $@"; }
2256 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2257 if ( $irreg[$i] == ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 ) ) {
2258 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, 21 );
2259 $wkno = ( ( $wkno != 49 ) ? ( $wkno + 3 ) % 52 : 52 );
2262 @resultdate = Add_Delta_Days( $year, $month, $day, 21 );
2265 my $tmpmonth = $month;
2266 if ( $year && $month && $day ) {
2267 if ( $subscription->{periodicity} == 5 ) {
2268 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2269 if ( $irreg[$i] == ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 ) ) {
2270 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2271 $tmpmonth = ( ( $tmpmonth != 11 ) ? ( $tmpmonth + 1 ) % 12 : 12 );
2274 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 1, 0 );
2276 if ( $subscription->{periodicity} == 6 ) {
2277 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2278 if ( $irreg[$i] == ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 ) ) {
2279 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2280 $tmpmonth = ( ( $tmpmonth != 10 ) ? ( $tmpmonth + 2 ) % 12 : 12 );
2283 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 2, 0 );
2285 if ( $subscription->{periodicity} == 7 ) {
2286 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2287 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2288 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2289 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2292 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2294 if ( $subscription->{periodicity} == 8 ) {
2295 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2296 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2297 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2298 $tmpmonth = ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 );
2301 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 3, 0 );
2303 if ( $subscription->{periodicity} == 13 ) {
2304 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2305 if ( $irreg[$i] == ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 ) ) {
2306 ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2307 $tmpmonth = ( ( $tmpmonth != 8 ) ? ( $tmpmonth + 4 ) % 12 : 12 );
2310 @resultdate = Add_Delta_YMD( $year, $month, $day, 0, 4, 0 );
2312 if ( $subscription->{periodicity} == 9 ) {
2313 for ( my $i = 0 ; $i < @irreg ; $i++ ) {
2314 if ( $irreg[$i] == ( ( $tmpmonth != 9 ) ? ( $tmpmonth + 3 ) % 12 : 12 ) ) {
2315 ### BUFIX Seems to need more Than One ?
2316 ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, 6 );
2317 $tmpmonth = ( ( $tmpmonth != 6 ) ? ( $tmpmonth + 6 ) % 12 : 12 );
2320 @resultdate = Add_Delta_YM( $year, $month, $day, 0, 6 );
2322 if ( $subscription->{periodicity} == 10 ) {
2323 @resultdate = Add_Delta_YM( $year, $month, $day, 1, 0 );
2325 if ( $subscription->{periodicity} == 11 ) {
2326 @resultdate = Add_Delta_YM( $year, $month, $day, 2, 0 );
2329 my $resultdate = sprintf( "%04d-%02d-%02d", $resultdate[0], $resultdate[1], $resultdate[2] );
2331 return "$resultdate";
2334 =head2 is_barcode_in_use
2336 Returns number of occurence of the barcode in the items table
2337 Can be used as a boolean test of whether the barcode has
2338 been deployed as yet
2342 sub is_barcode_in_use {
2343 my $barcode = shift;
2344 my $dbh = C4::Context->dbh;
2345 my $occurences = $dbh->selectall_arrayref(
2346 'SELECT itemnumber from items where barcode = ?',
2351 return @{$occurences};
2359 Koha Development Team <http://koha-community.org/>