Bug 27196: [20.05.x] Don't explode if item that is waiting if checked in by SIP
[koha.git] / serials / subscription-add.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
14 #
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>.
17
18 use Modern::Perl;
19
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;
37
38 use Koha::Subscription::Numberpattern;
39 use Koha::Subscription::Frequency;
40 use Koha::SharedContent;
41
42 #use Smart::Comments;
43
44 our $query = CGI->new;
45 my $op = $query->param('op') || '';
46 my $dbh = C4::Context->dbh;
47 my $sub_length;
48
49
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";
54
55 our ($template, $loggedinuser, $cookie)
56 = get_template_and_user({template_name => "serials/subscription-add.tt",
57                                 query => $query,
58                                 type => "intranet",
59                                 flagsrequired => {serials => $permission},
60                                 debug => 1,
61                                 });
62
63
64
65 my $sub_on;
66
67 my $subs;
68 our $firstissuedate;
69
70 my $mana_url = C4::Context->config('mana_config');
71 $template->param( 'mana_url' => $mana_url );
72 my $subscriptionid = $query->param('subscriptionid');
73
74 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
75
76     $subs = GetSubscription($subscriptionid);
77
78     output_and_exit( $query, $cookie, $template, 'unknown_subscription')
79         unless $subs;
80
81     ## FIXME : Check rights to edit if mod. Could/Should display an error message.
82     if ($subs->{'cannotedit'} && $op eq 'modify'){
83       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
84       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
85     }
86     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
87     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
88         next unless defined $subs->{$_};
89         # TODO : Handle date formats properly.
90          if ($subs->{$_} eq '0000-00-00') {
91             $subs->{$_} = ''
92         } else {
93             $subs->{$_} = $subs->{$_};
94         }
95           }
96       if (!defined $subs->{letter}) {
97           $subs->{letter}= q{};
98       }
99     my $nextexpected = GetNextExpected($subscriptionid);
100     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
101     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
102     unless($op eq 'modsubscription') {
103         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
104             if ($subs->{$length_unit}) {
105                 $sub_length=$subs->{$length_unit};
106                 $sub_on=$length_unit;
107                 last;
108             }
109         }
110
111         $template->param( %{$subs} );
112         $template->param(
113                     $op => 1,
114                     "subtype_$sub_on" => 1,
115                     sublength =>$sub_length,
116                     history => ($op eq 'modify'),
117                     firstacquiyear => substr($firstissuedate,0,4),
118                     );
119
120         if($op eq 'modify') {
121             my ($serials_number) = GetSerials($subscriptionid);
122             if($serials_number > 1) {
123                 $template->param(more_than_one_serial => 1);
124             }
125         }
126     }
127
128     if ( $op eq 'dup' ) {
129         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
130         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
131         $template->param( dont_export_field_loop => \@fields_id );
132     }
133
134     my $letters = get_letter_loop( $subs->{letter} );
135     $template->param( letterloop => $letters );
136
137 }
138
139 my $locations_loop = GetAuthorisedValues("LOC");
140
141 $template->param(
142     branchcode => $subs->{branchcode},
143     locations_loop=>$locations_loop,
144 );
145
146 my @additional_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
147 my %additional_field_values;
148 if ($subscriptionid) {
149     my $subscription = Koha::Subscriptions->find($subscriptionid);
150     foreach my $value ($subscription->additional_field_values->as_list) {
151         $additional_field_values{$value->field_id} = $value->value;
152     }
153 }
154
155 $template->param(
156     additional_fields => \@additional_fields,
157     additional_field_values => \%additional_field_values,
158 );
159
160 my $typeloop = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
161
162 # FIXME We should use the translated_description for item types
163 my @typearg =
164     map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
165 my @previoustypearg =
166     map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
167
168 $template->param(
169     typeloop                 => \@typearg,
170     previoustypeloop         => \@previoustypearg,
171     locations_loop=>$locations_loop,
172 );
173
174 # prepare template variables common to all $op conditions:
175 $template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
176
177 if ($op!~/^mod/) {
178     my $letters = get_letter_loop();
179     $template->param( letterloop => $letters );
180 }
181
182 if ($op eq 'addsubscription') {
183     redirect_add_subscription();
184 } elsif ($op eq 'modsubscription') {
185     redirect_mod_subscription();
186 } else {
187
188     $template->param(
189         subtypes => [ qw( numberlength weeklength monthlength ) ],
190         subtype => $sub_on,
191     );
192
193     if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
194         my $letters = get_letter_loop();
195         $template->param( letterloop => $letters );
196     }
197
198     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
199     if (defined $new_biblionumber) {
200         my $biblio = Koha::Biblios->find( $new_biblionumber );
201         if (defined $biblio) {
202             $template->param(bibnum      => $new_biblionumber);
203             $template->param(bibliotitle => $biblio->title);
204         }
205     }
206
207     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
208
209     my @frequencies = GetSubscriptionFrequencies;
210     my @frqloop;
211     foreach my $freq (@frequencies) {
212         my $selected = 0;
213         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
214         my $row = {
215             id => $freq->{'id'},
216             selected => $selected,
217             label => $freq->{'description'},
218         };
219         push @frqloop, $row;
220     }
221     $template->param(frequencies => \@frqloop);
222
223     my @numpatterns = GetSubscriptionNumberpatterns;
224     my @numberpatternloop;
225     foreach my $numpattern (@numpatterns) {
226         my $selected = 0;
227         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
228         my $row = {
229             id => $numpattern->{'id'},
230             selected => $selected,
231             label => $numpattern->{'label'},
232         };
233         push @numberpatternloop, $row;
234     }
235     $template->param(numberpatterns => \@numberpatternloop);
236
237     my $languages = [ map {
238         {
239             language => $_->{iso639_2_code},
240             description => $_->{language_description} || $_->{language}
241         }
242     } @{ C4::Languages::getAllLanguages() } ];
243
244     $template->param( locales => $languages );
245
246     output_html_with_http_headers $query, $cookie, $template->output;
247 }
248
249 sub get_letter_loop {
250     my ($selected_lettercode) = @_;
251     $selected_lettercode //= '';
252     my $letters = GetLetters({ module => 'serial' });
253     return [
254         map {
255             {
256                 value      => $_->{code},
257                 lettername => $_->{name},
258                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
259             }
260           } @$letters
261     ];
262 }
263
264 sub _get_sub_length {
265     my ($type, $length) = @_;
266     return
267         (
268             $type eq 'issues' ? $length : 0,
269             $type eq 'weeks'   ? $length : 0,
270             $type eq 'months'  ? $length : 0,
271         );
272 }
273
274 sub _guess_enddate {
275     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
276     my ($year, $month, $day);
277     my $enddate;
278     if($numberlength != 0) {
279         my $frequency = GetSubscriptionFrequency($frequencyid);
280         if($frequency->{'unit'} eq 'day') {
281             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
282         } elsif($frequency->{'unit'} eq 'week') {
283             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
284         } elsif($frequency->{'unit'} eq 'month') {
285             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
286         } elsif($frequency->{'unit'} eq 'year') {
287             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
288         }
289     } elsif($weeklength != 0) {
290         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
291     } elsif($monthlength != 0) {
292         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
293     }
294     if(defined $year) {
295         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
296     } else {
297         undef $enddate;
298     }
299     return $enddate;
300 }
301
302 sub redirect_add_subscription {
303     my $periodicity = $query->param('frequency');
304     if ($periodicity eq 'mana') {
305         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
306             {
307                 description   => $query->param('sfdescription'),
308                 unit          => $query->param('unit'),
309                 unitsperissue => $query->param('unitsperissue'),
310                 issuesperunit => $query->param('issuesperunit'),
311             }
312         )->store();
313         $periodicity = $subscription_freq->id;
314     }
315     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
316
317     my $auser          = $query->param('user');
318     my $branchcode     = $query->param('branchcode');
319     my $aqbooksellerid = $query->param('aqbooksellerid');
320     my $cost           = $query->param('cost');
321     my $aqbudgetid     = $query->param('aqbudgetid');
322     my @irregularity   = $query->multi_param('irregularity');
323     my $locale         = $query->param('locale');
324     my $graceperiod    = $query->param('graceperiod') || 0;
325
326     my $subtype = $query->param('subtype');
327     my $sublength = $query->param('sublength');
328     my ( $numberlength, $weeklength, $monthlength )
329         = _get_sub_length( $subtype, $sublength );
330     my $add1              = $query->param('add1');
331     my $lastvalue1        = $query->param('lastvalue1');
332     my $innerloop1        = $query->param('innerloop1');
333     my $innerloop2        = $query->param('innerloop2');
334     my $lastvalue2        = $query->param('lastvalue2');
335     my $lastvalue3        = $query->param('lastvalue3');
336     my $innerloop3        = $query->param('innerloop3');
337     my $status            = 1;
338     my $biblionumber      = $query->param('biblionumber');
339     my $callnumber        = $query->param('callnumber');
340     my $notes             = $query->param('notes');
341     my $internalnotes     = $query->param('internalnotes');
342     my $letter            = $query->param('letter');
343     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
344     my $serialsadditems   = $query->param('serialsadditems');
345     my $staffdisplaycount = $query->param('staffdisplaycount');
346     my $opacdisplaycount  = $query->param('opacdisplaycount');
347     my $location          = $query->param('location');
348     my $itemtype          = $query->param('itemtype');
349     my $previousitemtype  = $query->param('previousitemtype');
350     my $skip_serialseq    = $query->param('skip_serialseq');
351
352     my $mana_id;
353     if ( $query->param('mana_id') ne "" ) {
354         $mana_id = $query->param('mana_id');
355         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
356     }
357
358     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
359     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
360     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
361
362     if(!defined $enddate || $enddate eq '') {
363         if($subtype eq "issues") {
364             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
365         } else {
366             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
367         }
368     }
369     my $subscriptionid = NewSubscription(
370         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
371         $startdate, $periodicity, $numberlength, $weeklength,
372         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
373         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
374         join(";",@irregularity), $numberpattern, $locale, $callnumber,
375         $manualhistory, $internalnotes, $serialsadditems,
376         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
377         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
378     );
379     if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
380         my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
381         $template->param( mana_msg => $result->{msg} );
382     }
383
384     my @additional_fields;
385     my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
386     my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
387     while ( my $field = $subscription_fields->next ) {
388         my $value = $query->param('additional_field_' . $field->id);
389         if ($field->marcfield) {
390             my ($field, $subfield) = split /\$/, $field->marcfield;
391             if ( $record and $field and $subfield ) {
392                 $value = $record->subfield( $field, $subfield );
393             }
394         }
395         push @additional_fields, {
396             id => $field->id,
397             value => $value,
398         };
399     }
400     Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
401
402     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
403     return;
404 }
405
406 sub redirect_mod_subscription {
407     my $subscriptionid = $query->param('subscriptionid');
408     my @irregularity = $query->multi_param('irregularity');
409     my $auser = $query->param('user');
410     my $librarian => scalar $query->param('librarian'),
411     my $branchcode = $query->param('branchcode');
412     my $cost = $query->param('cost');
413     my $aqbooksellerid = $query->param('aqbooksellerid');
414     my $biblionumber = $query->param('biblionumber');
415     my $aqbudgetid = $query->param('aqbudgetid');
416
417     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
418     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
419     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
420
421     my $nextacquidate  = $query->param('nextacquidate');
422     $nextacquidate = $nextacquidate
423         ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
424         : $firstacquidate;
425
426     my $periodicity = $query->param('frequency');
427     if ($periodicity eq 'mana') {
428         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
429             {
430                 description   => $query->param('sfdescription'),
431                 unit          => $query->param('unit'),
432                 unitsperissue => $query->param('unitsperissue'),
433                 issuesperunit => $query->param('issuesperunit'),
434             }
435         )->store();
436         $periodicity = $subscription_freq->id;
437     }
438     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
439
440     my $subtype = $query->param('subtype');
441     my $sublength = $query->param('sublength');
442     my ($numberlength, $weeklength, $monthlength)
443         = _get_sub_length( $subtype, $sublength );
444     my $locale = $query->param('locale');
445     my $lastvalue1 = $query->param('lastvalue1');
446     my $innerloop1 = $query->param('innerloop1');
447     my $lastvalue2 = $query->param('lastvalue2');
448     my $innerloop2 = $query->param('innerloop2');
449     my $lastvalue3 = $query->param('lastvalue3');
450     my $innerloop3 = $query->param('innerloop3');
451     my $status = 1;
452     my $callnumber = $query->param('callnumber');
453     my $notes = $query->param('notes');
454     my $internalnotes = $query->param('internalnotes');
455     my $letter = $query->param('letter');
456     my $manualhistory = $query->param('manualhist') ? 1 : 0;
457     my $serialsadditems = $query->param('serialsadditems');
458         my $staffdisplaycount = $query->param('staffdisplaycount');
459         my $opacdisplaycount = $query->param('opacdisplaycount');
460     my $graceperiod     = $query->param('graceperiod') || 0;
461     my $location = $query->param('location');
462     my $itemtype          = $query->param('itemtype');
463     my $previousitemtype  = $query->param('previousitemtype');
464     my $skip_serialseq    = $query->param('skip_serialseq');
465
466     my $mana_id;
467     if ( $query->param('mana_id') ne "" ) {
468         $mana_id = $query->param('mana_id');
469         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
470     }
471     else {
472         $mana_id = undef;
473     }
474
475     # Guess end date
476     if(!defined $enddate || $enddate eq '') {
477         if($subtype eq "issues") {
478             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
479         } else {
480             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
481         }
482     }
483
484     my $nextexpected = GetNextExpected($subscriptionid);
485     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
486     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
487         ModNextExpected($subscriptionid, $nextacquidate);
488         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
489         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
490     }
491
492     ModSubscription(
493         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
494         $periodicity, $firstacquidate, join(";",@irregularity),
495         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
496         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
497         $status, $biblionumber, $callnumber, $notes, $letter,
498         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
499         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
500         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
501     );
502
503     my @additional_fields;
504     my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
505     my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
506     while ( my $field = $subscription_fields->next ) {
507         my $value = $query->param('additional_field_' . $field->id);
508         if ($field->marcfield) {
509             my ($field, $subfield) = split /\$/, $field->marcfield;
510             if ( $record and $field and $subfield ) {
511                 $value = $record->subfield( $field, $subfield );
512             }
513         }
514         push @additional_fields, {
515             id => $field->id,
516             value => $value,
517         };
518     }
519     Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
520
521     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
522     return;
523 }