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