Bug 24474: (QA follow-up) Fix failing test
[koha.git] / serials / subscription-add.pl
bloba7b483be181bff151b7fa344d57ad0079650a01c
1 #!/usr/bin/perl
3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18 use Modern::Perl;
20 use CGI qw ( -utf8 );
21 use Date::Calc qw(Today Day_of_Year Week_of_Year Add_Delta_Days Add_Delta_YM);
22 use C4::Koha;
23 use C4::Biblio;
24 use C4::Auth;
25 use C4::Acquisition;
26 use C4::Output;
27 use C4::Context;
28 use C4::Serials;
29 use C4::Serials::Frequency;
30 use C4::Serials::Numberpattern;
31 use C4::Letters;
32 use Koha::AdditionalFields;
33 use Koha::Biblios;
34 use Koha::DateUtils;
35 use Koha::ItemTypes;
36 use Carp;
38 use Koha::Subscription::Numberpattern;
39 use Koha::Subscription::Frequency;
40 use Koha::SharedContent;
42 #use Smart::Comments;
44 our $query = CGI->new;
45 my $op = $query->param('op') || '';
46 my $dbh = C4::Context->dbh;
47 my $sub_length;
50 # Permission needed if it is a modification : edit_subscription
51 # Permission needed otherwise (nothing or dup) : create_subscription
52 my $permission =
53 ( $op eq 'modify' || $op eq 'modsubscription' ) ? "edit_subscription" : "create_subscription";
55 our ($template, $loggedinuser, $cookie)
56 = get_template_and_user({template_name => "serials/subscription-add.tt",
57 query => $query,
58 type => "intranet",
59 authnotrequired => 0,
60 flagsrequired => {serials => $permission},
61 debug => 1,
62 });
66 my $sub_on;
68 my $subs;
69 our $firstissuedate;
71 my $mana_url = C4::Context->config('mana_config');
72 $template->param( 'mana_url' => $mana_url );
73 my $subscriptionid = $query->param('subscriptionid');
75 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
77 $subs = GetSubscription($subscriptionid);
79 output_and_exit( $query, $cookie, $template, 'unknown_subscription')
80 unless $subs;
82 ## FIXME : Check rights to edit if mod. Could/Should display an error message.
83 if ($subs->{'cannotedit'} && $op eq 'modify'){
84 carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
85 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
87 $firstissuedate = $subs->{firstacquidate} || ''; # in iso format.
88 for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
89 next unless defined $subs->{$_};
90 # TODO : Handle date formats properly.
91 if ($subs->{$_} eq '0000-00-00') {
92 $subs->{$_} = ''
93 } else {
94 $subs->{$_} = $subs->{$_};
97 if (!defined $subs->{letter}) {
98 $subs->{letter}= q{};
100 my $nextexpected = GetNextExpected($subscriptionid);
101 $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
102 $subs->{nextacquidate} = $nextexpected->{planneddate} if($op eq 'modify');
103 unless($op eq 'modsubscription') {
104 foreach my $length_unit (qw(numberlength weeklength monthlength)) {
105 if ($subs->{$length_unit}) {
106 $sub_length=$subs->{$length_unit};
107 $sub_on=$length_unit;
108 last;
112 $template->param( %{$subs} );
113 $template->param(
114 $op => 1,
115 "subtype_$sub_on" => 1,
116 sublength =>$sub_length,
117 history => ($op eq 'modify'),
118 firstacquiyear => substr($firstissuedate,0,4),
121 if($op eq 'modify') {
122 my ($serials_number) = GetSerials($subscriptionid);
123 if($serials_number > 1) {
124 $template->param(more_than_one_serial => 1);
129 if ( $op eq 'dup' ) {
130 my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
131 my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
132 $template->param( dont_export_field_loop => \@fields_id );
135 my $letters = get_letter_loop( $subs->{letter} );
136 $template->param( letterloop => $letters );
140 my $locations_loop = GetAuthorisedValues("LOC");
142 $template->param(
143 branchcode => $subs->{branchcode},
144 locations_loop=>$locations_loop,
147 my @additional_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
148 my %additional_field_values;
149 if ($subscriptionid) {
150 my $subscription = Koha::Subscriptions->find($subscriptionid);
151 foreach my $value ($subscription->additional_field_values->as_list) {
152 $additional_field_values{$value->field_id} = $value->value;
156 $template->param(
157 additional_fields => \@additional_fields,
158 additional_field_values => \%additional_field_values,
161 my $typeloop = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
163 # FIXME We should use the translated_description for item types
164 my @typearg =
165 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
166 my @previoustypearg =
167 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
169 $template->param(
170 typeloop => \@typearg,
171 previoustypeloop => \@previoustypearg,
172 locations_loop=>$locations_loop,
175 # prepare template variables common to all $op conditions:
176 $template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
178 if ($op!~/^mod/) {
179 my $letters = get_letter_loop();
180 $template->param( letterloop => $letters );
183 if ($op eq 'addsubscription') {
184 redirect_add_subscription();
185 } elsif ($op eq 'modsubscription') {
186 redirect_mod_subscription();
187 } else {
189 $template->param(
190 subtypes => [ qw( numberlength weeklength monthlength ) ],
191 subtype => $sub_on,
194 if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
195 my $letters = get_letter_loop();
196 $template->param( letterloop => $letters );
199 my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
200 if (defined $new_biblionumber) {
201 my $biblio = Koha::Biblios->find( $new_biblionumber );
202 if (defined $biblio) {
203 $template->param(bibnum => $new_biblionumber);
204 $template->param(bibliotitle => $biblio->title);
208 $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
210 my @frequencies = GetSubscriptionFrequencies;
211 my @frqloop;
212 foreach my $freq (@frequencies) {
213 my $selected = 0;
214 $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
215 my $row = {
216 id => $freq->{'id'},
217 selected => $selected,
218 label => $freq->{'description'},
220 push @frqloop, $row;
222 $template->param(frequencies => \@frqloop);
224 my @numpatterns = GetSubscriptionNumberpatterns;
225 my @numberpatternloop;
226 foreach my $numpattern (@numpatterns) {
227 my $selected = 0;
228 $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
229 my $row = {
230 id => $numpattern->{'id'},
231 selected => $selected,
232 label => $numpattern->{'label'},
234 push @numberpatternloop, $row;
236 $template->param(numberpatterns => \@numberpatternloop);
238 my $languages = [ map {
240 language => $_->{iso639_2_code},
241 description => $_->{language_description} || $_->{language}
243 } @{ C4::Languages::getAllLanguages() } ];
245 $template->param( locales => $languages );
247 my @bookseller_ids = Koha::Acquisition::Booksellers->search->get_column('id');
248 $template->param( bookseller_ids => \@bookseller_ids );
250 output_html_with_http_headers $query, $cookie, $template->output;
253 sub get_letter_loop {
254 my ($selected_lettercode) = @_;
255 $selected_lettercode //= '';
256 my $letters = GetLetters({ module => 'serial' });
257 return [
258 map {
260 value => $_->{code},
261 lettername => $_->{name},
262 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
264 } @$letters
268 sub _get_sub_length {
269 my ($type, $length) = @_;
270 return
272 $type eq 'issues' ? $length : 0,
273 $type eq 'weeks' ? $length : 0,
274 $type eq 'months' ? $length : 0,
278 sub _guess_enddate {
279 my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
280 my ($year, $month, $day);
281 my $enddate;
282 if($numberlength != 0) {
283 my $frequency = GetSubscriptionFrequency($frequencyid);
284 if($frequency->{'unit'} eq 'day') {
285 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
286 } elsif($frequency->{'unit'} eq 'week') {
287 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
288 } elsif($frequency->{'unit'} eq 'month') {
289 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
290 } elsif($frequency->{'unit'} eq 'year') {
291 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
293 } elsif($weeklength != 0) {
294 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
295 } elsif($monthlength != 0) {
296 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
298 if(defined $year) {
299 $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
300 } else {
301 undef $enddate;
303 return $enddate;
306 sub redirect_add_subscription {
307 my $periodicity = $query->param('frequency');
308 if ($periodicity eq 'mana') {
309 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
311 description => $query->param('sfdescription'),
312 unit => $query->param('unit'),
313 unitsperissue => $query->param('unitsperissue'),
314 issuesperunit => $query->param('issuesperunit'),
316 )->store();
317 $periodicity = $subscription_freq->id;
319 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
321 my $auser = $query->param('user');
322 my $branchcode = $query->param('branchcode');
323 my $aqbooksellerid = $query->param('aqbooksellerid');
324 my $cost = $query->param('cost');
325 my $aqbudgetid = $query->param('aqbudgetid');
326 my @irregularity = $query->multi_param('irregularity');
327 my $locale = $query->param('locale');
328 my $graceperiod = $query->param('graceperiod') || 0;
330 my $subtype = $query->param('subtype');
331 my $sublength = $query->param('sublength');
332 my ( $numberlength, $weeklength, $monthlength )
333 = _get_sub_length( $subtype, $sublength );
334 my $add1 = $query->param('add1');
335 my $lastvalue1 = $query->param('lastvalue1');
336 my $innerloop1 = $query->param('innerloop1');
337 my $innerloop2 = $query->param('innerloop2');
338 my $lastvalue2 = $query->param('lastvalue2');
339 my $lastvalue3 = $query->param('lastvalue3');
340 my $innerloop3 = $query->param('innerloop3');
341 my $status = 1;
342 my $biblionumber = $query->param('biblionumber');
343 my $callnumber = $query->param('callnumber');
344 my $notes = $query->param('notes');
345 my $internalnotes = $query->param('internalnotes');
346 my $letter = $query->param('letter');
347 my $manualhistory = $query->param('manualhist') ? 1 : 0;
348 my $serialsadditems = $query->param('serialsadditems');
349 my $staffdisplaycount = $query->param('staffdisplaycount');
350 my $opacdisplaycount = $query->param('opacdisplaycount');
351 my $location = $query->param('location');
352 my $itemtype = $query->param('itemtype');
353 my $previousitemtype = $query->param('previousitemtype');
354 my $skip_serialseq = $query->param('skip_serialseq');
356 my $mana_id;
357 if ( $query->param('mana_id') ne "" ) {
358 $mana_id = $query->param('mana_id');
359 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
362 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
363 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
364 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
366 if(!defined $enddate || $enddate eq '') {
367 if($subtype eq "issues") {
368 $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
369 } else {
370 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
373 my $subscriptionid = NewSubscription(
374 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
375 $startdate, $periodicity, $numberlength, $weeklength,
376 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
377 $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
378 join(";",@irregularity), $numberpattern, $locale, $callnumber,
379 $manualhistory, $internalnotes, $serialsadditems,
380 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
381 $skip_serialseq, $itemtype, $previousitemtype, $mana_id
383 if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
384 my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
385 $template->param( mana_msg => $result->{msg} );
388 my @additional_fields;
389 my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
390 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
391 while ( my $field = $subscription_fields->next ) {
392 my $value = $query->param('additional_field_' . $field->id);
393 if ($field->marcfield) {
394 my ($field, $subfield) = split /\$/, $field->marcfield;
395 if ( $record and $field and $subfield ) {
396 $value = $record->subfield( $field, $subfield );
399 push @additional_fields, {
400 id => $field->id,
401 value => $value,
404 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
406 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
407 return;
410 sub redirect_mod_subscription {
411 my $subscriptionid = $query->param('subscriptionid');
412 my @irregularity = $query->multi_param('irregularity');
413 my $auser = $query->param('user');
414 my $librarian => scalar $query->param('librarian'),
415 my $branchcode = $query->param('branchcode');
416 my $cost = $query->param('cost');
417 my $aqbooksellerid = $query->param('aqbooksellerid');
418 my $biblionumber = $query->param('biblionumber');
419 my $aqbudgetid = $query->param('aqbudgetid');
421 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
422 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
423 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
425 my $nextacquidate = $query->param('nextacquidate');
426 $nextacquidate = $nextacquidate
427 ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
428 : $firstacquidate;
430 my $periodicity = $query->param('frequency');
431 if ($periodicity eq 'mana') {
432 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
434 description => $query->param('sfdescription'),
435 unit => $query->param('unit'),
436 unitsperissue => $query->param('unitsperissue'),
437 issuesperunit => $query->param('issuesperunit'),
439 )->store();
440 $periodicity = $subscription_freq->id;
442 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
444 my $subtype = $query->param('subtype');
445 my $sublength = $query->param('sublength');
446 my ($numberlength, $weeklength, $monthlength)
447 = _get_sub_length( $subtype, $sublength );
448 my $locale = $query->param('locale');
449 my $lastvalue1 = $query->param('lastvalue1');
450 my $innerloop1 = $query->param('innerloop1');
451 my $lastvalue2 = $query->param('lastvalue2');
452 my $innerloop2 = $query->param('innerloop2');
453 my $lastvalue3 = $query->param('lastvalue3');
454 my $innerloop3 = $query->param('innerloop3');
455 my $status = 1;
456 my $callnumber = $query->param('callnumber');
457 my $notes = $query->param('notes');
458 my $internalnotes = $query->param('internalnotes');
459 my $letter = $query->param('letter');
460 my $manualhistory = $query->param('manualhist') ? 1 : 0;
461 my $serialsadditems = $query->param('serialsadditems');
462 my $staffdisplaycount = $query->param('staffdisplaycount');
463 my $opacdisplaycount = $query->param('opacdisplaycount');
464 my $graceperiod = $query->param('graceperiod') || 0;
465 my $location = $query->param('location');
466 my $itemtype = $query->param('itemtype');
467 my $previousitemtype = $query->param('previousitemtype');
468 my $skip_serialseq = $query->param('skip_serialseq');
470 my $mana_id;
471 if ( $query->param('mana_id') ne "" ) {
472 $mana_id = $query->param('mana_id');
473 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
475 else {
476 $mana_id = undef;
479 # Guess end date
480 if(!defined $enddate || $enddate eq '') {
481 if($subtype eq "issues") {
482 $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
483 } else {
484 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
488 my $nextexpected = GetNextExpected($subscriptionid);
489 # If it's a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
490 if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
491 ModNextExpected($subscriptionid, $nextacquidate);
492 # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
493 $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
496 ModSubscription(
497 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
498 $periodicity, $firstacquidate, join(";",@irregularity),
499 $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
500 $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
501 $status, $biblionumber, $callnumber, $notes, $letter,
502 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
503 $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
504 $skip_serialseq, $itemtype, $previousitemtype, $mana_id
507 my @additional_fields;
508 my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
509 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
510 while ( my $field = $subscription_fields->next ) {
511 my $value = $query->param('additional_field_' . $field->id);
512 if ($field->marcfield) {
513 my ($field, $subfield) = split /\$/, $field->marcfield;
514 if ( $record and $field and $subfield ) {
515 $value = $record->subfield( $field, $subfield );
518 push @additional_fields, {
519 id => $field->id,
520 value => $value,
523 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
525 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
526 return;