Bug 22692: Unit tests
[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 Smart::Comments;
39
40 our $query = CGI->new;
41 my $op = $query->param('op') || '';
42 my $dbh = C4::Context->dbh;
43 my $sub_length;
44
45
46 # Permission needed if it is a modification : edit_subscription
47 # Permission needed otherwise (nothing or dup) : create_subscription
48 my $permission =
49   ( $op eq 'modify' || $op eq 'modsubscription' ) ? "edit_subscription" : "create_subscription";
50
51 my ($template, $loggedinuser, $cookie)
52 = get_template_and_user({template_name => "serials/subscription-add.tt",
53                                 query => $query,
54                                 type => "intranet",
55                                 authnotrequired => 0,
56                                 flagsrequired => {serials => $permission},
57                                 debug => 1,
58                                 });
59
60
61
62 my $sub_on;
63
64 my $subs;
65 our $firstissuedate;
66
67 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
68
69     my $subscriptionid = $query->param('subscriptionid');
70     $subs = GetSubscription($subscriptionid);
71
72     output_and_exit( $query, $cookie, $template, 'unknown_subscription')
73         unless $subs;
74
75     ## FIXME : Check rights to edit if mod. Could/Should display an error message.
76     if ($subs->{'cannotedit'} && $op eq 'modify'){
77       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
78       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
79     }
80     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
81     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
82         next unless defined $subs->{$_};
83         # TODO : Handle date formats properly.
84          if ($subs->{$_} eq '0000-00-00') {
85             $subs->{$_} = ''
86         } else {
87             $subs->{$_} = $subs->{$_};
88         }
89           }
90       if (!defined $subs->{letter}) {
91           $subs->{letter}= q{};
92       }
93     my $nextexpected = GetNextExpected($subscriptionid);
94     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
95     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
96     unless($op eq 'modsubscription') {
97         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
98             if ($subs->{$length_unit}) {
99                 $sub_length=$subs->{$length_unit};
100                 $sub_on=$length_unit;
101                 last;
102             }
103         }
104
105         $template->param( %{$subs} );
106         $template->param(
107                     $op => 1,
108                     "subtype_$sub_on" => 1,
109                     sublength =>$sub_length,
110                     history => ($op eq 'modify'),
111                     firstacquiyear => substr($firstissuedate,0,4),
112                     );
113
114         if($op eq 'modify') {
115             my ($serials_number) = GetSerials($subscriptionid);
116             if($serials_number > 1) {
117                 $template->param(more_than_one_serial => 1);
118             }
119         }
120     }
121
122     if ( $op eq 'dup' ) {
123         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
124         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
125         $template->param( dont_export_field_loop => \@fields_id );
126     }
127
128     my $letters = get_letter_loop( $subs->{letter} );
129     $template->param( letterloop => $letters );
130
131 }
132
133 my $locations_loop = GetAuthorisedValues("LOC");
134
135 $template->param(
136     branchcode => $subs->{branchcode},
137     locations_loop=>$locations_loop,
138 );
139
140
141 my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
142 for my $field ( @$additional_fields ) {
143     if ( $field->{authorised_value_category} ) {
144         $field->{authorised_value_choices} = GetAuthorisedValues( $field->{authorised_value_category} );
145     }
146 }
147 $template->param( additional_fields_for_subscription => $additional_fields );
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     output_html_with_http_headers $query, $cookie, $template->output;
236 }
237
238 sub get_letter_loop {
239     my ($selected_lettercode) = @_;
240     $selected_lettercode //= '';
241     my $letters = GetLetters({ module => 'serial' });
242     return [
243         map {
244             {
245                 value      => $_->{code},
246                 lettername => $_->{name},
247                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
248             }
249           } @$letters
250     ];
251 }
252
253 sub _get_sub_length {
254     my ($type, $length) = @_;
255     return
256         (
257             $type eq 'issues' ? $length : 0,
258             $type eq 'weeks'   ? $length : 0,
259             $type eq 'months'  ? $length : 0,
260         );
261 }
262
263 sub _guess_enddate {
264     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
265     my ($year, $month, $day);
266     my $enddate;
267     if($numberlength != 0) {
268         my $frequency = GetSubscriptionFrequency($frequencyid);
269         if($frequency->{'unit'} eq 'day') {
270             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
271         } elsif($frequency->{'unit'} eq 'week') {
272             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
273         } elsif($frequency->{'unit'} eq 'month') {
274             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
275         } elsif($frequency->{'unit'} eq 'year') {
276             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
277         }
278     } elsif($weeklength != 0) {
279         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
280     } elsif($monthlength != 0) {
281         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
282     }
283     if(defined $year) {
284         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
285     } else {
286         undef $enddate;
287     }
288     return $enddate;
289 }
290
291 sub redirect_add_subscription {
292     my $auser          = $query->param('user');
293     my $branchcode     = $query->param('branchcode');
294     my $aqbooksellerid = $query->param('aqbooksellerid');
295     my $cost           = $query->param('cost');
296     my $aqbudgetid     = $query->param('aqbudgetid');
297     my $periodicity    = $query->param('frequency');
298     my @irregularity   = $query->multi_param('irregularity');
299     my $numberpattern  = $query->param('numbering_pattern');
300     my $locale         = $query->param('locale');
301     my $graceperiod    = $query->param('graceperiod') || 0;
302
303     my $subtype = $query->param('subtype');
304     my $sublength = $query->param('sublength');
305     my ( $numberlength, $weeklength, $monthlength )
306         = _get_sub_length( $subtype, $sublength );
307     my $add1              = $query->param('add1');
308     my $lastvalue1        = $query->param('lastvalue1');
309     my $innerloop1        = $query->param('innerloop1');
310     my $innerloop2        = $query->param('innerloop2');
311     my $lastvalue2        = $query->param('lastvalue2');
312     my $lastvalue3        = $query->param('lastvalue3');
313     my $innerloop3        = $query->param('innerloop3');
314     my $status            = 1;
315     my $biblionumber      = $query->param('biblionumber');
316     my $callnumber        = $query->param('callnumber');
317     my $notes             = $query->param('notes');
318     my $internalnotes     = $query->param('internalnotes');
319     my $letter            = $query->param('letter');
320     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
321     my $serialsadditems   = $query->param('serialsadditems');
322     my $staffdisplaycount = $query->param('staffdisplaycount');
323     my $opacdisplaycount  = $query->param('opacdisplaycount');
324     my $location          = $query->param('location');
325     my $itemtype          = $query->param('itemtype');
326     my $previousitemtype  = $query->param('previousitemtype');
327     my $skip_serialseq    = $query->param('skip_serialseq');
328
329     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
330     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
331     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
332
333     if(!defined $enddate || $enddate eq '') {
334         if($subtype eq "issues") {
335             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
336         } else {
337             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
338         }
339     }
340
341     my $subscriptionid = NewSubscription(
342         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
343         $startdate, $periodicity, $numberlength, $weeklength,
344         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
345         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
346         join(";",@irregularity), $numberpattern, $locale, $callnumber,
347         $manualhistory, $internalnotes, $serialsadditems,
348         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
349         $skip_serialseq, $itemtype, $previousitemtype
350     );
351
352     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
353     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
354
355     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
356     return;
357 }
358
359 sub redirect_mod_subscription {
360     my $subscriptionid = $query->param('subscriptionid');
361     my @irregularity = $query->multi_param('irregularity');
362     my $auser = $query->param('user');
363     my $librarian => scalar $query->param('librarian'),
364     my $branchcode = $query->param('branchcode');
365     my $cost = $query->param('cost');
366     my $aqbooksellerid = $query->param('aqbooksellerid');
367     my $biblionumber = $query->param('biblionumber');
368     my $aqbudgetid = $query->param('aqbudgetid');
369
370     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
371     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
372     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
373
374     my $nextacquidate  = $query->param('nextacquidate');
375     $nextacquidate = $nextacquidate
376         ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
377         : $firstacquidate;
378
379     my $periodicity = $query->param('frequency');
380
381     my $subtype = $query->param('subtype');
382     my $sublength = $query->param('sublength');
383     my ($numberlength, $weeklength, $monthlength)
384         = _get_sub_length( $subtype, $sublength );
385     my $numberpattern = $query->param('numbering_pattern');
386     my $locale = $query->param('locale');
387     my $lastvalue1 = $query->param('lastvalue1');
388     my $innerloop1 = $query->param('innerloop1');
389     my $lastvalue2 = $query->param('lastvalue2');
390     my $innerloop2 = $query->param('innerloop2');
391     my $lastvalue3 = $query->param('lastvalue3');
392     my $innerloop3 = $query->param('innerloop3');
393     my $status = 1;
394     my $callnumber = $query->param('callnumber');
395     my $notes = $query->param('notes');
396     my $internalnotes = $query->param('internalnotes');
397     my $letter = $query->param('letter');
398     my $manualhistory = $query->param('manualhist') ? 1 : 0;
399     my $serialsadditems = $query->param('serialsadditems');
400         my $staffdisplaycount = $query->param('staffdisplaycount');
401         my $opacdisplaycount = $query->param('opacdisplaycount');
402     my $graceperiod     = $query->param('graceperiod') || 0;
403     my $location = $query->param('location');
404     my $itemtype          = $query->param('itemtype');
405     my $previousitemtype  = $query->param('previousitemtype');
406     my $skip_serialseq    = $query->param('skip_serialseq');
407
408     # Guess end date
409     if(!defined $enddate || $enddate eq '') {
410         if($subtype eq "issues") {
411             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
412         } else {
413             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
414         }
415     }
416
417     my $nextexpected = GetNextExpected($subscriptionid);
418     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
419     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
420         ModNextExpected($subscriptionid, $nextacquidate);
421         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
422         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
423     }
424
425     ModSubscription(
426         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
427         $periodicity, $firstacquidate, join(";",@irregularity),
428         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
429         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
430         $status, $biblionumber, $callnumber, $notes, $letter,
431         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
432         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
433         $skip_serialseq, $itemtype, $previousitemtype
434     );
435
436     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
437     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
438
439     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
440     return;
441 }
442
443 sub insert_additional_fields {
444     my ( $additional_fields, $biblionumber, $subscriptionid ) = @_;
445     my $record = GetMarcBiblio({
446         biblionumber => $biblionumber,
447         embed_items  => 1 });
448     for my $field ( @$additional_fields ) {
449         my $af = Koha::AdditionalField->new({ id => $field->{id} })->fetch;
450         if ( $af->{marcfield} ) {
451             my ( $field, $subfield ) = split /\$/, $af->{marcfield};
452             $af->{values} = undef;
453             if ( $field and $subfield ) {
454                 my $value = $record->subfield( $field, $subfield );
455                 $af->{values} = {
456                     $subscriptionid => $value
457                 };
458             }
459         } else {
460             $af->{values} = {
461                 $subscriptionid => scalar $query->param('additional_field_' . $field->{id})
462             } if defined $query->param('additional_field_' . $field->{id});
463         }
464         $af->insert_values;
465     }
466 }