Bug 24031: Remove check for syspref UseKohaPlugins
[koha.git] / serials / subscription-add.pl
blobf0cb7b53e17efbf87caaff051321f9b80556493a
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 _guess_enddate {
269 my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
270 my ($year, $month, $day);
271 my $enddate;
272 if($numberlength != 0) {
273 my $frequency = GetSubscriptionFrequency($frequencyid);
274 if($frequency->{'unit'} eq 'day') {
275 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
276 } elsif($frequency->{'unit'} eq 'week') {
277 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
278 } elsif($frequency->{'unit'} eq 'month') {
279 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
280 } elsif($frequency->{'unit'} eq 'year') {
281 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
283 } elsif($weeklength != 0) {
284 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
285 } elsif($monthlength != 0) {
286 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
288 if(defined $year) {
289 $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
290 } else {
291 undef $enddate;
293 return $enddate;
296 sub redirect_add_subscription {
297 my $periodicity = $query->param('frequency');
298 if ($periodicity eq 'mana') {
299 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
301 description => $query->param('sfdescription'),
302 unit => $query->param('unit'),
303 unitsperissue => $query->param('unitsperissue'),
304 issuesperunit => $query->param('issuesperunit'),
306 )->store();
307 $periodicity = $subscription_freq->id;
309 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
311 my $auser = $query->param('user');
312 my $branchcode = $query->param('branchcode');
313 my $aqbooksellerid = $query->param('aqbooksellerid');
314 my $cost = $query->param('cost');
315 my $aqbudgetid = $query->param('aqbudgetid');
316 my @irregularity = $query->multi_param('irregularity');
317 my $locale = $query->param('locale');
318 my $graceperiod = $query->param('graceperiod') || 0;
320 my $subtype = $query->param('subtype');
321 my $sublength = $query->param('sublength');
322 my ( $numberlength, $weeklength, $monthlength )
323 = GetSubscriptionLength( $subtype, $sublength );
324 my $add1 = $query->param('add1');
325 my $lastvalue1 = $query->param('lastvalue1');
326 my $innerloop1 = $query->param('innerloop1');
327 my $innerloop2 = $query->param('innerloop2');
328 my $lastvalue2 = $query->param('lastvalue2');
329 my $lastvalue3 = $query->param('lastvalue3');
330 my $innerloop3 = $query->param('innerloop3');
331 my $status = 1;
332 my $biblionumber = $query->param('biblionumber');
333 my $callnumber = $query->param('callnumber');
334 my $notes = $query->param('notes');
335 my $internalnotes = $query->param('internalnotes');
336 my $letter = $query->param('letter');
337 my $manualhistory = $query->param('manualhist') ? 1 : 0;
338 my $serialsadditems = $query->param('serialsadditems');
339 my $staffdisplaycount = $query->param('staffdisplaycount');
340 my $opacdisplaycount = $query->param('opacdisplaycount');
341 my $location = $query->param('location');
342 my $itemtype = $query->param('itemtype');
343 my $previousitemtype = $query->param('previousitemtype');
344 my $skip_serialseq = $query->param('skip_serialseq');
346 my $mana_id;
347 if ( $query->param('mana_id') ne "" ) {
348 $mana_id = $query->param('mana_id');
349 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
352 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
353 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
354 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
356 if(!defined $enddate || $enddate eq '') {
357 if($subtype eq "issues") {
358 $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
359 } else {
360 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
363 my $subscriptionid = NewSubscription(
364 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
365 $startdate, $periodicity, $numberlength, $weeklength,
366 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
367 $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
368 join(";",@irregularity), $numberpattern, $locale, $callnumber,
369 $manualhistory, $internalnotes, $serialsadditems,
370 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
371 $skip_serialseq, $itemtype, $previousitemtype, $mana_id
373 if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
374 my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
375 $template->param( mana_msg => $result->{msg} );
378 my @additional_fields;
379 my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
380 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
381 while ( my $field = $subscription_fields->next ) {
382 my $value = $query->param('additional_field_' . $field->id);
383 if ($field->marcfield) {
384 my ($field, $subfield) = split /\$/, $field->marcfield;
385 if ( $record and $field and $subfield ) {
386 $value = $record->subfield( $field, $subfield );
389 push @additional_fields, {
390 id => $field->id,
391 value => $value,
394 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
396 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
397 return;
400 sub redirect_mod_subscription {
401 my $subscriptionid = $query->param('subscriptionid');
402 my @irregularity = $query->multi_param('irregularity');
403 my $auser = $query->param('user');
404 my $librarian => scalar $query->param('librarian'),
405 my $branchcode = $query->param('branchcode');
406 my $cost = $query->param('cost');
407 my $aqbooksellerid = $query->param('aqbooksellerid');
408 my $biblionumber = $query->param('biblionumber');
409 my $aqbudgetid = $query->param('aqbudgetid');
411 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
412 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
413 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
415 my $nextacquidate = $query->param('nextacquidate');
416 $nextacquidate = $nextacquidate
417 ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
418 : $firstacquidate;
420 my $periodicity = $query->param('frequency');
421 if ($periodicity eq 'mana') {
422 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
424 description => $query->param('sfdescription'),
425 unit => $query->param('unit'),
426 unitsperissue => $query->param('unitsperissue'),
427 issuesperunit => $query->param('issuesperunit'),
429 )->store();
430 $periodicity = $subscription_freq->id;
432 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
434 my $subtype = $query->param('subtype');
435 my $sublength = $query->param('sublength');
436 my ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength( $subtype, $sublength );
437 my $locale = $query->param('locale');
438 my $lastvalue1 = $query->param('lastvalue1');
439 my $innerloop1 = $query->param('innerloop1');
440 my $lastvalue2 = $query->param('lastvalue2');
441 my $innerloop2 = $query->param('innerloop2');
442 my $lastvalue3 = $query->param('lastvalue3');
443 my $innerloop3 = $query->param('innerloop3');
444 my $status = 1;
445 my $callnumber = $query->param('callnumber');
446 my $notes = $query->param('notes');
447 my $internalnotes = $query->param('internalnotes');
448 my $letter = $query->param('letter');
449 my $manualhistory = $query->param('manualhist') ? 1 : 0;
450 my $serialsadditems = $query->param('serialsadditems');
451 my $staffdisplaycount = $query->param('staffdisplaycount');
452 my $opacdisplaycount = $query->param('opacdisplaycount');
453 my $graceperiod = $query->param('graceperiod') || 0;
454 my $location = $query->param('location');
455 my $itemtype = $query->param('itemtype');
456 my $previousitemtype = $query->param('previousitemtype');
457 my $skip_serialseq = $query->param('skip_serialseq');
459 my $mana_id;
460 if ( $query->param('mana_id') ne "" ) {
461 $mana_id = $query->param('mana_id');
462 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
464 else {
465 $mana_id = undef;
468 # Guess end date
469 if(!defined $enddate || $enddate eq '') {
470 if($subtype eq "issues") {
471 $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
472 } else {
473 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
477 my $nextexpected = GetNextExpected($subscriptionid);
478 # If it's a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
479 if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
480 ModNextExpected($subscriptionid, $nextacquidate);
481 # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
482 $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
485 ModSubscription(
486 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
487 $periodicity, $firstacquidate, join(";",@irregularity),
488 $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
489 $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
490 $status, $biblionumber, $callnumber, $notes, $letter,
491 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
492 $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
493 $skip_serialseq, $itemtype, $previousitemtype, $mana_id
496 my @additional_fields;
497 my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
498 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
499 while ( my $field = $subscription_fields->next ) {
500 my $value = $query->param('additional_field_' . $field->id);
501 if ($field->marcfield) {
502 my ($field, $subfield) = split /\$/, $field->marcfield;
503 if ( $record and $field and $subfield ) {
504 $value = $record->subfield( $field, $subfield );
507 push @additional_fields, {
508 id => $field->id,
509 value => $value,
512 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
514 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
515 return;