Bug 13189 - Patron card creator patron search browse by last name broken by extended...
[koha.git] / C4 / Serials.pm
blob49325cb277ecf260e1a4ac347951b15f3a62acbc
1 package C4::Serials;
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
11 # version.
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.
21 use Modern::Perl;
23 use C4::Auth qw(haspermission);
24 use C4::Context;
25 use C4::Dates qw(format_date format_date_in_iso);
26 use DateTime;
27 use Date::Calc qw(:all);
28 use POSIX qw(strftime);
29 use C4::Biblio;
30 use C4::Log; # logaction
31 use C4::Debug;
32 use C4::Serials::Frequency;
33 use C4::Serials::Numberpattern;
35 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
37 BEGIN {
38 $VERSION = 3.07.00.049; # set version for version checking
39 require Exporter;
40 @ISA = qw(Exporter);
41 @EXPORT = qw(
42 &NewSubscription &ModSubscription &DelSubscription &GetSubscriptions
43 &GetSubscription &CountSubscriptionFromBiblionumber &GetSubscriptionsFromBiblionumber
44 &SearchSubscriptions
45 &GetFullSubscriptionsFromBiblionumber &GetFullSubscription &ModSubscriptionHistory
46 &HasSubscriptionStrictlyExpired &HasSubscriptionExpired &GetExpirationDate &abouttoexpire
47 &GetSubscriptionHistoryFromSubscriptionId
49 &GetNextSeq &GetSeq &NewIssue &ItemizeSerials &GetSerials
50 &GetLatestSerials &ModSerialStatus &GetNextDate &GetSerials2
51 &ReNewSubscription &GetLateOrMissingIssues
52 &GetSerialInformation &AddItem2Serial
53 &PrepareSerialsData &GetNextExpected &ModNextExpected
55 &UpdateClaimdateIssues
56 &GetSuppliersWithLateIssues &getsupplierbyserialid
57 &GetDistributedTo &SetDistributedTo
58 &getroutinglist &delroutingmember &addroutingmember
59 &reorder_members
60 &check_routing &updateClaim &removeMissingIssue
61 &CountIssues
62 HasItems
63 &GetSubscriptionsFromBorrower
64 &subscriptionCurrentlyOnOrder
69 =head1 NAME
71 C4::Serials - Serials Module Functions
73 =head1 SYNOPSIS
75 use C4::Serials;
77 =head1 DESCRIPTION
79 Functions for handling subscriptions, claims routing etc.
82 =head1 SUBROUTINES
84 =head2 GetSuppliersWithLateIssues
86 $supplierlist = GetSuppliersWithLateIssues()
88 this function get all suppliers with late issues.
90 return :
91 an array_ref of suppliers each entry is a hash_ref containing id and name
92 the array is in name order
94 =cut
96 sub GetSuppliersWithLateIssues {
97 my $dbh = C4::Context->dbh;
98 my $query = qq|
99 SELECT DISTINCT id, name
100 FROM subscription
101 LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid
102 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
103 WHERE id > 0
104 AND (
105 (planneddate < now() AND serial.status=1)
106 OR serial.STATUS IN (3, 4, 41, 42, 43, 44, 7)
108 AND subscription.closed = 0
109 ORDER BY name|;
110 return $dbh->selectall_arrayref($query, { Slice => {} });
113 =head2 GetSubscriptionHistoryFromSubscriptionId
115 $history = GetSubscriptionHistoryFromSubscriptionId($subscriptionid);
117 This function returns the subscription history as a hashref
119 =cut
121 sub GetSubscriptionHistoryFromSubscriptionId {
122 my ($subscriptionid) = @_;
124 return unless $subscriptionid;
126 my $dbh = C4::Context->dbh;
127 my $query = qq|
128 SELECT *
129 FROM subscriptionhistory
130 WHERE subscriptionid = ?
132 my $sth = $dbh->prepare($query);
133 $sth->execute($subscriptionid);
134 my $results = $sth->fetchrow_hashref;
135 $sth->finish;
137 return $results;
140 =head2 GetSerialStatusFromSerialId
142 $sth = GetSerialStatusFromSerialId();
143 this function returns a statement handle
144 After this function, don't forget to execute it by using $sth->execute($serialid)
145 return :
146 $sth = $dbh->prepare($query).
148 =cut
150 sub GetSerialStatusFromSerialId {
151 my $dbh = C4::Context->dbh;
152 my $query = qq|
153 SELECT status
154 FROM serial
155 WHERE serialid = ?
157 return $dbh->prepare($query);
160 =head2 GetSerialInformation
163 $data = GetSerialInformation($serialid);
164 returns a hash_ref containing :
165 items : items marcrecord (can be an array)
166 serial table field
167 subscription table field
168 + information about subscription expiration
170 =cut
172 sub GetSerialInformation {
173 my ($serialid) = @_;
174 my $dbh = C4::Context->dbh;
175 my $query = qq|
176 SELECT serial.*, serial.notes as sernotes, serial.status as serstatus,subscription.*,subscription.subscriptionid as subsid
177 FROM serial LEFT JOIN subscription ON subscription.subscriptionid=serial.subscriptionid
178 WHERE serialid = ?
180 my $rq = $dbh->prepare($query);
181 $rq->execute($serialid);
182 my $data = $rq->fetchrow_hashref;
184 # create item information if we have serialsadditems for this subscription
185 if ( $data->{'serialsadditems'} ) {
186 my $queryitem = $dbh->prepare("SELECT itemnumber from serialitems where serialid=?");
187 $queryitem->execute($serialid);
188 my $itemnumbers = $queryitem->fetchall_arrayref( [0] );
189 require C4::Items;
190 if ( scalar(@$itemnumbers) > 0 ) {
191 foreach my $itemnum (@$itemnumbers) {
193 #It is ASSUMED that GetMarcItem ALWAYS WORK...
194 #Maybe GetMarcItem should return values on failure
195 $debug and warn "itemnumber :$itemnum->[0], bibnum :" . $data->{'biblionumber'};
196 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data );
197 $itemprocessed->{'itemnumber'} = $itemnum->[0];
198 $itemprocessed->{'itemid'} = $itemnum->[0];
199 $itemprocessed->{'serialid'} = $serialid;
200 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
201 push @{ $data->{'items'} }, $itemprocessed;
203 } else {
204 my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, '', $data );
205 $itemprocessed->{'itemid'} = "N$serialid";
206 $itemprocessed->{'serialid'} = $serialid;
207 $itemprocessed->{'biblionumber'} = $data->{'biblionumber'};
208 $itemprocessed->{'countitems'} = 0;
209 push @{ $data->{'items'} }, $itemprocessed;
212 $data->{ "status" . $data->{'serstatus'} } = 1;
213 $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1;
214 $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} );
215 $data->{cannotedit} = not can_edit_subscription( $data );
216 return $data;
219 =head2 AddItem2Serial
221 $rows = AddItem2Serial($serialid,$itemnumber);
222 Adds an itemnumber to Serial record
223 returns the number of rows affected
225 =cut
227 sub AddItem2Serial {
228 my ( $serialid, $itemnumber ) = @_;
230 return unless ($serialid and $itemnumber);
232 my $dbh = C4::Context->dbh;
233 my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?");
234 $rq->execute( $serialid, $itemnumber );
235 return $rq->rows;
238 =head2 UpdateClaimdateIssues
240 UpdateClaimdateIssues($serialids,[$date]);
242 Update Claimdate for issues in @$serialids list with date $date
243 (Take Today if none)
245 =cut
247 sub UpdateClaimdateIssues {
248 my ( $serialids, $date ) = @_;
250 return unless ($serialids);
252 my $dbh = C4::Context->dbh;
253 $date = strftime( "%Y-%m-%d", localtime ) unless ($date);
254 my $query = "
255 UPDATE serial
256 SET claimdate = ?,
257 status = 7,
258 claims_count = claims_count + 1
259 WHERE serialid in (" . join( ",", map { '?' } @$serialids ) . ")
261 my $rq = $dbh->prepare($query);
262 $rq->execute($date, @$serialids);
263 return $rq->rows;
266 =head2 GetSubscription
268 $subs = GetSubscription($subscriptionid)
269 this function returns the subscription which has $subscriptionid as id.
270 return :
271 a hashref. This hash containts
272 subscription, subscriptionhistory, aqbooksellers.name, biblio.title
274 =cut
276 sub GetSubscription {
277 my ($subscriptionid) = @_;
278 my $dbh = C4::Context->dbh;
279 my $query = qq(
280 SELECT subscription.*,
281 subscriptionhistory.*,
282 aqbooksellers.name AS aqbooksellername,
283 biblio.title AS bibliotitle,
284 subscription.biblionumber as bibnum
285 FROM subscription
286 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
287 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
288 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
289 WHERE subscription.subscriptionid = ?
292 $debug and warn "query : $query\nsubsid :$subscriptionid";
293 my $sth = $dbh->prepare($query);
294 $sth->execute($subscriptionid);
295 my $subscription = $sth->fetchrow_hashref;
296 $subscription->{cannotedit} = not can_edit_subscription( $subscription );
297 return $subscription;
300 =head2 GetFullSubscription
302 $array_ref = GetFullSubscription($subscriptionid)
303 this function reads the serial table.
305 =cut
307 sub GetFullSubscription {
308 my ($subscriptionid) = @_;
310 return unless ($subscriptionid);
312 my $dbh = C4::Context->dbh;
313 my $query = qq|
314 SELECT serial.serialid,
315 serial.serialseq,
316 serial.planneddate,
317 serial.publisheddate,
318 serial.status,
319 serial.notes as notes,
320 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
321 aqbooksellers.name as aqbooksellername,
322 biblio.title as bibliotitle,
323 subscription.branchcode AS branchcode,
324 subscription.subscriptionid AS subscriptionid
325 FROM serial
326 LEFT JOIN subscription ON
327 (serial.subscriptionid=subscription.subscriptionid )
328 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
329 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
330 WHERE serial.subscriptionid = ?
331 ORDER BY year DESC,
332 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
333 serial.subscriptionid
335 $debug and warn "GetFullSubscription query: $query";
336 my $sth = $dbh->prepare($query);
337 $sth->execute($subscriptionid);
338 my $subscriptions = $sth->fetchall_arrayref( {} );
339 for my $subscription ( @$subscriptions ) {
340 $subscription->{cannotedit} = not can_edit_subscription( $subscription );
342 return $subscriptions;
345 =head2 PrepareSerialsData
347 $array_ref = PrepareSerialsData($serialinfomation)
348 where serialinformation is a hashref array
350 =cut
352 sub PrepareSerialsData {
353 my ($lines) = @_;
355 return unless ($lines);
357 my %tmpresults;
358 my $year;
359 my @res;
360 my $startdate;
361 my $aqbooksellername;
362 my $bibliotitle;
363 my @loopissues;
364 my $first;
365 my $previousnote = "";
367 foreach my $subs (@{$lines}) {
368 for my $datefield ( qw(publisheddate planneddate) ) {
369 # handle 0000-00-00 dates
370 if (defined $subs->{$datefield} and $subs->{$datefield} =~ m/^00/) {
371 $subs->{$datefield} = undef;
374 $subs->{ "status" . $subs->{'status'} } = 1;
375 if ( grep { $_ == $subs->{status} } qw( 1 3 4 41 42 43 44 7 ) ) {
376 $subs->{"checked"} = 1;
379 if ( $subs->{'year'} && $subs->{'year'} ne "" ) {
380 $year = $subs->{'year'};
381 } else {
382 $year = "manage";
384 if ( $tmpresults{$year} ) {
385 push @{ $tmpresults{$year}->{'serials'} }, $subs;
386 } else {
387 $tmpresults{$year} = {
388 'year' => $year,
389 'aqbooksellername' => $subs->{'aqbooksellername'},
390 'bibliotitle' => $subs->{'bibliotitle'},
391 'serials' => [$subs],
392 'first' => $first,
396 foreach my $key ( sort { $b cmp $a } keys %tmpresults ) {
397 push @res, $tmpresults{$key};
399 return \@res;
402 =head2 GetSubscriptionsFromBiblionumber
404 $array_ref = GetSubscriptionsFromBiblionumber($biblionumber)
405 this function get the subscription list. it reads the subscription table.
406 return :
407 reference to an array of subscriptions which have the biblionumber given on input arg.
408 each element of this array is a hashref containing
409 startdate, histstartdate,opacnote,missinglist,recievedlist,periodicity,status & enddate
411 =cut
413 sub GetSubscriptionsFromBiblionumber {
414 my ($biblionumber) = @_;
416 return unless ($biblionumber);
418 my $dbh = C4::Context->dbh;
419 my $query = qq(
420 SELECT subscription.*,
421 branches.branchname,
422 subscriptionhistory.*,
423 aqbooksellers.name AS aqbooksellername,
424 biblio.title AS bibliotitle
425 FROM subscription
426 LEFT JOIN subscriptionhistory ON subscription.subscriptionid=subscriptionhistory.subscriptionid
427 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
428 LEFT JOIN biblio ON biblio.biblionumber=subscription.biblionumber
429 LEFT JOIN branches ON branches.branchcode=subscription.branchcode
430 WHERE subscription.biblionumber = ?
432 my $sth = $dbh->prepare($query);
433 $sth->execute($biblionumber);
434 my @res;
435 while ( my $subs = $sth->fetchrow_hashref ) {
436 $subs->{startdate} = format_date( $subs->{startdate} );
437 $subs->{histstartdate} = format_date( $subs->{histstartdate} );
438 $subs->{histenddate} = format_date( $subs->{histenddate} );
439 $subs->{opacnote} =~ s/\n/\<br\/\>/g;
440 $subs->{missinglist} =~ s/\n/\<br\/\>/g;
441 $subs->{recievedlist} =~ s/\n/\<br\/\>/g;
442 $subs->{ "periodicity" . $subs->{periodicity} } = 1;
443 $subs->{ "numberpattern" . $subs->{numberpattern} } = 1;
444 $subs->{ "status" . $subs->{'status'} } = 1;
446 if ( $subs->{enddate} eq '0000-00-00' ) {
447 $subs->{enddate} = '';
448 } else {
449 $subs->{enddate} = format_date( $subs->{enddate} );
451 $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} );
452 $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} );
453 $subs->{cannotedit} = not can_edit_subscription( $subs );
454 push @res, $subs;
456 return \@res;
459 =head2 GetFullSubscriptionsFromBiblionumber
461 $array_ref = GetFullSubscriptionsFromBiblionumber($biblionumber)
462 this function reads the serial table.
464 =cut
466 sub GetFullSubscriptionsFromBiblionumber {
467 my ($biblionumber) = @_;
468 my $dbh = C4::Context->dbh;
469 my $query = qq|
470 SELECT serial.serialid,
471 serial.serialseq,
472 serial.planneddate,
473 serial.publisheddate,
474 serial.status,
475 serial.notes as notes,
476 year(IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate)) as year,
477 biblio.title as bibliotitle,
478 subscription.branchcode AS branchcode,
479 subscription.subscriptionid AS subscriptionid
480 FROM serial
481 LEFT JOIN subscription ON
482 (serial.subscriptionid=subscription.subscriptionid)
483 LEFT JOIN aqbooksellers on subscription.aqbooksellerid=aqbooksellers.id
484 LEFT JOIN biblio on biblio.biblionumber=subscription.biblionumber
485 WHERE subscription.biblionumber = ?
486 ORDER BY year DESC,
487 IF(serial.publisheddate="00-00-0000",serial.planneddate,serial.publisheddate) DESC,
488 serial.subscriptionid
490 my $sth = $dbh->prepare($query);
491 $sth->execute($biblionumber);
492 my $subscriptions = $sth->fetchall_arrayref( {} );
493 for my $subscription ( @$subscriptions ) {
494 $subscription->{cannotedit} = not can_edit_subscription( $subscription );
496 return $subscriptions;
499 =head2 GetSubscriptions
501 @results = GetSubscriptions($title,$ISSN,$ean,$biblionumber);
502 this function gets all subscriptions which have title like $title,ISSN like $ISSN,EAN like $ean and biblionumber like $biblionumber.
503 return:
504 a table of hashref. Each hash containt the subscription.
506 =cut
508 sub GetSubscriptions {
509 my ( $string, $issn, $ean, $biblionumber ) = @_;
511 #return unless $title or $ISSN or $biblionumber;
512 my $dbh = C4::Context->dbh;
513 my $sth;
514 my $sql = qq(
515 SELECT subscriptionhistory.*, subscription.*, biblio.title,biblioitems.issn,biblio.biblionumber
516 FROM subscription
517 LEFT JOIN subscriptionhistory USING(subscriptionid)
518 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
519 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
521 my @bind_params;
522 my $sqlwhere = q{};
523 if ($biblionumber) {
524 $sqlwhere = " WHERE biblio.biblionumber=?";
525 push @bind_params, $biblionumber;
527 if ($string) {
528 my @sqlstrings;
529 my @strings_to_search;
530 @strings_to_search = map { "%$_%" } split( / /, $string );
531 foreach my $index (qw(biblio.title subscription.callnumber subscription.location subscription.notes subscription.internalnotes)) {
532 push @bind_params, @strings_to_search;
533 my $tmpstring = "AND $index LIKE ? " x scalar(@strings_to_search);
534 $debug && warn "$tmpstring";
535 $tmpstring =~ s/^AND //;
536 push @sqlstrings, $tmpstring;
538 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
540 if ($issn) {
541 my @sqlstrings;
542 my @strings_to_search;
543 @strings_to_search = map { "%$_%" } split( / /, $issn );
544 foreach my $index ( qw(biblioitems.issn subscription.callnumber)) {
545 push @bind_params, @strings_to_search;
546 my $tmpstring = "OR $index LIKE ? " x scalar(@strings_to_search);
547 $debug && warn "$tmpstring";
548 $tmpstring =~ s/^OR //;
549 push @sqlstrings, $tmpstring;
551 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
553 if ($ean) {
554 my @sqlstrings;
555 my @strings_to_search;
556 @strings_to_search = map { "$_" } split( / /, $ean );
557 foreach my $index ( qw(biblioitems.ean) ) {
558 push @bind_params, @strings_to_search;
559 my $tmpstring = "OR $index = ? " x scalar(@strings_to_search);
560 $debug && warn "$tmpstring";
561 $tmpstring =~ s/^OR //;
562 push @sqlstrings, $tmpstring;
564 $sqlwhere .= ( $sqlwhere ? " AND " : " WHERE " ) . "((" . join( ") OR (", @sqlstrings ) . "))";
567 $sql .= "$sqlwhere ORDER BY title";
568 $debug and warn "GetSubscriptions query: $sql params : ", join( " ", @bind_params );
569 $sth = $dbh->prepare($sql);
570 $sth->execute(@bind_params);
571 my $subscriptions = $sth->fetchall_arrayref( {} );
572 for my $subscription ( @$subscriptions ) {
573 $subscription->{cannotedit} = not can_edit_subscription( $subscription );
575 return @$subscriptions;
578 =head2 SearchSubscriptions
580 @results = SearchSubscriptions($args);
582 This function returns a list of hashrefs, one for each subscription
583 that meets the conditions specified by the $args hashref.
585 The valid search fields are:
587 biblionumber
588 title
589 issn
591 callnumber
592 location
593 publisher
594 bookseller
595 branch
596 expiration_date
597 closed
599 The expiration_date search field is special; it specifies the maximum
600 subscription expiration date.
602 =cut
604 sub SearchSubscriptions {
605 my ( $args ) = @_;
607 my $query = qq{
608 SELECT
609 subscription.notes AS publicnotes,
610 subscription.*,
611 subscriptionhistory.*,
612 biblio.notes AS biblionotes,
613 biblio.title,
614 biblio.author,
615 biblioitems.issn
616 FROM subscription
617 LEFT JOIN subscriptionhistory USING(subscriptionid)
618 LEFT JOIN biblio ON biblio.biblionumber = subscription.biblionumber
619 LEFT JOIN biblioitems ON biblioitems.biblionumber = subscription.biblionumber
620 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
622 my @where_strs;
623 my @where_args;
624 if( $args->{biblionumber} ) {
625 push @where_strs, "biblio.biblionumber = ?";
626 push @where_args, $args->{biblionumber};
628 if( $args->{title} ){
629 my @words = split / /, $args->{title};
630 my (@strs, @args);
631 foreach my $word (@words) {
632 push @strs, "biblio.title LIKE ?";
633 push @args, "%$word%";
635 if (@strs) {
636 push @where_strs, '(' . join (' AND ', @strs) . ')';
637 push @where_args, @args;
640 if( $args->{issn} ){
641 push @where_strs, "biblioitems.issn LIKE ?";
642 push @where_args, "%$args->{issn}%";
644 if( $args->{ean} ){
645 push @where_strs, "biblioitems.ean LIKE ?";
646 push @where_args, "%$args->{ean}%";
648 if ( $args->{callnumber} ) {
649 push @where_strs, "subscription.callnumber LIKE ?";
650 push @where_args, "%$args->{callnumber}%";
652 if( $args->{publisher} ){
653 push @where_strs, "biblioitems.publishercode LIKE ?";
654 push @where_args, "%$args->{publisher}%";
656 if( $args->{bookseller} ){
657 push @where_strs, "aqbooksellers.name LIKE ?";
658 push @where_args, "%$args->{bookseller}%";
660 if( $args->{branch} ){
661 push @where_strs, "subscription.branchcode = ?";
662 push @where_args, "$args->{branch}";
664 if ( $args->{location} ) {
665 push @where_strs, "subscription.location = ?";
666 push @where_args, "$args->{location}";
668 if ( $args->{expiration_date} ) {
669 push @where_strs, "subscription.enddate <= ?";
670 push @where_args, "$args->{expiration_date}";
672 if( defined $args->{closed} ){
673 push @where_strs, "subscription.closed = ?";
674 push @where_args, "$args->{closed}";
676 if(@where_strs){
677 $query .= " WHERE " . join(" AND ", @where_strs);
680 my $dbh = C4::Context->dbh;
681 my $sth = $dbh->prepare($query);
682 $sth->execute(@where_args);
683 my $results = $sth->fetchall_arrayref( {} );
684 $sth->finish;
686 for my $subscription ( @$results ) {
687 $subscription->{cannotedit} = not can_edit_subscription( $subscription );
688 $subscription->{cannotdisplay} = not can_show_subscription( $subscription );
691 return @$results;
695 =head2 GetSerials
697 ($totalissues,@serials) = GetSerials($subscriptionid);
698 this function gets every serial not arrived for a given subscription
699 as well as the number of issues registered in the database (all types)
700 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
702 FIXME: We should return \@serials.
704 =cut
706 sub GetSerials {
707 my ( $subscriptionid, $count ) = @_;
709 return unless $subscriptionid;
711 my $dbh = C4::Context->dbh;
713 # status = 2 is "arrived"
714 my $counter = 0;
715 $count = 5 unless ($count);
716 my @serials;
717 my $query = "SELECT serialid,serialseq, status, publisheddate, planneddate,notes, routingnotes
718 FROM serial
719 WHERE subscriptionid = ? AND status NOT IN (2, 4, 41, 42, 43, 44, 5)
720 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC";
721 my $sth = $dbh->prepare($query);
722 $sth->execute($subscriptionid);
724 while ( my $line = $sth->fetchrow_hashref ) {
725 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
726 for my $datefield ( qw( planneddate publisheddate) ) {
727 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
728 $line->{$datefield} = format_date( $line->{$datefield});
729 } else {
730 $line->{$datefield} = q{};
733 push @serials, $line;
736 # OK, now add the last 5 issues arrives/missing
737 $query = "SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
738 FROM serial
739 WHERE subscriptionid = ?
740 AND (status in (2, 4, 41, 42, 43, 44, 5))
741 ORDER BY IF(publisheddate<>'0000-00-00',publisheddate,planneddate) DESC
743 $sth = $dbh->prepare($query);
744 $sth->execute($subscriptionid);
745 while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) {
746 $counter++;
747 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
748 for my $datefield ( qw( planneddate publisheddate) ) {
749 if ($line->{$datefield} && $line->{$datefield}!~m/^00/) {
750 $line->{$datefield} = format_date( $line->{$datefield});
751 } else {
752 $line->{$datefield} = q{};
756 push @serials, $line;
759 $query = "SELECT count(*) FROM serial WHERE subscriptionid=?";
760 $sth = $dbh->prepare($query);
761 $sth->execute($subscriptionid);
762 my ($totalissues) = $sth->fetchrow;
763 return ( $totalissues, @serials );
766 =head2 GetSerials2
768 @serials = GetSerials2($subscriptionid,$status);
769 this function returns every serial waited for a given subscription
770 as well as the number of issues registered in the database (all types)
771 this number is used to see if a subscription can be deleted (=it must have only 1 issue)
773 =cut
775 sub GetSerials2 {
776 my ( $subscription, $status ) = @_;
778 return unless ($subscription and $status);
780 my $dbh = C4::Context->dbh;
781 my $query = qq|
782 SELECT serialid,serialseq, status, planneddate, publisheddate,notes, routingnotes
783 FROM serial
784 WHERE subscriptionid=$subscription AND status IN ($status)
785 ORDER BY publisheddate,serialid DESC
787 $debug and warn "GetSerials2 query: $query";
788 my $sth = $dbh->prepare($query);
789 $sth->execute;
790 my @serials;
792 while ( my $line = $sth->fetchrow_hashref ) {
793 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
794 # Format dates for display
795 for my $datefield ( qw( planneddate publisheddate ) ) {
796 if (!defined($line->{$datefield}) || $line->{$datefield} =~m/^00/) {
797 $line->{$datefield} = q{};
799 else {
800 $line->{$datefield} = format_date( $line->{$datefield} );
803 push @serials, $line;
805 return @serials;
808 =head2 GetLatestSerials
810 \@serials = GetLatestSerials($subscriptionid,$limit)
811 get the $limit's latest serials arrived or missing for a given subscription
812 return :
813 a ref to an array which contains all of the latest serials stored into a hash.
815 =cut
817 sub GetLatestSerials {
818 my ( $subscriptionid, $limit ) = @_;
820 return unless ($subscriptionid and $limit);
822 my $dbh = C4::Context->dbh;
824 # status = 2 is "arrived"
825 my $strsth = "SELECT serialid,serialseq, status, planneddate, publisheddate, notes
826 FROM serial
827 WHERE subscriptionid = ?
828 AND status IN (2, 4, 41, 42, 43, 44)
829 ORDER BY publisheddate DESC LIMIT 0,$limit
831 my $sth = $dbh->prepare($strsth);
832 $sth->execute($subscriptionid);
833 my @serials;
834 while ( my $line = $sth->fetchrow_hashref ) {
835 $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list
836 $line->{"planneddate"} = format_date( $line->{"planneddate"} );
837 $line->{"publisheddate"} = format_date( $line->{"publisheddate"} );
838 push @serials, $line;
841 return \@serials;
844 =head2 GetDistributedTo
846 $distributedto=GetDistributedTo($subscriptionid)
847 This function returns the field distributedto for the subscription matching subscriptionid
849 =cut
851 sub GetDistributedTo {
852 my $dbh = C4::Context->dbh;
853 my $distributedto;
854 my ($subscriptionid) = @_;
856 return unless ($subscriptionid);
858 my $query = "SELECT distributedto FROM subscription WHERE subscriptionid=?";
859 my $sth = $dbh->prepare($query);
860 $sth->execute($subscriptionid);
861 return ($distributedto) = $sth->fetchrow;
864 =head2 GetNextSeq
866 my (
867 $nextseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
868 $newinnerloop1, $newinnerloop2, $newinnerloop3
869 ) = GetNextSeq( $subscription, $pattern, $planneddate );
871 $subscription is a hashref containing all the attributes of the table
872 'subscription'.
873 $pattern is a hashref containing all the attributes of the table
874 'subscription_numberpatterns'.
875 $planneddate is a C4::Dates object.
876 This function get the next issue for the subscription given on input arg
878 =cut
880 sub GetNextSeq {
881 my ($subscription, $pattern, $planneddate) = @_;
883 return unless ($subscription and $pattern);
885 my ( $newlastvalue1, $newlastvalue2, $newlastvalue3,
886 $newinnerloop1, $newinnerloop2, $newinnerloop3 );
887 my $count = 1;
889 if ($subscription->{'skip_serialseq'}) {
890 my @irreg = split /;/, $subscription->{'irregularity'};
891 if(@irreg > 0) {
892 my $irregularities = {};
893 $irregularities->{$_} = 1 foreach(@irreg);
894 my $issueno = GetFictiveIssueNumber($subscription, $planneddate) + 1;
895 while($irregularities->{$issueno}) {
896 $count++;
897 $issueno++;
902 my $numberingmethod = $pattern->{numberingmethod};
903 my $calculated = "";
904 if ($numberingmethod) {
905 $calculated = $numberingmethod;
906 my $locale = $subscription->{locale};
907 $newlastvalue1 = $subscription->{lastvalue1} || 0;
908 $newlastvalue2 = $subscription->{lastvalue2} || 0;
909 $newlastvalue3 = $subscription->{lastvalue3} || 0;
910 $newinnerloop1 = $subscription->{innerloop1} || 0;
911 $newinnerloop2 = $subscription->{innerloop2} || 0;
912 $newinnerloop3 = $subscription->{innerloop3} || 0;
913 my %calc;
914 foreach(qw/X Y Z/) {
915 $calc{$_} = 1 if ($numberingmethod =~ /\{$_\}/);
918 for(my $i = 0; $i < $count; $i++) {
919 if($calc{'X'}) {
920 # check if we have to increase the new value.
921 $newinnerloop1 += 1;
922 if ($newinnerloop1 >= $pattern->{every1}) {
923 $newinnerloop1 = 0;
924 $newlastvalue1 += $pattern->{add1};
926 # reset counter if needed.
927 $newlastvalue1 = $pattern->{setto1} if ($newlastvalue1 > $pattern->{whenmorethan1});
929 if($calc{'Y'}) {
930 # check if we have to increase the new value.
931 $newinnerloop2 += 1;
932 if ($newinnerloop2 >= $pattern->{every2}) {
933 $newinnerloop2 = 0;
934 $newlastvalue2 += $pattern->{add2};
936 # reset counter if needed.
937 $newlastvalue2 = $pattern->{setto2} if ($newlastvalue2 > $pattern->{whenmorethan2});
939 if($calc{'Z'}) {
940 # check if we have to increase the new value.
941 $newinnerloop3 += 1;
942 if ($newinnerloop3 >= $pattern->{every3}) {
943 $newinnerloop3 = 0;
944 $newlastvalue3 += $pattern->{add3};
946 # reset counter if needed.
947 $newlastvalue3 = $pattern->{setto3} if ($newlastvalue3 > $pattern->{whenmorethan3});
950 if($calc{'X'}) {
951 my $newlastvalue1string = _numeration( $newlastvalue1, $pattern->{numbering1}, $locale );
952 $calculated =~ s/\{X\}/$newlastvalue1string/g;
954 if($calc{'Y'}) {
955 my $newlastvalue2string = _numeration( $newlastvalue2, $pattern->{numbering2}, $locale );
956 $calculated =~ s/\{Y\}/$newlastvalue2string/g;
958 if($calc{'Z'}) {
959 my $newlastvalue3string = _numeration( $newlastvalue3, $pattern->{numbering3}, $locale );
960 $calculated =~ s/\{Z\}/$newlastvalue3string/g;
964 return ($calculated,
965 $newlastvalue1, $newlastvalue2, $newlastvalue3,
966 $newinnerloop1, $newinnerloop2, $newinnerloop3);
969 =head2 GetSeq
971 $calculated = GetSeq($subscription, $pattern)
972 $subscription is a hashref containing all the attributes of the table 'subscription'
973 $pattern is a hashref containing all the attributes of the table 'subscription_numberpatterns'
974 this function transforms {X},{Y},{Z} to 150,0,0 for example.
975 return:
976 the sequence in string format
978 =cut
980 sub GetSeq {
981 my ($subscription, $pattern) = @_;
983 return unless ($subscription and $pattern);
985 my $locale = $subscription->{locale};
987 my $calculated = $pattern->{numberingmethod};
989 my $newlastvalue1 = $subscription->{'lastvalue1'} || 0;
990 $newlastvalue1 = _numeration($newlastvalue1, $pattern->{numbering1}, $locale) if ($pattern->{numbering1}); # reset counter if needed.
991 $calculated =~ s/\{X\}/$newlastvalue1/g;
993 my $newlastvalue2 = $subscription->{'lastvalue2'} || 0;
994 $newlastvalue2 = _numeration($newlastvalue2, $pattern->{numbering2}, $locale) if ($pattern->{numbering2}); # reset counter if needed.
995 $calculated =~ s/\{Y\}/$newlastvalue2/g;
997 my $newlastvalue3 = $subscription->{'lastvalue3'} || 0;
998 $newlastvalue3 = _numeration($newlastvalue3, $pattern->{numbering3}, $locale) if ($pattern->{numbering3}); # reset counter if needed.
999 $calculated =~ s/\{Z\}/$newlastvalue3/g;
1000 return $calculated;
1003 =head2 GetExpirationDate
1005 $enddate = GetExpirationDate($subscriptionid, [$startdate])
1007 this function return the next expiration date for a subscription given on input args.
1009 return
1010 the enddate or undef
1012 =cut
1014 sub GetExpirationDate {
1015 my ( $subscriptionid, $startdate ) = @_;
1017 return unless ($subscriptionid);
1019 my $dbh = C4::Context->dbh;
1020 my $subscription = GetSubscription($subscriptionid);
1021 my $enddate;
1023 # we don't do the same test if the subscription is based on X numbers or on X weeks/months
1024 $enddate = $startdate || $subscription->{startdate};
1025 my @date = split( /-/, $enddate );
1026 return if ( scalar(@date) != 3 || not check_date(@date) );
1027 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity});
1028 if ( $frequency and $frequency->{unit} ) {
1030 # If Not Irregular
1031 if ( my $length = $subscription->{numberlength} ) {
1033 #calculate the date of the last issue.
1034 for ( my $i = 1 ; $i <= $length ; $i++ ) {
1035 $enddate = GetNextDate( $subscription, $enddate );
1037 } elsif ( $subscription->{monthlength} ) {
1038 if ( $$subscription{startdate} ) {
1039 my @enddate = Add_Delta_YM( $date[0], $date[1], $date[2], 0, $subscription->{monthlength} );
1040 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1042 } elsif ( $subscription->{weeklength} ) {
1043 if ( $$subscription{startdate} ) {
1044 my @date = split( /-/, $subscription->{startdate} );
1045 my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 );
1046 $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] );
1048 } else {
1049 $enddate = $subscription->{enddate};
1051 return $enddate;
1052 } else {
1053 return $subscription->{enddate};
1057 =head2 CountSubscriptionFromBiblionumber
1059 $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber)
1060 this returns a count of the subscriptions for a given biblionumber
1061 return :
1062 the number of subscriptions
1064 =cut
1066 sub CountSubscriptionFromBiblionumber {
1067 my ($biblionumber) = @_;
1069 return unless ($biblionumber);
1071 my $dbh = C4::Context->dbh;
1072 my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?";
1073 my $sth = $dbh->prepare($query);
1074 $sth->execute($biblionumber);
1075 my $subscriptionsnumber = $sth->fetchrow;
1076 return $subscriptionsnumber;
1079 =head2 ModSubscriptionHistory
1081 ModSubscriptionHistory($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
1083 this function modifies the history of a subscription. Put your new values on input arg.
1084 returns the number of rows affected
1086 =cut
1088 sub ModSubscriptionHistory {
1089 my ( $subscriptionid, $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote ) = @_;
1091 return unless ($subscriptionid);
1093 my $dbh = C4::Context->dbh;
1094 my $query = "UPDATE subscriptionhistory
1095 SET histstartdate=?,histenddate=?,recievedlist=?,missinglist=?,opacnote=?,librariannote=?
1096 WHERE subscriptionid=?
1098 my $sth = $dbh->prepare($query);
1099 $receivedlist =~ s/^; // if $receivedlist;
1100 $missinglist =~ s/^; // if $missinglist;
1101 $opacnote =~ s/^; // if $opacnote;
1102 $sth->execute( $histstartdate, $enddate, $receivedlist, $missinglist, $opacnote, $librariannote, $subscriptionid );
1103 return $sth->rows;
1106 =head2 ModSerialStatus
1108 ModSerialStatus($serialid,$serialseq, $planneddate,$publisheddate,$status,$notes)
1110 This function modify the serial status. Serial status is a number.(eg 2 is "arrived")
1111 Note : if we change from "waited" to something else,then we will have to create a new "waited" entry
1113 =cut
1115 sub ModSerialStatus {
1116 my ( $serialid, $serialseq, $planneddate, $publisheddate, $status, $notes ) = @_;
1118 return unless ($serialid);
1120 #It is a usual serial
1121 # 1st, get previous status :
1122 my $dbh = C4::Context->dbh;
1123 my $query = "SELECT serial.subscriptionid,serial.status,subscription.periodicity
1124 FROM serial, subscription
1125 WHERE serial.subscriptionid=subscription.subscriptionid
1126 AND serialid=?";
1127 my $sth = $dbh->prepare($query);
1128 $sth->execute($serialid);
1129 my ( $subscriptionid, $oldstatus, $periodicity ) = $sth->fetchrow;
1130 my $frequency = GetSubscriptionFrequency($periodicity);
1132 # change status & update subscriptionhistory
1133 my $val;
1134 if ( $status == 6 ) {
1135 DelIssue( { 'serialid' => $serialid, 'subscriptionid' => $subscriptionid, 'serialseq' => $serialseq } );
1136 } else {
1138 my $query = 'UPDATE serial SET serialseq=?,publisheddate=?,planneddate=?,status=?,notes=? WHERE serialid = ?';
1139 $sth = $dbh->prepare($query);
1140 $sth->execute( $serialseq, $publisheddate, $planneddate, $status, $notes, $serialid );
1141 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1142 $sth = $dbh->prepare($query);
1143 $sth->execute($subscriptionid);
1144 my $val = $sth->fetchrow_hashref;
1145 unless ( $val->{manualhistory} ) {
1146 $query = "SELECT missinglist,recievedlist FROM subscriptionhistory WHERE subscriptionid=?";
1147 $sth = $dbh->prepare($query);
1148 $sth->execute($subscriptionid);
1149 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1151 if ( $status == 2 || ($oldstatus == 2 && $status != 2) ) {
1152 $recievedlist .= "; $serialseq"
1153 if ($recievedlist !~ /(^|;)\s*$serialseq(?=;|$)/);
1156 # in case serial has been previously marked as missing
1157 if (grep /$status/, (1,2,3,7)) {
1158 $missinglist=~ s/(^|;)\s*$serialseq(?=;|$)//g;
1161 my @missing_statuses = qw( 4 41 42 43 44 );
1162 $missinglist .= "; $serialseq"
1163 if ( ( grep { $_ == $status } @missing_statuses ) && ( $missinglist !~/(^|;)\s*$serialseq(?=;|$)/ ) );
1164 $missinglist .= "; not issued $serialseq"
1165 if ( $status == 5 && $missinglist !~ /(^|;)\s*$serialseq(?=;|$)/ );
1167 $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?";
1168 $sth = $dbh->prepare($query);
1169 $recievedlist =~ s/^; //;
1170 $missinglist =~ s/^; //;
1171 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1175 # create new waited entry if needed (ie : was a "waited" and has changed)
1176 if ( $oldstatus == 1 && $status != 1 ) {
1177 my $subscription = GetSubscription($subscriptionid);
1178 my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern});
1180 # next issue number
1181 my (
1182 $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3,
1183 $newinnerloop1, $newinnerloop2, $newinnerloop3
1185 = GetNextSeq( $subscription, $pattern, $publisheddate );
1187 # next date (calculated from actual date & frequency parameters)
1188 my $nextpublisheddate = GetNextDate($subscription, $publisheddate, 1);
1189 my $nextpubdate = $nextpublisheddate;
1190 NewIssue( $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, 1, $nextpubdate, $nextpubdate );
1191 $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=?
1192 WHERE subscriptionid = ?";
1193 $sth = $dbh->prepare($query);
1194 $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid );
1196 # check if an alert must be sent... (= a letter is defined & status became "arrived"
1197 if ( $subscription->{letter} && $status == 2 && $oldstatus != 2 ) {
1198 require C4::Letters;
1199 C4::Letters::SendAlerts( 'issue', $subscription->{subscriptionid}, $subscription->{letter} );
1203 return;
1206 =head2 GetNextExpected
1208 $nextexpected = GetNextExpected($subscriptionid)
1210 Get the planneddate for the current expected issue of the subscription.
1212 returns a hashref:
1214 $nextexepected = {
1215 serialid => int
1216 planneddate => ISO date
1219 =cut
1221 sub GetNextExpected {
1222 my ($subscriptionid) = @_;
1224 my $dbh = C4::Context->dbh;
1225 my $query = qq{
1226 SELECT *
1227 FROM serial
1228 WHERE subscriptionid = ?
1229 AND status = ?
1230 LIMIT 1
1232 my $sth = $dbh->prepare($query);
1234 # Each subscription has only one 'expected' issue, with serial.status==1.
1235 $sth->execute( $subscriptionid, 1 );
1236 my $nextissue = $sth->fetchrow_hashref;
1237 if ( !$nextissue ) {
1238 $query = qq{
1239 SELECT *
1240 FROM serial
1241 WHERE subscriptionid = ?
1242 ORDER BY publisheddate DESC
1243 LIMIT 1
1245 $sth = $dbh->prepare($query);
1246 $sth->execute($subscriptionid);
1247 $nextissue = $sth->fetchrow_hashref;
1249 foreach(qw/planneddate publisheddate/) {
1250 if ( !defined $nextissue->{$_} ) {
1251 # or should this default to 1st Jan ???
1252 $nextissue->{$_} = strftime( '%Y-%m-%d', localtime );
1254 $nextissue->{$_} = ($nextissue->{$_} ne '0000-00-00')
1255 ? $nextissue->{$_}
1256 : undef;
1259 return $nextissue;
1262 =head2 ModNextExpected
1264 ModNextExpected($subscriptionid,$date)
1266 Update the planneddate for the current expected issue of the subscription.
1267 This will modify all future prediction results.
1269 C<$date> is an ISO date.
1271 returns 0
1273 =cut
1275 sub ModNextExpected {
1276 my ( $subscriptionid, $date ) = @_;
1277 my $dbh = C4::Context->dbh;
1279 #FIXME: Would expect to only set planneddate, but we set both on new issue creation, so updating it here
1280 my $sth = $dbh->prepare('UPDATE serial SET planneddate=?,publisheddate=? WHERE subscriptionid=? AND status=?');
1282 # Each subscription has only one 'expected' issue, with serial.status==1.
1283 $sth->execute( $date, $date, $subscriptionid, 1 );
1284 return 0;
1288 =head2 GetSubscriptionIrregularities
1290 =over 4
1292 =item @irreg = &GetSubscriptionIrregularities($subscriptionid);
1293 get the list of irregularities for a subscription
1295 =back
1297 =cut
1299 sub GetSubscriptionIrregularities {
1300 my $subscriptionid = shift;
1302 return unless $subscriptionid;
1304 my $dbh = C4::Context->dbh;
1305 my $query = qq{
1306 SELECT irregularity
1307 FROM subscription
1308 WHERE subscriptionid = ?
1310 my $sth = $dbh->prepare($query);
1311 $sth->execute($subscriptionid);
1313 my ($result) = $sth->fetchrow_array;
1314 my @irreg = split /;/, $result;
1316 return @irreg;
1319 =head2 ModSubscription
1321 this function modifies a subscription. Put all new values on input args.
1322 returns the number of rows affected
1324 =cut
1326 sub ModSubscription {
1327 my (
1328 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
1329 $periodicity, $firstacquidate, $irregularity, $numberpattern, $locale,
1330 $numberlength, $weeklength, $monthlength, $lastvalue1, $innerloop1,
1331 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, $status,
1332 $biblionumber, $callnumber, $notes, $letter, $manualhistory,
1333 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1334 $graceperiod, $location, $enddate, $subscriptionid, $skip_serialseq
1335 ) = @_;
1337 my $dbh = C4::Context->dbh;
1338 my $query = "UPDATE subscription
1339 SET librarian=?, branchcode=?, aqbooksellerid=?, cost=?, aqbudgetid=?,
1340 startdate=?, periodicity=?, firstacquidate=?, irregularity=?,
1341 numberpattern=?, locale=?, numberlength=?, weeklength=?, monthlength=?,
1342 lastvalue1=?, innerloop1=?, lastvalue2=?, innerloop2=?,
1343 lastvalue3=?, innerloop3=?, status=?, biblionumber=?,
1344 callnumber=?, notes=?, letter=?, manualhistory=?,
1345 internalnotes=?, serialsadditems=?, staffdisplaycount=?,
1346 opacdisplaycount=?, graceperiod=?, location = ?, enddate=?,
1347 skip_serialseq=?
1348 WHERE subscriptionid = ?";
1350 my $sth = $dbh->prepare($query);
1351 $sth->execute(
1352 $auser, $branchcode, $aqbooksellerid, $cost,
1353 $aqbudgetid, $startdate, $periodicity, $firstacquidate,
1354 $irregularity, $numberpattern, $locale, $numberlength,
1355 $weeklength, $monthlength, $lastvalue1, $innerloop1,
1356 $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
1357 $status, $biblionumber, $callnumber, $notes,
1358 $letter, ($manualhistory ? $manualhistory : 0),
1359 $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount,
1360 $graceperiod, $location, $enddate, $skip_serialseq,
1361 $subscriptionid
1363 my $rows = $sth->rows;
1365 logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1366 return $rows;
1369 =head2 NewSubscription
1371 $subscriptionid = &NewSubscription($auser,branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
1372 $startdate,$periodicity,$numberlength,$weeklength,$monthlength,
1373 $lastvalue1,$innerloop1,$lastvalue2,$innerloop2,$lastvalue3,$innerloop3,
1374 $status, $notes, $letter, $firstacquidate, $irregularity, $numberpattern,
1375 $locale, $callnumber, $manualhistory, $internalnotes, $serialsadditems,
1376 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq);
1378 Create a new subscription with value given on input args.
1380 return :
1381 the id of this new subscription
1383 =cut
1385 sub NewSubscription {
1386 my (
1387 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1388 $startdate, $periodicity, $numberlength, $weeklength, $monthlength,
1389 $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, $lastvalue3,
1390 $innerloop3, $status, $notes, $letter, $firstacquidate, $irregularity,
1391 $numberpattern, $locale, $callnumber, $manualhistory, $internalnotes,
1392 $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod,
1393 $location, $enddate, $skip_serialseq
1394 ) = @_;
1395 my $dbh = C4::Context->dbh;
1397 #save subscription (insert into database)
1398 my $query = qq|
1399 INSERT INTO subscription
1400 (librarian, branchcode, aqbooksellerid, cost, aqbudgetid,
1401 biblionumber, startdate, periodicity, numberlength, weeklength,
1402 monthlength, lastvalue1, innerloop1, lastvalue2, innerloop2,
1403 lastvalue3, innerloop3, status, notes, letter, firstacquidate,
1404 irregularity, numberpattern, locale, callnumber,
1405 manualhistory, internalnotes, serialsadditems, staffdisplaycount,
1406 opacdisplaycount, graceperiod, location, enddate, skip_serialseq)
1407 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
1409 my $sth = $dbh->prepare($query);
1410 $sth->execute(
1411 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
1412 $startdate, $periodicity, $numberlength, $weeklength,
1413 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
1414 $lastvalue3, $innerloop3, $status, $notes, $letter,
1415 $firstacquidate, $irregularity, $numberpattern, $locale, $callnumber,
1416 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
1417 $opacdisplaycount, $graceperiod, $location, $enddate, $skip_serialseq
1420 my $subscriptionid = $dbh->{'mysql_insertid'};
1421 unless ($enddate) {
1422 $enddate = GetExpirationDate( $subscriptionid, $startdate );
1423 $query = qq|
1424 UPDATE subscription
1425 SET enddate=?
1426 WHERE subscriptionid=?
1428 $sth = $dbh->prepare($query);
1429 $sth->execute( $enddate, $subscriptionid );
1432 # then create the 1st expected number
1433 $query = qq(
1434 INSERT INTO subscriptionhistory
1435 (biblionumber, subscriptionid, histstartdate, opacnote, librariannote)
1436 VALUES (?,?,?,?,?)
1438 $sth = $dbh->prepare($query);
1439 $sth->execute( $biblionumber, $subscriptionid, $startdate, $notes, $internalnotes );
1441 # reread subscription to get a hash (for calculation of the 1st issue number)
1442 my $subscription = GetSubscription($subscriptionid);
1443 my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern});
1445 # calculate issue number
1446 my $serialseq = GetSeq($subscription, $pattern) || q{};
1447 $query = qq|
1448 INSERT INTO serial
1449 (serialseq,subscriptionid,biblionumber,status, planneddate, publisheddate)
1450 VALUES (?,?,?,?,?,?)
1452 $sth = $dbh->prepare($query);
1453 $sth->execute( $serialseq, $subscriptionid, $biblionumber, 1, $firstacquidate, $firstacquidate );
1455 logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1457 #set serial flag on biblio if not already set.
1458 my $bib = GetBiblio($biblionumber);
1459 if ( $bib and !$bib->{'serial'} ) {
1460 my $record = GetMarcBiblio($biblionumber);
1461 my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial', $bib->{'frameworkcode'} );
1462 if ($tag) {
1463 eval { $record->field($tag)->update( $subf => 1 ); };
1465 ModBiblio( $record, $biblionumber, $bib->{'frameworkcode'} );
1467 return $subscriptionid;
1470 =head2 ReNewSubscription
1472 ReNewSubscription($subscriptionid,$user,$startdate,$numberlength,$weeklength,$monthlength,$note)
1474 this function renew a subscription with values given on input args.
1476 =cut
1478 sub ReNewSubscription {
1479 my ( $subscriptionid, $user, $startdate, $numberlength, $weeklength, $monthlength, $note ) = @_;
1480 my $dbh = C4::Context->dbh;
1481 my $subscription = GetSubscription($subscriptionid);
1482 my $query = qq|
1483 SELECT *
1484 FROM biblio
1485 LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber
1486 WHERE biblio.biblionumber=?
1488 my $sth = $dbh->prepare($query);
1489 $sth->execute( $subscription->{biblionumber} );
1490 my $biblio = $sth->fetchrow_hashref;
1492 if ( C4::Context->preference("RenewSerialAddsSuggestion") ) {
1493 require C4::Suggestions;
1494 C4::Suggestions::NewSuggestion(
1495 { 'suggestedby' => $user,
1496 'title' => $subscription->{bibliotitle},
1497 'author' => $biblio->{author},
1498 'publishercode' => $biblio->{publishercode},
1499 'note' => $biblio->{note},
1500 'biblionumber' => $subscription->{biblionumber}
1505 # renew subscription
1506 $query = qq|
1507 UPDATE subscription
1508 SET startdate=?,numberlength=?,weeklength=?,monthlength=?,reneweddate=NOW()
1509 WHERE subscriptionid=?
1511 $sth = $dbh->prepare($query);
1512 $sth->execute( $startdate, $numberlength, $weeklength, $monthlength, $subscriptionid );
1513 my $enddate = GetExpirationDate($subscriptionid);
1514 $debug && warn "enddate :$enddate";
1515 $query = qq|
1516 UPDATE subscription
1517 SET enddate=?
1518 WHERE subscriptionid=?
1520 $sth = $dbh->prepare($query);
1521 $sth->execute( $enddate, $subscriptionid );
1522 $query = qq|
1523 UPDATE subscriptionhistory
1524 SET histenddate=?
1525 WHERE subscriptionid=?
1527 $sth = $dbh->prepare($query);
1528 $sth->execute( $enddate, $subscriptionid );
1530 logaction( "SERIAL", "RENEW", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1531 return;
1534 =head2 NewIssue
1536 NewIssue($serialseq,$subscriptionid,$biblionumber,$status, $planneddate, $publisheddate, $notes)
1538 Create a new issue stored on the database.
1539 Note : we have to update the recievedlist and missinglist on subscriptionhistory for this subscription.
1540 returns the serial id
1542 =cut
1544 sub NewIssue {
1545 my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, $publisheddate, $notes ) = @_;
1546 ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ?
1548 return unless ($subscriptionid);
1550 my $dbh = C4::Context->dbh;
1551 my $query = qq|
1552 INSERT INTO serial
1553 (serialseq,subscriptionid,biblionumber,status,publisheddate,planneddate,notes)
1554 VALUES (?,?,?,?,?,?,?)
1556 my $sth = $dbh->prepare($query);
1557 $sth->execute( $serialseq, $subscriptionid, $biblionumber, $status, $publisheddate, $planneddate, $notes );
1558 my $serialid = $dbh->{'mysql_insertid'};
1559 $query = qq|
1560 SELECT missinglist,recievedlist
1561 FROM subscriptionhistory
1562 WHERE subscriptionid=?
1564 $sth = $dbh->prepare($query);
1565 $sth->execute($subscriptionid);
1566 my ( $missinglist, $recievedlist ) = $sth->fetchrow;
1568 if ( $status == 2 ) {
1569 ### TODO Add a feature that improves recognition and description.
1570 ### As such count (serialseq) i.e. : N18,2(N19),N20
1571 ### Would use substr and index But be careful to previous presence of ()
1572 $recievedlist .= "; $serialseq" unless (index($recievedlist,$serialseq)>0);
1574 if ( $status == 4 ) {
1575 $missinglist .= "; $serialseq" unless (index($missinglist,$serialseq)>0);
1577 $query = qq|
1578 UPDATE subscriptionhistory
1579 SET recievedlist=?, missinglist=?
1580 WHERE subscriptionid=?
1582 $sth = $dbh->prepare($query);
1583 $recievedlist =~ s/^; //;
1584 $missinglist =~ s/^; //;
1585 $sth->execute( $recievedlist, $missinglist, $subscriptionid );
1586 return $serialid;
1589 =head2 ItemizeSerials
1591 ItemizeSerials($serialid, $info);
1592 $info is a hashref containing barcode branch, itemcallnumber, status, location
1593 $serialid the serialid
1594 return :
1595 1 if the itemize is a succes.
1596 0 and @error otherwise. @error containts the list of errors found.
1598 =cut
1600 sub ItemizeSerials {
1601 my ( $serialid, $info ) = @_;
1603 return unless ($serialid);
1605 my $now = POSIX::strftime( "%Y-%m-%d", localtime );
1607 my $dbh = C4::Context->dbh;
1608 my $query = qq|
1609 SELECT *
1610 FROM serial
1611 WHERE serialid=?
1613 my $sth = $dbh->prepare($query);
1614 $sth->execute($serialid);
1615 my $data = $sth->fetchrow_hashref;
1616 if ( C4::Context->preference("RoutingSerials") ) {
1618 # check for existing biblioitem relating to serial issue
1619 my ( $count, @results ) = GetBiblioItemByBiblioNumber( $data->{'biblionumber'} );
1620 my $bibitemno = 0;
1621 for ( my $i = 0 ; $i < $count ; $i++ ) {
1622 if ( $results[$i]->{'volumeddesc'} eq $data->{'serialseq'} . ' (' . $data->{'planneddate'} . ')' ) {
1623 $bibitemno = $results[$i]->{'biblioitemnumber'};
1624 last;
1627 if ( $bibitemno == 0 ) {
1628 my $sth = $dbh->prepare( "SELECT * FROM biblioitems WHERE biblionumber = ? ORDER BY biblioitemnumber DESC" );
1629 $sth->execute( $data->{'biblionumber'} );
1630 my $biblioitem = $sth->fetchrow_hashref;
1631 $biblioitem->{'volumedate'} = $data->{planneddate};
1632 $biblioitem->{'volumeddesc'} = $data->{serialseq} . ' (' . format_date( $data->{'planneddate'} ) . ')';
1633 $biblioitem->{'dewey'} = $info->{itemcallnumber};
1637 my $fwk = GetFrameworkCode( $data->{'biblionumber'} );
1638 if ( $info->{barcode} ) {
1639 my @errors;
1640 if ( is_barcode_in_use( $info->{barcode} ) ) {
1641 push @errors, 'barcode_not_unique';
1642 } else {
1643 my $marcrecord = MARC::Record->new();
1644 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.barcode", $fwk );
1645 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{barcode} );
1646 $marcrecord->insert_fields_ordered($newField);
1647 if ( $info->{branch} ) {
1648 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.homebranch", $fwk );
1650 #warn "items.homebranch : $tag , $subfield";
1651 if ( $marcrecord->field($tag) ) {
1652 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1653 } else {
1654 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1655 $marcrecord->insert_fields_ordered($newField);
1657 ( $tag, $subfield ) = GetMarcFromKohaField( "items.holdingbranch", $fwk );
1659 #warn "items.holdingbranch : $tag , $subfield";
1660 if ( $marcrecord->field($tag) ) {
1661 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{branch} );
1662 } else {
1663 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{branch} );
1664 $marcrecord->insert_fields_ordered($newField);
1667 if ( $info->{itemcallnumber} ) {
1668 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemcallnumber", $fwk );
1670 if ( $marcrecord->field($tag) ) {
1671 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{itemcallnumber} );
1672 } else {
1673 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{itemcallnumber} );
1674 $marcrecord->insert_fields_ordered($newField);
1677 if ( $info->{notes} ) {
1678 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.itemnotes", $fwk );
1680 if ( $marcrecord->field($tag) ) {
1681 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{notes} );
1682 } else {
1683 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{notes} );
1684 $marcrecord->insert_fields_ordered($newField);
1687 if ( $info->{location} ) {
1688 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.location", $fwk );
1690 if ( $marcrecord->field($tag) ) {
1691 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{location} );
1692 } else {
1693 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{location} );
1694 $marcrecord->insert_fields_ordered($newField);
1697 if ( $info->{status} ) {
1698 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.notforloan", $fwk );
1700 if ( $marcrecord->field($tag) ) {
1701 $marcrecord->field($tag)->add_subfields( "$subfield" => $info->{status} );
1702 } else {
1703 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $info->{status} );
1704 $marcrecord->insert_fields_ordered($newField);
1707 if ( C4::Context->preference("RoutingSerials") ) {
1708 my ( $tag, $subfield ) = GetMarcFromKohaField( "items.dateaccessioned", $fwk );
1709 if ( $marcrecord->field($tag) ) {
1710 $marcrecord->field($tag)->add_subfields( "$subfield" => $now );
1711 } else {
1712 my $newField = MARC::Field->new( "$tag", '', '', "$subfield" => $now );
1713 $marcrecord->insert_fields_ordered($newField);
1716 require C4::Items;
1717 C4::Items::AddItemFromMarc( $marcrecord, $data->{'biblionumber'} );
1718 return 1;
1720 return ( 0, @errors );
1724 =head2 HasSubscriptionStrictlyExpired
1726 1 or 0 = HasSubscriptionStrictlyExpired($subscriptionid)
1728 the subscription has stricly expired when today > the end subscription date
1730 return :
1731 1 if true, 0 if false, -1 if the expiration date is not set.
1733 =cut
1735 sub HasSubscriptionStrictlyExpired {
1737 # Getting end of subscription date
1738 my ($subscriptionid) = @_;
1740 return unless ($subscriptionid);
1742 my $dbh = C4::Context->dbh;
1743 my $subscription = GetSubscription($subscriptionid);
1744 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1746 # If the expiration date is set
1747 if ( $expirationdate != 0 ) {
1748 my ( $endyear, $endmonth, $endday ) = split( '-', $expirationdate );
1750 # Getting today's date
1751 my ( $nowyear, $nowmonth, $nowday ) = Today();
1753 # if today's date > expiration date, then the subscription has stricly expired
1754 if ( Delta_Days( $nowyear, $nowmonth, $nowday, $endyear, $endmonth, $endday ) < 0 ) {
1755 return 1;
1756 } else {
1757 return 0;
1759 } else {
1761 # There are some cases where the expiration date is not set
1762 # As we can't determine if the subscription has expired on a date-basis,
1763 # we return -1;
1764 return -1;
1768 =head2 HasSubscriptionExpired
1770 $has_expired = HasSubscriptionExpired($subscriptionid)
1772 the subscription has expired when the next issue to arrive is out of subscription limit.
1774 return :
1775 0 if the subscription has not expired
1776 1 if the subscription has expired
1777 2 if has subscription does not have a valid expiration date set
1779 =cut
1781 sub HasSubscriptionExpired {
1782 my ($subscriptionid) = @_;
1784 return unless ($subscriptionid);
1786 my $dbh = C4::Context->dbh;
1787 my $subscription = GetSubscription($subscriptionid);
1788 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity});
1789 if ( $frequency and $frequency->{unit} ) {
1790 my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid);
1791 if (!defined $expirationdate) {
1792 $expirationdate = q{};
1794 my $query = qq|
1795 SELECT max(planneddate)
1796 FROM serial
1797 WHERE subscriptionid=?
1799 my $sth = $dbh->prepare($query);
1800 $sth->execute($subscriptionid);
1801 my ($res) = $sth->fetchrow;
1802 if (!$res || $res=~m/^0000/) {
1803 return 0;
1805 my @res = split( /-/, $res );
1806 my @endofsubscriptiondate = split( /-/, $expirationdate );
1807 return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) );
1808 return 1
1809 if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 )
1810 || ( !$res ) );
1811 return 0;
1812 } else {
1813 # Irregular
1814 if ( $subscription->{'numberlength'} ) {
1815 my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} );
1816 return 1 if ( $countreceived > $subscription->{'numberlength'} );
1817 return 0;
1818 } else {
1819 return 0;
1822 return 0; # Notice that you'll never get here.
1825 =head2 SetDistributedto
1827 SetDistributedto($distributedto,$subscriptionid);
1828 This function update the value of distributedto for a subscription given on input arg.
1830 =cut
1832 sub SetDistributedto {
1833 my ( $distributedto, $subscriptionid ) = @_;
1834 my $dbh = C4::Context->dbh;
1835 my $query = qq|
1836 UPDATE subscription
1837 SET distributedto=?
1838 WHERE subscriptionid=?
1840 my $sth = $dbh->prepare($query);
1841 $sth->execute( $distributedto, $subscriptionid );
1842 return;
1845 =head2 DelSubscription
1847 DelSubscription($subscriptionid)
1848 this function deletes subscription which has $subscriptionid as id.
1850 =cut
1852 sub DelSubscription {
1853 my ($subscriptionid) = @_;
1854 my $dbh = C4::Context->dbh;
1855 $subscriptionid = $dbh->quote($subscriptionid);
1856 $dbh->do("DELETE FROM subscription WHERE subscriptionid=$subscriptionid");
1857 $dbh->do("DELETE FROM subscriptionhistory WHERE subscriptionid=$subscriptionid");
1858 $dbh->do("DELETE FROM serial WHERE subscriptionid=$subscriptionid");
1860 logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog");
1863 =head2 DelIssue
1865 DelIssue($serialseq,$subscriptionid)
1866 this function deletes an issue which has $serialseq and $subscriptionid given on input arg.
1868 returns the number of rows affected
1870 =cut
1872 sub DelIssue {
1873 my ($dataissue) = @_;
1874 my $dbh = C4::Context->dbh;
1875 ### TODO Add itemdeletion. Would need to get itemnumbers. Should be in a pref ?
1877 my $query = qq|
1878 DELETE FROM serial
1879 WHERE serialid= ?
1880 AND subscriptionid= ?
1882 my $mainsth = $dbh->prepare($query);
1883 $mainsth->execute( $dataissue->{'serialid'}, $dataissue->{'subscriptionid'} );
1885 #Delete element from subscription history
1886 $query = "SELECT * FROM subscription WHERE subscriptionid = ?";
1887 my $sth = $dbh->prepare($query);
1888 $sth->execute( $dataissue->{'subscriptionid'} );
1889 my $val = $sth->fetchrow_hashref;
1890 unless ( $val->{manualhistory} ) {
1891 my $query = qq|
1892 SELECT * FROM subscriptionhistory
1893 WHERE subscriptionid= ?
1895 my $sth = $dbh->prepare($query);
1896 $sth->execute( $dataissue->{'subscriptionid'} );
1897 my $data = $sth->fetchrow_hashref;
1898 my $serialseq = $dataissue->{'serialseq'};
1899 $data->{'missinglist'} =~ s/\b$serialseq\b//;
1900 $data->{'recievedlist'} =~ s/\b$serialseq\b//;
1901 my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?";
1902 $sth = $dbh->prepare($strsth);
1903 $sth->execute( $dataissue->{'subscriptionid'} );
1906 return $mainsth->rows;
1909 =head2 GetLateOrMissingIssues
1911 @issuelist = GetLateMissingIssues($supplierid,$serialid)
1913 this function selects missing issues on database - where serial.status = 4 or serial.status=3 or planneddate<now
1915 return :
1916 the issuelist as an array of hash refs. Each element of this array contains
1917 name,title,planneddate,serialseq,serial.subscriptionid from tables : subscription, serial & biblio
1919 =cut
1921 sub GetLateOrMissingIssues {
1922 my ( $supplierid, $serialid, $order ) = @_;
1924 return unless ( $supplierid or $serialid );
1926 my $dbh = C4::Context->dbh;
1927 my $sth;
1928 my $byserial = '';
1929 if ($serialid) {
1930 $byserial = "and serialid = " . $serialid;
1932 if ($order) {
1933 $order .= ", title";
1934 } else {
1935 $order = "title";
1937 if ($supplierid) {
1938 $sth = $dbh->prepare(
1939 "SELECT
1940 serialid, aqbooksellerid, name,
1941 biblio.title, biblioitems.issn, planneddate, serialseq,
1942 serial.status, serial.subscriptionid, claimdate, claims_count,
1943 subscription.branchcode
1944 FROM serial
1945 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1946 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1947 LEFT JOIN biblioitems ON subscription.biblionumber=biblioitems.biblionumber
1948 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1949 WHERE subscription.subscriptionid = serial.subscriptionid
1950 AND (serial.STATUS IN (4, 41, 42, 43, 44) OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1951 AND subscription.aqbooksellerid=$supplierid
1952 $byserial
1953 ORDER BY $order"
1955 } else {
1956 $sth = $dbh->prepare(
1957 "SELECT
1958 serialid, aqbooksellerid, name,
1959 biblio.title, planneddate, serialseq,
1960 serial.status, serial.subscriptionid, claimdate, claims_count,
1961 subscription.branchcode
1962 FROM serial
1963 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
1964 LEFT JOIN biblio ON subscription.biblionumber=biblio.biblionumber
1965 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid = aqbooksellers.id
1966 WHERE subscription.subscriptionid = serial.subscriptionid
1967 AND (serial.STATUS IN (4, 41, 42, 43, 44) OR ((planneddate < now() AND serial.STATUS =1) OR serial.STATUS = 3 OR serial.STATUS = 7))
1968 $byserial
1969 ORDER BY $order"
1972 $sth->execute;
1973 my @issuelist;
1974 while ( my $line = $sth->fetchrow_hashref ) {
1976 if ($line->{planneddate} && $line->{planneddate} !~/^0+\-/) {
1977 $line->{planneddateISO} = $line->{planneddate};
1978 $line->{planneddate} = format_date( $line->{planneddate} );
1980 if ($line->{claimdate} && $line->{claimdate} !~/^0+\-/) {
1981 $line->{claimdateISO} = $line->{claimdate};
1982 $line->{claimdate} = format_date( $line->{claimdate} );
1984 $line->{"status".$line->{status}} = 1;
1985 push @issuelist, $line;
1987 return @issuelist;
1990 =head2 removeMissingIssue
1992 removeMissingIssue($subscriptionid)
1994 this function removes an issue from being part of the missing string in
1995 subscriptionlist.missinglist column
1997 called when a missing issue is found from the serials-recieve.pl file
1999 =cut
2001 sub removeMissingIssue {
2002 my ( $sequence, $subscriptionid ) = @_;
2004 return unless ($sequence and $subscriptionid);
2006 my $dbh = C4::Context->dbh;
2007 my $sth = $dbh->prepare("SELECT * FROM subscriptionhistory WHERE subscriptionid = ?");
2008 $sth->execute($subscriptionid);
2009 my $data = $sth->fetchrow_hashref;
2010 my $missinglist = $data->{'missinglist'};
2011 my $missinglistbefore = $missinglist;
2013 # warn $missinglist." before";
2014 $missinglist =~ s/($sequence)//;
2016 # warn $missinglist." after";
2017 if ( $missinglist ne $missinglistbefore ) {
2018 $missinglist =~ s/\|\s\|/\|/g;
2019 $missinglist =~ s/^\| //g;
2020 $missinglist =~ s/\|$//g;
2021 my $sth2 = $dbh->prepare(
2022 "UPDATE subscriptionhistory
2023 SET missinglist = ?
2024 WHERE subscriptionid = ?"
2026 $sth2->execute( $missinglist, $subscriptionid );
2028 return;
2031 =head2 updateClaim
2033 &updateClaim($serialid)
2035 this function updates the time when a claim is issued for late/missing items
2037 called from claims.pl file
2039 =cut
2041 sub updateClaim {
2042 my ($serialid) = @_;
2043 my $dbh = C4::Context->dbh;
2044 $dbh->do(q|
2045 UPDATE serial
2046 SET claimdate = NOW(),
2047 claims_count = claims_count + 1
2048 WHERE serialid = ?
2049 |, {}, $serialid );
2050 return;
2053 =head2 getsupplierbyserialid
2055 $result = getsupplierbyserialid($serialid)
2057 this function is used to find the supplier id given a serial id
2059 return :
2060 hashref containing serialid, subscriptionid, and aqbooksellerid
2062 =cut
2064 sub getsupplierbyserialid {
2065 my ($serialid) = @_;
2066 my $dbh = C4::Context->dbh;
2067 my $sth = $dbh->prepare(
2068 "SELECT serialid, serial.subscriptionid, aqbooksellerid
2069 FROM serial
2070 LEFT JOIN subscription ON serial.subscriptionid = subscription.subscriptionid
2071 WHERE serialid = ?
2074 $sth->execute($serialid);
2075 my $line = $sth->fetchrow_hashref;
2076 my $result = $line->{'aqbooksellerid'};
2077 return $result;
2080 =head2 check_routing
2082 $result = &check_routing($subscriptionid)
2084 this function checks to see if a serial has a routing list and returns the count of routingid
2085 used to show either an 'add' or 'edit' link
2087 =cut
2089 sub check_routing {
2090 my ($subscriptionid) = @_;
2092 return unless ($subscriptionid);
2094 my $dbh = C4::Context->dbh;
2095 my $sth = $dbh->prepare(
2096 "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist
2097 ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2098 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC
2101 $sth->execute($subscriptionid);
2102 my $line = $sth->fetchrow_hashref;
2103 my $result = $line->{'routingids'};
2104 return $result;
2107 =head2 addroutingmember
2109 addroutingmember($borrowernumber,$subscriptionid)
2111 this function takes a borrowernumber and subscriptionid and adds the member to the
2112 routing list for that serial subscription and gives them a rank on the list
2113 of either 1 or highest current rank + 1
2115 =cut
2117 sub addroutingmember {
2118 my ( $borrowernumber, $subscriptionid ) = @_;
2120 return unless ($borrowernumber and $subscriptionid);
2122 my $rank;
2123 my $dbh = C4::Context->dbh;
2124 my $sth = $dbh->prepare( "SELECT max(ranking) rank FROM subscriptionroutinglist WHERE subscriptionid = ?" );
2125 $sth->execute($subscriptionid);
2126 while ( my $line = $sth->fetchrow_hashref ) {
2127 if ( $line->{'rank'} > 0 ) {
2128 $rank = $line->{'rank'} + 1;
2129 } else {
2130 $rank = 1;
2133 $sth = $dbh->prepare( "INSERT INTO subscriptionroutinglist (subscriptionid,borrowernumber,ranking) VALUES (?,?,?)" );
2134 $sth->execute( $subscriptionid, $borrowernumber, $rank );
2137 =head2 reorder_members
2139 reorder_members($subscriptionid,$routingid,$rank)
2141 this function is used to reorder the routing list
2143 it takes the routingid of the member one wants to re-rank and the rank it is to move to
2144 - it gets all members on list puts their routingid's into an array
2145 - removes the one in the array that is $routingid
2146 - then reinjects $routingid at point indicated by $rank
2147 - then update the database with the routingids in the new order
2149 =cut
2151 sub reorder_members {
2152 my ( $subscriptionid, $routingid, $rank ) = @_;
2153 my $dbh = C4::Context->dbh;
2154 my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" );
2155 $sth->execute($subscriptionid);
2156 my @result;
2157 while ( my $line = $sth->fetchrow_hashref ) {
2158 push( @result, $line->{'routingid'} );
2161 # To find the matching index
2162 my $i;
2163 my $key = -1; # to allow for 0 being a valid response
2164 for ( $i = 0 ; $i < @result ; $i++ ) {
2165 if ( $routingid == $result[$i] ) {
2166 $key = $i; # save the index
2167 last;
2171 # if index exists in array then move it to new position
2172 if ( $key > -1 && $rank > 0 ) {
2173 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
2174 my $moving_item = splice( @result, $key, 1 );
2175 splice( @result, $new_rank, 0, $moving_item );
2177 for ( my $j = 0 ; $j < @result ; $j++ ) {
2178 my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" );
2179 $sth->execute;
2181 return;
2184 =head2 delroutingmember
2186 delroutingmember($routingid,$subscriptionid)
2188 this function either deletes one member from routing list if $routingid exists otherwise
2189 deletes all members from the routing list
2191 =cut
2193 sub delroutingmember {
2195 # if $routingid exists then deletes that row otherwise deletes all with $subscriptionid
2196 my ( $routingid, $subscriptionid ) = @_;
2197 my $dbh = C4::Context->dbh;
2198 if ($routingid) {
2199 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE routingid = ?");
2200 $sth->execute($routingid);
2201 reorder_members( $subscriptionid, $routingid );
2202 } else {
2203 my $sth = $dbh->prepare("DELETE FROM subscriptionroutinglist WHERE subscriptionid = ?");
2204 $sth->execute($subscriptionid);
2206 return;
2209 =head2 getroutinglist
2211 @routinglist = getroutinglist($subscriptionid)
2213 this gets the info from the subscriptionroutinglist for $subscriptionid
2215 return :
2216 the routinglist as an array. Each element of the array contains a hash_ref containing
2217 routingid - a unique id, borrowernumber, ranking, and biblionumber of subscription
2219 =cut
2221 sub getroutinglist {
2222 my ($subscriptionid) = @_;
2223 my $dbh = C4::Context->dbh;
2224 my $sth = $dbh->prepare(
2225 'SELECT routingid, borrowernumber, ranking, biblionumber
2226 FROM subscription
2227 JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid
2228 WHERE subscription.subscriptionid = ? ORDER BY ranking ASC'
2230 $sth->execute($subscriptionid);
2231 my $routinglist = $sth->fetchall_arrayref({});
2232 return @{$routinglist};
2235 =head2 countissuesfrom
2237 $result = countissuesfrom($subscriptionid,$startdate)
2239 Returns a count of serial rows matching the given subsctiptionid
2240 with published date greater than startdate
2242 =cut
2244 sub countissuesfrom {
2245 my ( $subscriptionid, $startdate ) = @_;
2246 my $dbh = C4::Context->dbh;
2247 my $query = qq|
2248 SELECT count(*)
2249 FROM serial
2250 WHERE subscriptionid=?
2251 AND serial.publisheddate>?
2253 my $sth = $dbh->prepare($query);
2254 $sth->execute( $subscriptionid, $startdate );
2255 my ($countreceived) = $sth->fetchrow;
2256 return $countreceived;
2259 =head2 CountIssues
2261 $result = CountIssues($subscriptionid)
2263 Returns a count of serial rows matching the given subsctiptionid
2265 =cut
2267 sub CountIssues {
2268 my ($subscriptionid) = @_;
2269 my $dbh = C4::Context->dbh;
2270 my $query = qq|
2271 SELECT count(*)
2272 FROM serial
2273 WHERE subscriptionid=?
2275 my $sth = $dbh->prepare($query);
2276 $sth->execute($subscriptionid);
2277 my ($countreceived) = $sth->fetchrow;
2278 return $countreceived;
2281 =head2 HasItems
2283 $result = HasItems($subscriptionid)
2285 returns a count of items from serial matching the subscriptionid
2287 =cut
2289 sub HasItems {
2290 my ($subscriptionid) = @_;
2291 my $dbh = C4::Context->dbh;
2292 my $query = q|
2293 SELECT COUNT(serialitems.itemnumber)
2294 FROM serial
2295 LEFT JOIN serialitems USING(serialid)
2296 WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL
2298 my $sth=$dbh->prepare($query);
2299 $sth->execute($subscriptionid);
2300 my ($countitems)=$sth->fetchrow_array();
2301 return $countitems;
2304 =head2 abouttoexpire
2306 $result = abouttoexpire($subscriptionid)
2308 this function alerts you to the penultimate issue for a serial subscription
2310 returns 1 - if this is the penultimate issue
2311 returns 0 - if not
2313 =cut
2315 sub abouttoexpire {
2316 my ($subscriptionid) = @_;
2317 my $dbh = C4::Context->dbh;
2318 my $subscription = GetSubscription($subscriptionid);
2319 my $per = $subscription->{'periodicity'};
2320 my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($per);
2321 if ($frequency and $frequency->{unit}){
2322 my $expirationdate = GetExpirationDate($subscriptionid);
2323 my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid);
2324 my $nextdate = GetNextDate($subscription, $res);
2325 if(Date::Calc::Delta_Days(
2326 split( /-/, $nextdate ),
2327 split( /-/, $expirationdate )
2328 ) <= 0) {
2329 return 1;
2331 } elsif ($subscription->{numberlength}>0) {
2332 return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1);
2334 return 0;
2337 sub in_array { # used in next sub down
2338 my ( $val, @elements ) = @_;
2339 foreach my $elem (@elements) {
2340 if ( $val == $elem ) {
2341 return 1;
2344 return 0;
2347 =head2 GetSubscriptionsFromBorrower
2349 ($count,@routinglist) = GetSubscriptionsFromBorrower($borrowernumber)
2351 this gets the info from subscriptionroutinglist for each $subscriptionid
2353 return :
2354 a count of the serial subscription routing lists to which a patron belongs,
2355 with the titles of those serial subscriptions as an array. Each element of the array
2356 contains a hash_ref with subscriptionID and title of subscription.
2358 =cut
2360 sub GetSubscriptionsFromBorrower {
2361 my ($borrowernumber) = @_;
2362 my $dbh = C4::Context->dbh;
2363 my $sth = $dbh->prepare(
2364 "SELECT subscription.subscriptionid, biblio.title
2365 FROM subscription
2366 JOIN biblio ON biblio.biblionumber = subscription.biblionumber
2367 JOIN subscriptionroutinglist USING (subscriptionid)
2368 WHERE subscriptionroutinglist.borrowernumber = ? ORDER BY title ASC
2371 $sth->execute($borrowernumber);
2372 my @routinglist;
2373 my $count = 0;
2374 while ( my $line = $sth->fetchrow_hashref ) {
2375 $count++;
2376 push( @routinglist, $line );
2378 return ( $count, @routinglist );
2382 =head2 GetFictiveIssueNumber
2384 $issueno = GetFictiveIssueNumber($subscription, $publishedate);
2386 Get the position of the issue published at $publisheddate, considering the
2387 first issue (at firstacquidate) is at position 1, the next is at position 2, etc...
2388 This issuenumber doesn't take into account irregularities, so, for instance, if the 3rd
2389 issue is declared as 'irregular' (will be skipped at receipt), the next issue number
2390 will be 4, not 3. It's why it is called 'fictive'. It is NOT a serial seq, and is not
2391 depending on how many rows are in serial table.
2392 The issue number calculation is based on subscription frequency, first acquisition
2393 date, and $publisheddate.
2395 =cut
2397 sub GetFictiveIssueNumber {
2398 my ($subscription, $publisheddate) = @_;
2400 my $frequency = GetSubscriptionFrequency($subscription->{'periodicity'});
2401 my $unit = $frequency->{unit} ? lc $frequency->{'unit'} : undef;
2402 my $issueno = 0;
2404 if($unit) {
2405 my ($year, $month, $day) = split /-/, $publisheddate;
2406 my ($fa_year, $fa_month, $fa_day) = split /-/, $subscription->{'firstacquidate'};
2407 my $wkno;
2408 my $delta;
2410 if($unit eq 'day') {
2411 $delta = Delta_Days($fa_year, $fa_month, $fa_day, $year, $month, $day);
2412 } elsif($unit eq 'week') {
2413 ($wkno, $year) = Week_of_Year($year, $month, $day);
2414 my ($fa_wkno, $fa_yr) = Week_of_Year($fa_year, $fa_month, $fa_day);
2415 $delta = ($fa_yr == $year) ? ($wkno - $fa_wkno) : ( ($year-$fa_yr-1)*52 + (52-$fa_wkno+$wkno) );
2416 } elsif($unit eq 'month') {
2417 $delta = ($fa_year == $year)
2418 ? ($month - $fa_month)
2419 : ( ($year-$fa_year-1)*12 + (12-$fa_month+$month) );
2420 } elsif($unit eq 'year') {
2421 $delta = $year - $fa_year;
2423 if($frequency->{'unitsperissue'} == 1) {
2424 $issueno = $delta * $frequency->{'issuesperunit'} + $subscription->{'countissuesperunit'};
2425 } else {
2426 # Assuming issuesperunit == 1
2427 $issueno = int( ($delta + $frequency->{'unitsperissue'}) / $frequency->{'unitsperissue'} );
2430 return $issueno;
2433 =head2 GetNextDate
2435 $resultdate = GetNextDate($publisheddate,$subscription)
2437 this function it takes the publisheddate and will return the next issue's date
2438 and will skip dates if there exists an irregularity.
2439 $publisheddate has to be an ISO date
2440 $subscription is a hashref containing at least 'periodicity', 'firstacquidate', 'irregularity', and 'countissuesperunit'
2441 $updatecount is a boolean value which, when set to true, update the 'countissuesperunit' in database
2442 - eg if periodicity is monthly and $publisheddate is 2007-02-10 but if March and April is to be
2443 skipped then the returned date will be 2007-05-10
2445 return :
2446 $resultdate - then next date in the sequence (ISO date)
2448 Return undef if subscription is irregular
2450 =cut
2452 sub GetNextDate {
2453 my ( $subscription, $publisheddate, $updatecount ) = @_;
2455 return unless $subscription and $publisheddate;
2457 my $freqdata = GetSubscriptionFrequency($subscription->{'periodicity'});
2459 if ($freqdata->{'unit'}) {
2460 my ( $year, $month, $day ) = split /-/, $publisheddate;
2462 # Process an irregularity Hash
2463 # Suppose that irregularities are stored in a string with this structure
2464 # irreg1;irreg2;irreg3
2465 # where irregX is the number of issue which will not be received
2466 # (the first issue takes the number 1, the 2nd the number 2 and so on)
2467 my %irregularities;
2468 if ( $subscription->{irregularity} ) {
2469 my @irreg = split /;/, $subscription->{'irregularity'} ;
2470 foreach my $irregularity (@irreg) {
2471 $irregularities{$irregularity} = 1;
2475 # Get the 'fictive' next issue number
2476 # It is used to check if next issue is an irregular issue.
2477 my $issueno = GetFictiveIssueNumber($subscription, $publisheddate) + 1;
2479 # Then get the next date
2480 my $unit = lc $freqdata->{'unit'};
2481 if ($unit eq 'day') {
2482 while ($irregularities{$issueno}) {
2483 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2484 ($year,$month,$day) = Add_Delta_Days($year,$month, $day , $freqdata->{'unitsperissue'} );
2485 $subscription->{'countissuesperunit'} = 1;
2486 } else {
2487 $subscription->{'countissuesperunit'}++;
2489 $issueno++;
2491 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2492 ($year,$month,$day) = Add_Delta_Days($year,$month, $day , $freqdata->{"unitsperissue"} );
2493 $subscription->{'countissuesperunit'} = 1;
2494 } else {
2495 $subscription->{'countissuesperunit'}++;
2498 elsif ($unit eq 'week') {
2499 my ($wkno, $yr) = Week_of_Year($year, $month, $day);
2500 while ($irregularities{$issueno}) {
2501 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2502 $subscription->{'countissuesperunit'} = 1;
2503 $wkno += $freqdata->{"unitsperissue"};
2504 if($wkno > 52){
2505 $wkno = $wkno % 52;
2506 $yr++;
2508 my $dow = Day_of_Week($year, $month, $day);
2509 ($year,$month,$day) = Monday_of_Week($wkno, $yr);
2510 if($freqdata->{'issuesperunit'} == 1) {
2511 ($year, $month, $day) = Add_Delta_Days($year, $month, $day, $dow - 1);
2513 } else {
2514 $subscription->{'countissuesperunit'}++;
2516 $issueno++;
2518 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2519 $subscription->{'countissuesperunit'} = 1;
2520 $wkno += $freqdata->{"unitsperissue"};
2521 if($wkno > 52){
2522 $wkno = $wkno % 52 ;
2523 $yr++;
2525 my $dow = Day_of_Week($year, $month, $day);
2526 ($year,$month,$day) = Monday_of_Week($wkno, $yr);
2527 if($freqdata->{'issuesperunit'} == 1) {
2528 ($year, $month, $day) = Add_Delta_Days($year, $month, $day, $dow - 1);
2530 } else {
2531 $subscription->{'countissuesperunit'}++;
2534 elsif ($unit eq 'month') {
2535 while ($irregularities{$issueno}) {
2536 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2537 $subscription->{'countissuesperunit'} = 1;
2538 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, 0,$freqdata->{"unitsperissue"});
2539 unless($freqdata->{'issuesperunit'} == 1) {
2540 $day = 1; # Jumping to the first day of month, because we don't know what day is expected
2542 } else {
2543 $subscription->{'countissuesperunit'}++;
2545 $issueno++;
2547 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2548 $subscription->{'countissuesperunit'} = 1;
2549 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, 0,$freqdata->{"unitsperissue"});
2550 unless($freqdata->{'issuesperunit'} == 1) {
2551 $day = 1; # Jumping to the first day of month, because we don't know what day is expected
2553 } else {
2554 $subscription->{'countissuesperunit'}++;
2557 elsif ($unit eq 'year') {
2558 while ($irregularities{$issueno}) {
2559 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2560 $subscription->{'countissuesperunit'} = 1;
2561 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, $freqdata->{"unitsperissue"},0);
2562 unless($freqdata->{'issuesperunit'} == 1) {
2563 # Jumping to the first day of year, because we don't know what day is expected
2564 $month = 1;
2565 $day = 1;
2567 } else {
2568 $subscription->{'countissuesperunit'}++;
2570 $issueno++;
2572 if ($subscription->{'countissuesperunit'} + 1 > $freqdata->{'issuesperunit'}){
2573 $subscription->{'countissuesperunit'} = 1;
2574 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, $freqdata->{"unitsperissue"},0);
2575 unless($freqdata->{'issuesperunit'} == 1) {
2576 # Jumping to the first day of year, because we don't know what day is expected
2577 $month = 1;
2578 $day = 1;
2580 } else {
2581 $subscription->{'countissuesperunit'}++;
2584 if ($updatecount){
2585 my $dbh = C4::Context->dbh;
2586 my $query = qq{
2587 UPDATE subscription
2588 SET countissuesperunit = ?
2589 WHERE subscriptionid = ?
2591 my $sth = $dbh->prepare($query);
2592 $sth->execute($subscription->{'countissuesperunit'}, $subscription->{'subscriptionid'});
2594 return sprintf("%04d-%02d-%02d", $year, $month, $day);
2598 =head2 _numeration
2600 $string = &_numeration($value,$num_type,$locale);
2602 _numeration returns the string corresponding to $value in the num_type
2603 num_type can take :
2604 -dayname
2605 -monthname
2606 -season
2607 =cut
2611 sub _numeration {
2612 my ($value, $num_type, $locale) = @_;
2613 $value ||= 0;
2614 $num_type //= '';
2615 $locale ||= 'en';
2616 my $string;
2617 if ( $num_type =~ /^dayname$/ ) {
2618 # 1970-11-01 was a Sunday
2619 $value = $value % 7;
2620 my $dt = DateTime->new(
2621 year => 1970,
2622 month => 11,
2623 day => $value + 1,
2624 locale => $locale,
2626 $string = $dt->strftime("%A");
2627 } elsif ( $num_type =~ /^monthname$/ ) {
2628 $value = $value % 12;
2629 my $dt = DateTime->new(
2630 year => 1970,
2631 month => $value + 1,
2632 locale => $locale,
2634 $string = $dt->strftime("%B");
2635 } elsif ( $num_type =~ /^season$/ ) {
2636 my @seasons= qw( Spring Summer Fall Winter );
2637 $value = $value % 4;
2638 $string = $seasons[$value];
2639 } else {
2640 $string = $value;
2643 return $string;
2646 =head2 is_barcode_in_use
2648 Returns number of occurence of the barcode in the items table
2649 Can be used as a boolean test of whether the barcode has
2650 been deployed as yet
2652 =cut
2654 sub is_barcode_in_use {
2655 my $barcode = shift;
2656 my $dbh = C4::Context->dbh;
2657 my $occurences = $dbh->selectall_arrayref(
2658 'SELECT itemnumber from items where barcode = ?',
2659 {}, $barcode
2663 return @{$occurences};
2666 =head2 CloseSubscription
2667 Close a subscription given a subscriptionid
2668 =cut
2669 sub CloseSubscription {
2670 my ( $subscriptionid ) = @_;
2671 return unless $subscriptionid;
2672 my $dbh = C4::Context->dbh;
2673 my $sth = $dbh->prepare( qq{
2674 UPDATE subscription
2675 SET closed = 1
2676 WHERE subscriptionid = ?
2677 } );
2678 $sth->execute( $subscriptionid );
2680 # Set status = missing when status = stopped
2681 $sth = $dbh->prepare( qq{
2682 UPDATE serial
2683 SET status = 8
2684 WHERE subscriptionid = ?
2685 AND status = 1
2686 } );
2687 $sth->execute( $subscriptionid );
2690 =head2 ReopenSubscription
2691 Reopen a subscription given a subscriptionid
2692 =cut
2693 sub ReopenSubscription {
2694 my ( $subscriptionid ) = @_;
2695 return unless $subscriptionid;
2696 my $dbh = C4::Context->dbh;
2697 my $sth = $dbh->prepare( qq{
2698 UPDATE subscription
2699 SET closed = 0
2700 WHERE subscriptionid = ?
2701 } );
2702 $sth->execute( $subscriptionid );
2704 # Set status = expected when status = stopped
2705 $sth = $dbh->prepare( qq{
2706 UPDATE serial
2707 SET status = 1
2708 WHERE subscriptionid = ?
2709 AND status = 8
2710 } );
2711 $sth->execute( $subscriptionid );
2714 =head2 subscriptionCurrentlyOnOrder
2716 $bool = subscriptionCurrentlyOnOrder( $subscriptionid );
2718 Return 1 if subscription is currently on order else 0.
2720 =cut
2722 sub subscriptionCurrentlyOnOrder {
2723 my ( $subscriptionid ) = @_;
2724 my $dbh = C4::Context->dbh;
2725 my $query = qq|
2726 SELECT COUNT(*) FROM aqorders
2727 WHERE subscriptionid = ?
2728 AND datereceived IS NULL
2729 AND datecancellationprinted IS NULL
2731 my $sth = $dbh->prepare( $query );
2732 $sth->execute($subscriptionid);
2733 return $sth->fetchrow_array;
2736 =head2 can_edit_subscription
2738 $can = can_edit_subscription( $subscriptionid[, $userid] );
2740 Return 1 if the subscription can be edited by the current logged user (or a given $userid), else 0.
2742 =cut
2744 sub can_edit_subscription {
2745 my ( $subscription, $userid ) = @_;
2746 return _can_do_on_subscription( $subscription, $userid, 'edit_subscription' );
2749 =head2 can_show_subscription
2751 $can = can_show_subscription( $subscriptionid[, $userid] );
2753 Return 1 if the subscription can be shown by the current logged user (or a given $userid), else 0.
2755 =cut
2757 sub can_show_subscription {
2758 my ( $subscription, $userid ) = @_;
2759 return _can_do_on_subscription( $subscription, $userid, '*' );
2762 sub _can_do_on_subscription {
2763 my ( $subscription, $userid, $permission ) = @_;
2764 return 0 unless C4::Context->userenv;
2765 my $flags = C4::Context->userenv->{flags};
2766 $userid ||= C4::Context->userenv->{'id'};
2768 if ( C4::Context->preference('IndependentBranches') ) {
2769 return 1
2770 if C4::Context->IsSuperLibrarian()
2772 C4::Auth::haspermission( $userid, { serials => 'superserials' } )
2773 or (
2774 C4::Auth::haspermission( $userid,
2775 { serials => $permission } )
2776 and ( not defined $subscription->{branchcode}
2777 or $subscription->{branchcode} eq ''
2778 or $subscription->{branchcode} eq
2779 C4::Context->userenv->{'branch'} )
2782 else {
2783 return 1
2784 if C4::Context->IsSuperLibrarian()
2786 C4::Auth::haspermission( $userid, { serials => 'superserials' } )
2787 or C4::Auth::haspermission(
2788 $userid, { serials => $permission }
2792 return 0;
2796 __END__
2798 =head1 AUTHOR
2800 Koha Development Team <http://koha-community.org/>
2802 =cut