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