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