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