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