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>.
21 use Date::Calc qw( Add_Delta_Days Add_Delta_YM );
22 use C4::Koha qw( GetAuthorisedValues );
23 use C4::Auth qw( get_template_and_user );
24 use C4::Output qw( output_and_exit output_html_with_http_headers );
26 use C4::Serials qw( GetSubscription GetNextExpected GetSerials GetSubscriptionLength NewSubscription ModNextExpected ModSubscription );
27 use C4::Serials::Frequency;
28 use C4::Serials::Numberpattern;
29 use C4::Letters qw( GetLetters );
30 use Koha::AdditionalFields;
32 use Koha::DateUtils qw( output_pref );
36 use Koha::Subscription::Numberpattern;
37 use Koha::Subscription::Frequency;
38 use Koha::SharedContent;
40 our $query = CGI->new;
41 my $op = $query->param('op') || '';
42 my $dbh = C4::Context->dbh;
46 # Permission needed if it is a modification : edit_subscription
47 # Permission needed otherwise (nothing or dup) : create_subscription
49 ( $op eq 'modify' || $op eq 'modsubscription' ) ? "edit_subscription" : "create_subscription";
51 our ($template, $loggedinuser, $cookie)
52 = get_template_and_user({template_name => "serials/subscription-add.tt",
55 flagsrequired => {serials => $permission},
65 my $mana_url = C4::Context->config('mana_config');
66 $template->param( 'mana_url' => $mana_url );
67 my $subscriptionid = $query->param('subscriptionid');
69 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
71 $subs = GetSubscription($subscriptionid);
73 output_and_exit( $query, $cookie, $template, 'unknown_subscription')
76 ## FIXME : Check rights to edit if mod. Could/Should display an error message.
77 if ($subs->{'cannotedit'} && $op eq 'modify'){
78 carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
79 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
81 $firstissuedate = $subs->{firstacquidate} || ''; # in iso format.
82 if (!defined $subs->{letter}) {
85 my $nextexpected = GetNextExpected($subscriptionid);
86 $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
87 $subs->{nextacquidate} = $nextexpected->{planneddate} if($op eq 'modify');
88 unless($op eq 'modsubscription') {
89 foreach my $length_unit (qw(numberlength weeklength monthlength)) {
90 if ($subs->{$length_unit}) {
91 $sub_length=$subs->{$length_unit};
97 $template->param( %{$subs} );
100 "subtype_$sub_on" => 1,
101 sublength =>$sub_length,
102 history => ($op eq 'modify'),
103 firstacquiyear => substr($firstissuedate,0,4),
106 if($op eq 'modify') {
107 my ($serials_number) = GetSerials($subscriptionid);
108 if($serials_number > 1) {
109 $template->param(more_than_one_serial => 1);
114 if ( $op eq 'dup' ) {
115 my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
116 my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
117 $template->param( dont_export_field_loop => \@fields_id );
120 my $letters = get_letter_loop( $subs->{letter} );
121 $template->param( letterloop => $letters );
125 my $locations_loop = GetAuthorisedValues("LOC");
126 my $ccodes_loop = GetAuthorisedValues("CCODE");
129 branchcode => $subs->{branchcode},
130 locations_loop=>$locations_loop,
131 ccodes_loop=>$ccodes_loop
134 my @additional_fields = Koha::AdditionalFields->search({ tablename => 'subscription' })->as_list;
135 my %additional_field_values;
136 if ($subscriptionid) {
137 my $subscription = Koha::Subscriptions->find($subscriptionid);
138 foreach my $value ($subscription->additional_field_values->as_list) {
139 $additional_field_values{$value->field_id} = $value->value;
144 additional_fields => \@additional_fields,
145 additional_field_values => \%additional_field_values,
148 my $typeloop = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
150 # FIXME We should use the translated_description for item types
152 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
153 my @previoustypearg =
154 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
157 typeloop => \@typearg,
158 previoustypeloop => \@previoustypearg,
159 locations_loop=>$locations_loop,
162 # prepare template variables common to all $op conditions:
163 $template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
166 my $letters = get_letter_loop();
167 $template->param( letterloop => $letters );
170 if ($op eq 'addsubscription') {
171 redirect_add_subscription();
172 } elsif ($op eq 'modsubscription') {
173 redirect_mod_subscription();
177 subtypes => [ qw( numberlength weeklength monthlength ) ],
181 if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
182 my $letters = get_letter_loop();
183 $template->param( letterloop => $letters );
186 my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
187 if (defined $new_biblionumber) {
188 my $biblio = Koha::Biblios->find( $new_biblionumber );
189 if (defined $biblio) {
190 $template->param(bibnum => $new_biblionumber);
191 $template->param(bibliotitle => $biblio->title);
195 $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
197 my @frequencies = GetSubscriptionFrequencies;
199 foreach my $freq (@frequencies) {
201 $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
204 selected => $selected,
205 label => $freq->{'description'},
209 $template->param(frequencies => \@frqloop);
211 my @numpatterns = GetSubscriptionNumberpatterns;
212 my @numberpatternloop;
213 foreach my $numpattern (@numpatterns) {
215 $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
217 id => $numpattern->{'id'},
218 selected => $selected,
219 label => $numpattern->{'label'},
221 push @numberpatternloop, $row;
223 $template->param(numberpatterns => \@numberpatternloop);
225 my $languages = [ map {
227 language => $_->{iso639_2_code},
228 description => $_->{language_description} || $_->{language}
230 } @{ C4::Languages::getAllLanguages() } ];
232 $template->param( locales => $languages );
234 my @bookseller_ids = Koha::Acquisition::Booksellers->search->get_column('id');
235 $template->param( bookseller_ids => \@bookseller_ids );
237 output_html_with_http_headers $query, $cookie, $template->output;
240 sub get_letter_loop {
241 my ($selected_lettercode) = @_;
242 $selected_lettercode //= '';
243 my $letters = GetLetters({ module => 'serial' });
248 lettername => $_->{name},
249 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
256 my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
257 my ($year, $month, $day);
259 if($numberlength != 0) {
260 my $frequency = GetSubscriptionFrequency($frequencyid);
261 if($frequency->{'unit'} eq 'day') {
262 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
263 } elsif($frequency->{'unit'} eq 'week') {
264 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
265 } elsif($frequency->{'unit'} eq 'month') {
266 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
267 } elsif($frequency->{'unit'} eq 'year') {
268 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
270 } elsif($weeklength != 0) {
271 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
272 } elsif($monthlength != 0) {
273 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
276 $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
283 sub redirect_add_subscription {
284 my $periodicity = $query->param('frequency');
285 if ($periodicity eq 'mana') {
286 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
288 description => $query->param('sfdescription'),
289 unit => $query->param('unit'),
290 unitsperissue => $query->param('unitsperissue'),
291 issuesperunit => $query->param('issuesperunit'),
294 $periodicity = $subscription_freq->id;
296 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
298 my $auser = $query->param('user');
299 my $branchcode = $query->param('branchcode');
300 my $aqbooksellerid = $query->param('aqbooksellerid');
301 my $cost = $query->param('cost');
302 my $aqbudgetid = $query->param('aqbudgetid');
303 my @irregularity = $query->multi_param('irregularity');
304 my $locale = $query->param('locale');
305 my $graceperiod = $query->param('graceperiod') || 0;
307 my $subtype = $query->param('subtype');
308 my $sublength = $query->param('sublength');
309 my ( $numberlength, $weeklength, $monthlength )
310 = GetSubscriptionLength( $subtype, $sublength );
311 my $add1 = $query->param('add1');
312 my $lastvalue1 = $query->param('lastvalue1');
313 my $innerloop1 = $query->param('innerloop1');
314 my $innerloop2 = $query->param('innerloop2');
315 my $lastvalue2 = $query->param('lastvalue2');
316 my $lastvalue3 = $query->param('lastvalue3');
317 my $innerloop3 = $query->param('innerloop3');
319 my $biblionumber = $query->param('biblionumber');
320 my $callnumber = $query->param('callnumber');
321 my $notes = $query->param('notes');
322 my $internalnotes = $query->param('internalnotes');
323 my $letter = $query->param('letter');
324 my $manualhistory = $query->param('manualhist') ? 1 : 0;
325 my $serialsadditems = $query->param('serialsadditems');
326 my $staffdisplaycount = $query->param('staffdisplaycount');
327 my $opacdisplaycount = $query->param('opacdisplaycount');
328 my $location = $query->param('location');
329 my $itemtype = $query->param('itemtype');
330 my $previousitemtype = $query->param('previousitemtype');
331 my $skip_serialseq = $query->param('skip_serialseq');
332 my $ccode = $query->param('ccode');
335 if ( $query->param('mana_id') ne "" ) {
336 $mana_id = $query->param('mana_id');
337 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
340 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
341 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
342 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
344 if(!defined $enddate || $enddate eq '') {
345 if($subtype eq "issues") {
346 $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
348 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
351 my $subscriptionid = NewSubscription(
352 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
353 $startdate, $periodicity, $numberlength, $weeklength,
354 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
355 $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
356 join(";",@irregularity), $numberpattern, $locale, $callnumber,
357 $manualhistory, $internalnotes, $serialsadditems,
358 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
359 $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode
361 if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
362 my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
363 $template->param( mana_msg => $result->{msg} );
366 my @additional_fields;
367 my $biblio = Koha::Biblios->find($biblionumber);
368 my $record = $biblio->metadata->record({ embed_items => 1 });
369 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
370 while ( my $field = $subscription_fields->next ) {
371 my $value = $query->param('additional_field_' . $field->id);
372 if ($field->marcfield) {
373 my ($field, $subfield) = split /\$/, $field->marcfield;
374 if ( $record and $field and $subfield ) {
375 $value = $record->subfield( $field, $subfield );
378 push @additional_fields, {
383 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
385 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
389 sub redirect_mod_subscription {
390 my $subscriptionid = $query->param('subscriptionid');
391 my @irregularity = $query->multi_param('irregularity');
392 my $auser = $query->param('user');
393 my $librarian => scalar $query->param('librarian'),
394 my $branchcode = $query->param('branchcode');
395 my $cost = $query->param('cost');
396 my $aqbooksellerid = $query->param('aqbooksellerid');
397 my $biblionumber = $query->param('biblionumber');
398 my $aqbudgetid = $query->param('aqbudgetid');
400 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
401 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
402 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
404 my $nextacquidate = $query->param('nextacquidate');
405 $nextacquidate = $nextacquidate
406 ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
409 my $periodicity = $query->param('frequency');
410 if ($periodicity eq 'mana') {
411 my $subscription_freq = Koha::Subscription::Frequency->new()->set(
413 description => $query->param('sfdescription'),
414 unit => $query->param('unit'),
415 unitsperissue => $query->param('unitsperissue'),
416 issuesperunit => $query->param('issuesperunit'),
419 $periodicity = $subscription_freq->id;
421 my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
423 my $subtype = $query->param('subtype');
424 my $sublength = $query->param('sublength');
425 my ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength( $subtype, $sublength );
426 my $locale = $query->param('locale');
427 my $lastvalue1 = $query->param('lastvalue1');
428 my $innerloop1 = $query->param('innerloop1');
429 my $lastvalue2 = $query->param('lastvalue2');
430 my $innerloop2 = $query->param('innerloop2');
431 my $lastvalue3 = $query->param('lastvalue3');
432 my $innerloop3 = $query->param('innerloop3');
434 my $callnumber = $query->param('callnumber');
435 my $notes = $query->param('notes');
436 my $internalnotes = $query->param('internalnotes');
437 my $letter = $query->param('letter');
438 my $manualhistory = $query->param('manualhist') ? 1 : 0;
439 my $serialsadditems = $query->param('serialsadditems');
440 my $staffdisplaycount = $query->param('staffdisplaycount');
441 my $opacdisplaycount = $query->param('opacdisplaycount');
442 my $graceperiod = $query->param('graceperiod') || 0;
443 my $location = $query->param('location');
444 my $itemtype = $query->param('itemtype');
445 my $previousitemtype = $query->param('previousitemtype');
446 my $skip_serialseq = $query->param('skip_serialseq');
447 my $ccode = $query->param('ccode');
450 if ( $query->param('mana_id') ne "" ) {
451 $mana_id = $query->param('mana_id');
452 Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
459 if(!defined $enddate || $enddate eq '') {
460 if($subtype eq "issues") {
461 $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
463 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
467 my $nextexpected = GetNextExpected($subscriptionid);
468 # If it's a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
469 if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
470 ModNextExpected($subscriptionid, $nextacquidate);
471 # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
472 $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
476 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
477 $periodicity, $firstacquidate, join(";",@irregularity),
478 $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
479 $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
480 $status, $biblionumber, $callnumber, $notes, $letter,
481 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
482 $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
483 $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode
486 my @additional_fields;
487 my $biblio = Koha::Biblios->find($biblionumber);
488 my $record = $biblio->metadata->record({ embed_items => 1 });
489 my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
490 while ( my $field = $subscription_fields->next ) {
491 my $value = $query->param('additional_field_' . $field->id);
492 if ($field->marcfield) {
493 my ($field, $subfield) = split /\$/, $field->marcfield;
494 if ( $record and $field and $subfield ) {
495 $value = $record->subfield( $field, $subfield );
498 push @additional_fields, {
503 Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
505 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");