Bug 10855: Additional marc fields are not inserted
[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::Dates qw/format_date format_date_in_iso/;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Context;
30 use C4::Branch; # GetBranches
31 use C4::Serials;
32 use C4::Serials::Frequency;
33 use C4::Serials::Numberpattern;
34 use C4::Letters;
35 use Koha::AdditionalField;
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 my @budgets;
46
47 # Permission needed if it is a modification : edit_subscription
48 # Permission needed otherwise (nothing or dup) : create_subscription
49 my $permission = ($op eq "modify") ? "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     ## FIXME : Check rights to edit if mod. Could/Should display an error message.
73     if ($subs->{'cannotedit'} && $op eq 'modify'){
74       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
75       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
76     }
77     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
78     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
79         next unless defined $subs->{$_};
80         # TODO : Handle date formats properly.
81          if ($subs->{$_} eq '0000-00-00') {
82             $subs->{$_} = ''
83         } else {
84             $subs->{$_} = $subs->{$_};
85         }
86           }
87       if (!defined $subs->{letter}) {
88           $subs->{letter}= q{};
89       }
90     my $nextexpected = GetNextExpected($subscriptionid);
91     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
92     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
93     unless($op eq 'modsubscription') {
94         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
95             if ($subs->{$length_unit}) {
96                 $sub_length=$subs->{$length_unit};
97                 $sub_on=$length_unit;
98                 last;
99             }
100         }
101
102         $template->param( %{$subs} );
103         $template->param(
104                     $op => 1,
105                     "subtype_$sub_on" => 1,
106                     sublength =>$sub_length,
107                     history => ($op eq 'modify'),
108                     firstacquiyear => substr($firstissuedate,0,4),
109                     );
110
111         if($op eq 'modify') {
112             my ($serials_number) = GetSerials($subscriptionid);
113             if($serials_number > 1) {
114                 $template->param(more_than_one_serial => 1);
115             }
116         }
117     }
118
119     if ( $op eq 'dup' ) {
120         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
121         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
122         $template->param( dont_export_field_loop => \@fields_id );
123     }
124
125     my $letters = get_letter_loop( $subs->{letter} );
126     $template->param( letterloop => $letters );
127
128 }
129
130 my $onlymine =
131      C4::Context->preference('IndependentBranches')
132   && C4::Context->userenv
133   && !C4::Context->IsSuperLibrarian
134   && (
135     not C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'superserials' } )
136   )
137   && C4::Context->userenv->{branch};
138 my $branches = GetBranches($onlymine);
139 my $branchloop;
140 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
141     my $selected = 0;
142     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
143     push @{$branchloop}, {
144         value => $thisbranch,
145         selected => $selected,
146         branchname => $branches->{$thisbranch}->{'branchname'},
147     };
148 }
149
150 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
151
152 $template->param(branchloop => $branchloop,
153     locations_loop=>$locations_loop,
154 );
155
156
157 my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
158 for my $field ( @$additional_fields ) {
159     if ( $field->{authorised_value_category} ) {
160         $field->{authorised_value_choices} = GetAuthorisedValues( $field->{authorised_value_category} );
161     }
162 }
163 $template->param( additional_fields_for_subscription => $additional_fields );
164
165 # prepare template variables common to all $op conditions:
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 $bib = GetBiblioData($new_biblionumber);
190         if (defined $bib) {
191             $template->param(bibnum      => $new_biblionumber);
192             $template->param(bibliotitle => $bib->{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     my $letters = GetLetters({ module => 'serial' });
241     return [
242         map {
243             {
244                 value      => $_->{code},
245                 lettername => $_->{name},
246                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
247             }
248           } @$letters
249     ];
250 }
251
252 sub _get_sub_length {
253     my ($type, $length) = @_;
254     return
255         (
256             $type eq 'issues' ? $length : 0,
257             $type eq 'weeks'   ? $length : 0,
258             $type eq 'months'  ? $length : 0,
259         );
260 }
261
262 sub _guess_enddate {
263     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
264     my ($year, $month, $day);
265     my $enddate;
266     if($numberlength != 0) {
267         my $frequency = GetSubscriptionFrequency($frequencyid);
268         if($frequency->{'unit'} eq 'day') {
269             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
270         } elsif($frequency->{'unit'} eq 'week') {
271             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
272         } elsif($frequency->{'unit'} eq 'month') {
273             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
274         } elsif($frequency->{'unit'} eq 'year') {
275             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
276         }
277     } elsif($weeklength != 0) {
278         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
279     } elsif($monthlength != 0) {
280         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
281     }
282     if(defined $year) {
283         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
284     } else {
285         undef $enddate;
286     }
287     return $enddate;
288 }
289
290 sub redirect_add_subscription {
291     my $auser          = $query->param('user');
292     my $branchcode     = $query->param('branchcode');
293     my $aqbooksellerid = $query->param('aqbooksellerid');
294     my $cost           = $query->param('cost');
295     my $aqbudgetid     = $query->param('aqbudgetid');
296     my $periodicity    = $query->param('frequency');
297     my @irregularity   = $query->param('irregularity');
298     my $numberpattern  = $query->param('numbering_pattern');
299     my $locale         = $query->param('locale');
300     my $graceperiod    = $query->param('graceperiod') || 0;
301
302     my $subtype = $query->param('subtype');
303     my $sublength = $query->param('sublength');
304     my ( $numberlength, $weeklength, $monthlength )
305         = _get_sub_length( $subtype, $sublength );
306     my $add1              = $query->param('add1');
307     my $lastvalue1        = $query->param('lastvalue1');
308     my $innerloop1        = $query->param('innerloop1');
309     my $innerloop2        = $query->param('innerloop2');
310     my $lastvalue2        = $query->param('lastvalue2');
311     my $lastvalue3        = $query->param('lastvalue3');
312     my $innerloop3        = $query->param('innerloop3');
313     my $status            = 1;
314     my $biblionumber      = $query->param('biblionumber');
315     my $callnumber        = $query->param('callnumber');
316     my $notes             = $query->param('notes');
317     my $internalnotes     = $query->param('internalnotes');
318     my $letter            = $query->param('letter');
319     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
320     my $serialsadditems   = $query->param('serialsadditems');
321     my $staffdisplaycount = $query->param('staffdisplaycount');
322     my $opacdisplaycount  = $query->param('opacdisplaycount');
323     my $location          = $query->param('location');
324     my $skip_serialseq    = $query->param('skip_serialseq');
325     my $startdate = format_date_in_iso( $query->param('startdate') );
326     my $enddate = format_date_in_iso( $query->param('enddate') );
327     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
328     if(!defined $enddate || $enddate eq '') {
329         if($subtype eq "issues") {
330             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
331         } else {
332             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
333         }
334     }
335
336     my $subscriptionid = NewSubscription(
337         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
338         $startdate, $periodicity, $numberlength, $weeklength,
339         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
340         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
341         join(";",@irregularity), $numberpattern, $locale, $callnumber,
342         $manualhistory, $internalnotes, $serialsadditems,
343         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
344         $skip_serialseq
345     );
346
347     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
348     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
349
350     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
351     return;
352 }
353
354 sub redirect_mod_subscription {
355     my $subscriptionid = $query->param('subscriptionid');
356     my @irregularity = $query->param('irregularity');
357     my $auser = $query->param('user');
358     my $librarian => $query->param('librarian'),
359     my $branchcode = $query->param('branchcode');
360     my $cost = $query->param('cost');
361     my $aqbooksellerid = $query->param('aqbooksellerid');
362     my $biblionumber = $query->param('biblionumber');
363     my $aqbudgetid = $query->param('aqbudgetid');
364     my $startdate = format_date_in_iso($query->param('startdate'));
365     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
366     my $nextacquidate = $query->param('nextacquidate') ?
367                             format_date_in_iso($query->param('nextacquidate')):
368                             $firstacquidate;
369     my $enddate = format_date_in_iso($query->param('enddate'));
370     my $periodicity = $query->param('frequency');
371
372     my $subtype = $query->param('subtype');
373     my $sublength = $query->param('sublength');
374     my ($numberlength, $weeklength, $monthlength)
375         = _get_sub_length( $subtype, $sublength );
376     my $numberpattern = $query->param('numbering_pattern');
377     my $locale = $query->param('locale');
378     my $lastvalue1 = $query->param('lastvalue1');
379     my $innerloop1 = $query->param('innerloop1');
380     my $lastvalue2 = $query->param('lastvalue2');
381     my $innerloop2 = $query->param('innerloop2');
382     my $lastvalue3 = $query->param('lastvalue3');
383     my $innerloop3 = $query->param('innerloop3');
384     my $status = 1;
385     my $callnumber = $query->param('callnumber');
386     my $notes = $query->param('notes');
387     my $internalnotes = $query->param('internalnotes');
388     my $letter = $query->param('letter');
389     my $manualhistory = $query->param('manualhist') ? 1 : 0;
390     my $serialsadditems = $query->param('serialsadditems');
391         my $staffdisplaycount = $query->param('staffdisplaycount');
392         my $opacdisplaycount = $query->param('opacdisplaycount');
393     my $graceperiod     = $query->param('graceperiod') || 0;
394     my $location = $query->param('location');
395     my $skip_serialseq    = $query->param('skip_serialseq');
396
397     # Guess end date
398     if(!defined $enddate || $enddate eq '') {
399         if($subtype eq "issues") {
400             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
401         } else {
402             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
403         }
404     }
405
406     my $nextexpected = GetNextExpected($subscriptionid);
407     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
408     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
409         ModNextExpected($subscriptionid, $nextacquidate);
410         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
411         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
412     }
413
414     ModSubscription(
415         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
416         $periodicity, $firstacquidate, join(";",@irregularity),
417         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
418         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
419         $status, $biblionumber, $callnumber, $notes, $letter,
420         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
421         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
422         $skip_serialseq
423     );
424
425     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
426     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
427
428     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
429     return;
430 }
431
432 sub insert_additional_fields {
433     my ( $additional_fields, $biblionumber, $subscriptionid ) = @_;
434     my @additional_field_values;
435     my $record = GetMarcBiblio( $biblionumber, 1 );
436     for my $field ( @$additional_fields ) {
437         my $af = Koha::AdditionalField->new({ id => $field->{id} })->fetch;
438         if ( $af->{marcfield} ) {
439             my ( $field, $subfield ) = split /\$/, $af->{marcfield};
440             $af->{values} = undef;
441             if ( $field and $subfield ) {
442                 my $value = $record->subfield( $field, $subfield );
443                 $af->{values} = {
444                     $subscriptionid => $value
445                 };
446             }
447         } else {
448             $af->{values} = {
449                 $subscriptionid => $query->param('additional_field_' . $field->{id})
450             } if defined $query->param('additional_field_' . $field->{id});
451         }
452         $af->insert_values;
453     }
454 }