Bug 28007: (follow-up) Address missing instances
[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     if (!defined $subs->{letter}) {
88         $subs->{letter}= q{};
89     }
90     my $nextexpected = GetNextExpected($subscriptionid);
91     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
92     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
93     unless($op eq 'modsubscription') {
94         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
95             if ($subs->{$length_unit}) {
96                 $sub_length=$subs->{$length_unit};
97                 $sub_on=$length_unit;
98                 last;
99             }
100         }
101
102         $template->param( %{$subs} );
103         $template->param(
104                     $op => 1,
105                     "subtype_$sub_on" => 1,
106                     sublength =>$sub_length,
107                     history => ($op eq 'modify'),
108                     firstacquiyear => substr($firstissuedate,0,4),
109                     );
110
111         if($op eq 'modify') {
112             my ($serials_number) = GetSerials($subscriptionid);
113             if($serials_number > 1) {
114                 $template->param(more_than_one_serial => 1);
115             }
116         }
117     }
118
119     if ( $op eq 'dup' ) {
120         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
121         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
122         $template->param( dont_export_field_loop => \@fields_id );
123     }
124
125     my $letters = get_letter_loop( $subs->{letter} );
126     $template->param( letterloop => $letters );
127
128 }
129
130 my $locations_loop = GetAuthorisedValues("LOC");
131
132 $template->param(
133     branchcode => $subs->{branchcode},
134     locations_loop=>$locations_loop,
135 );
136
137 my @additional_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
138 my %additional_field_values;
139 if ($subscriptionid) {
140     my $subscription = Koha::Subscriptions->find($subscriptionid);
141     foreach my $value ($subscription->additional_field_values->as_list) {
142         $additional_field_values{$value->field_id} = $value->value;
143     }
144 }
145
146 $template->param(
147     additional_fields => \@additional_fields,
148     additional_field_values => \%additional_field_values,
149 );
150
151 my $typeloop = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
152
153 # FIXME We should use the translated_description for item types
154 my @typearg =
155     map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
156 my @previoustypearg =
157     map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
158
159 $template->param(
160     typeloop                 => \@typearg,
161     previoustypeloop         => \@previoustypearg,
162     locations_loop=>$locations_loop,
163 );
164
165 # prepare template variables common to all $op conditions:
166 $template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
167
168 if ($op!~/^mod/) {
169     my $letters = get_letter_loop();
170     $template->param( letterloop => $letters );
171 }
172
173 if ($op eq 'addsubscription') {
174     redirect_add_subscription();
175 } elsif ($op eq 'modsubscription') {
176     redirect_mod_subscription();
177 } else {
178
179     $template->param(
180         subtypes => [ qw( numberlength weeklength monthlength ) ],
181         subtype => $sub_on,
182     );
183
184     if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
185         my $letters = get_letter_loop();
186         $template->param( letterloop => $letters );
187     }
188
189     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
190     if (defined $new_biblionumber) {
191         my $biblio = Koha::Biblios->find( $new_biblionumber );
192         if (defined $biblio) {
193             $template->param(bibnum      => $new_biblionumber);
194             $template->param(bibliotitle => $biblio->title);
195         }
196     }
197
198     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
199
200     my @frequencies = GetSubscriptionFrequencies;
201     my @frqloop;
202     foreach my $freq (@frequencies) {
203         my $selected = 0;
204         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
205         my $row = {
206             id => $freq->{'id'},
207             selected => $selected,
208             label => $freq->{'description'},
209         };
210         push @frqloop, $row;
211     }
212     $template->param(frequencies => \@frqloop);
213
214     my @numpatterns = GetSubscriptionNumberpatterns;
215     my @numberpatternloop;
216     foreach my $numpattern (@numpatterns) {
217         my $selected = 0;
218         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
219         my $row = {
220             id => $numpattern->{'id'},
221             selected => $selected,
222             label => $numpattern->{'label'},
223         };
224         push @numberpatternloop, $row;
225     }
226     $template->param(numberpatterns => \@numberpatternloop);
227
228     my $languages = [ map {
229         {
230             language => $_->{iso639_2_code},
231             description => $_->{language_description} || $_->{language}
232         }
233     } @{ C4::Languages::getAllLanguages() } ];
234
235     $template->param( locales => $languages );
236
237     my @bookseller_ids = Koha::Acquisition::Booksellers->search->get_column('id');
238     $template->param( bookseller_ids => \@bookseller_ids );
239
240     output_html_with_http_headers $query, $cookie, $template->output;
241 }
242
243 sub get_letter_loop {
244     my ($selected_lettercode) = @_;
245     $selected_lettercode //= '';
246     my $letters = GetLetters({ module => 'serial' });
247     return [
248         map {
249             {
250                 value      => $_->{code},
251                 lettername => $_->{name},
252                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
253             }
254           } @$letters
255     ];
256 }
257
258 sub _guess_enddate {
259     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
260     my ($year, $month, $day);
261     my $enddate;
262     if($numberlength != 0) {
263         my $frequency = GetSubscriptionFrequency($frequencyid);
264         if($frequency->{'unit'} eq 'day') {
265             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
266         } elsif($frequency->{'unit'} eq 'week') {
267             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
268         } elsif($frequency->{'unit'} eq 'month') {
269             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
270         } elsif($frequency->{'unit'} eq 'year') {
271             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
272         }
273     } elsif($weeklength != 0) {
274         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
275     } elsif($monthlength != 0) {
276         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
277     }
278     if(defined $year) {
279         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
280     } else {
281         undef $enddate;
282     }
283     return $enddate;
284 }
285
286 sub redirect_add_subscription {
287     my $periodicity = $query->param('frequency');
288     if ($periodicity eq 'mana') {
289         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
290             {
291                 description   => $query->param('sfdescription'),
292                 unit          => $query->param('unit'),
293                 unitsperissue => $query->param('unitsperissue'),
294                 issuesperunit => $query->param('issuesperunit'),
295             }
296         )->store();
297         $periodicity = $subscription_freq->id;
298     }
299     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
300
301     my $auser          = $query->param('user');
302     my $branchcode     = $query->param('branchcode');
303     my $aqbooksellerid = $query->param('aqbooksellerid');
304     my $cost           = $query->param('cost');
305     my $aqbudgetid     = $query->param('aqbudgetid');
306     my @irregularity   = $query->multi_param('irregularity');
307     my $locale         = $query->param('locale');
308     my $graceperiod    = $query->param('graceperiod') || 0;
309
310     my $subtype = $query->param('subtype');
311     my $sublength = $query->param('sublength');
312     my ( $numberlength, $weeklength, $monthlength )
313         = GetSubscriptionLength( $subtype, $sublength );
314     my $add1              = $query->param('add1');
315     my $lastvalue1        = $query->param('lastvalue1');
316     my $innerloop1        = $query->param('innerloop1');
317     my $innerloop2        = $query->param('innerloop2');
318     my $lastvalue2        = $query->param('lastvalue2');
319     my $lastvalue3        = $query->param('lastvalue3');
320     my $innerloop3        = $query->param('innerloop3');
321     my $status            = 1;
322     my $biblionumber      = $query->param('biblionumber');
323     my $callnumber        = $query->param('callnumber');
324     my $notes             = $query->param('notes');
325     my $internalnotes     = $query->param('internalnotes');
326     my $letter            = $query->param('letter');
327     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
328     my $serialsadditems   = $query->param('serialsadditems');
329     my $staffdisplaycount = $query->param('staffdisplaycount');
330     my $opacdisplaycount  = $query->param('opacdisplaycount');
331     my $location          = $query->param('location');
332     my $itemtype          = $query->param('itemtype');
333     my $previousitemtype  = $query->param('previousitemtype');
334     my $skip_serialseq    = $query->param('skip_serialseq');
335
336     my $mana_id;
337     if ( $query->param('mana_id') ne "" ) {
338         $mana_id = $query->param('mana_id');
339         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
340     }
341
342     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
343     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
344     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
345
346     if(!defined $enddate || $enddate eq '') {
347         if($subtype eq "issues") {
348             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
349         } else {
350             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
351         }
352     }
353     my $subscriptionid = NewSubscription(
354         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
355         $startdate, $periodicity, $numberlength, $weeklength,
356         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
357         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
358         join(";",@irregularity), $numberpattern, $locale, $callnumber,
359         $manualhistory, $internalnotes, $serialsadditems,
360         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
361         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
362     );
363     if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
364         my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
365         $template->param( mana_msg => $result->{msg} );
366     }
367
368     my @additional_fields;
369     my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
370     my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
371     while ( my $field = $subscription_fields->next ) {
372         my $value = $query->param('additional_field_' . $field->id);
373         if ($field->marcfield) {
374             my ($field, $subfield) = split /\$/, $field->marcfield;
375             if ( $record and $field and $subfield ) {
376                 $value = $record->subfield( $field, $subfield );
377             }
378         }
379         push @additional_fields, {
380             id => $field->id,
381             value => $value,
382         };
383     }
384     Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
385
386     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
387     return;
388 }
389
390 sub redirect_mod_subscription {
391     my $subscriptionid = $query->param('subscriptionid');
392     my @irregularity = $query->multi_param('irregularity');
393     my $auser = $query->param('user');
394     my $librarian => scalar $query->param('librarian'),
395     my $branchcode = $query->param('branchcode');
396     my $cost = $query->param('cost');
397     my $aqbooksellerid = $query->param('aqbooksellerid');
398     my $biblionumber = $query->param('biblionumber');
399     my $aqbudgetid = $query->param('aqbudgetid');
400
401     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
402     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
403     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
404
405     my $nextacquidate  = $query->param('nextacquidate');
406     $nextacquidate = $nextacquidate
407         ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
408         : $firstacquidate;
409
410     my $periodicity = $query->param('frequency');
411     if ($periodicity eq 'mana') {
412         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
413             {
414                 description   => $query->param('sfdescription'),
415                 unit          => $query->param('unit'),
416                 unitsperissue => $query->param('unitsperissue'),
417                 issuesperunit => $query->param('issuesperunit'),
418             }
419         )->store();
420         $periodicity = $subscription_freq->id;
421     }
422     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
423
424     my $subtype = $query->param('subtype');
425     my $sublength = $query->param('sublength');
426     my ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength( $subtype, $sublength );
427     my $locale = $query->param('locale');
428     my $lastvalue1 = $query->param('lastvalue1');
429     my $innerloop1 = $query->param('innerloop1');
430     my $lastvalue2 = $query->param('lastvalue2');
431     my $innerloop2 = $query->param('innerloop2');
432     my $lastvalue3 = $query->param('lastvalue3');
433     my $innerloop3 = $query->param('innerloop3');
434     my $status = 1;
435     my $callnumber = $query->param('callnumber');
436     my $notes = $query->param('notes');
437     my $internalnotes = $query->param('internalnotes');
438     my $letter = $query->param('letter');
439     my $manualhistory = $query->param('manualhist') ? 1 : 0;
440     my $serialsadditems = $query->param('serialsadditems');
441         my $staffdisplaycount = $query->param('staffdisplaycount');
442         my $opacdisplaycount = $query->param('opacdisplaycount');
443     my $graceperiod     = $query->param('graceperiod') || 0;
444     my $location = $query->param('location');
445     my $itemtype          = $query->param('itemtype');
446     my $previousitemtype  = $query->param('previousitemtype');
447     my $skip_serialseq    = $query->param('skip_serialseq');
448
449     my $mana_id;
450     if ( $query->param('mana_id') ne "" ) {
451         $mana_id = $query->param('mana_id');
452         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
453     }
454     else {
455         $mana_id = undef;
456     }
457
458     # Guess end date
459     if(!defined $enddate || $enddate eq '') {
460         if($subtype eq "issues") {
461             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
462         } else {
463             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
464         }
465     }
466
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});
473     }
474
475     ModSubscription(
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
484     );
485
486     my @additional_fields;
487     my $record = GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 });
488     my $subscription_fields = Koha::AdditionalFields->search({ tablename => 'subscription' });
489     while ( my $field = $subscription_fields->next ) {
490         my $value = $query->param('additional_field_' . $field->id);
491         if ($field->marcfield) {
492             my ($field, $subfield) = split /\$/, $field->marcfield;
493             if ( $record and $field and $subfield ) {
494                 $value = $record->subfield( $field, $subfield );
495             }
496         }
497         push @additional_fields, {
498             id => $field->id,
499             value => $value,
500         };
501     }
502     Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields);
503
504     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
505     return;
506 }