7cc131da5a7b3a8948e37cf0539884967d1f5e4b
[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 $template->param( additional_fields_for_subscription => scalar Koha::AdditionalField->all( { tablename => 'subscription' } ) );
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 $periodicity = $query->param('frequency');
293     if ($periodicity eq 'mana') {
294         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
295             {
296                 description   => $query->param('sfdescription'),
297                 unit          => $query->param('unit'),
298                 unitsperissue => $query->param('unitsperissue'),
299                 issuesperunit => $query->param('issuesperunit'),
300             }
301         )->store();
302         $periodicity = $subscription_freq->id;
303     }
304     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
305
306     my $auser          = $query->param('user');
307     my $branchcode     = $query->param('branchcode');
308     my $aqbooksellerid = $query->param('aqbooksellerid');
309     my $cost           = $query->param('cost');
310     my $aqbudgetid     = $query->param('aqbudgetid');
311     my @irregularity   = $query->multi_param('irregularity');
312     my $locale         = $query->param('locale');
313     my $graceperiod    = $query->param('graceperiod') || 0;
314
315     my $subtype = $query->param('subtype');
316     my $sublength = $query->param('sublength');
317     my ( $numberlength, $weeklength, $monthlength )
318         = _get_sub_length( $subtype, $sublength );
319     my $add1              = $query->param('add1');
320     my $lastvalue1        = $query->param('lastvalue1');
321     my $innerloop1        = $query->param('innerloop1');
322     my $innerloop2        = $query->param('innerloop2');
323     my $lastvalue2        = $query->param('lastvalue2');
324     my $lastvalue3        = $query->param('lastvalue3');
325     my $innerloop3        = $query->param('innerloop3');
326     my $status            = 1;
327     my $biblionumber      = $query->param('biblionumber');
328     my $callnumber        = $query->param('callnumber');
329     my $notes             = $query->param('notes');
330     my $internalnotes     = $query->param('internalnotes');
331     my $letter            = $query->param('letter');
332     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
333     my $serialsadditems   = $query->param('serialsadditems');
334     my $staffdisplaycount = $query->param('staffdisplaycount');
335     my $opacdisplaycount  = $query->param('opacdisplaycount');
336     my $location          = $query->param('location');
337     my $itemtype          = $query->param('itemtype');
338     my $previousitemtype  = $query->param('previousitemtype');
339     my $skip_serialseq    = $query->param('skip_serialseq');
340
341     my $mana_id;
342     if ( $query->param('mana_id') ne "" ) {
343         $mana_id = $query->param('mana_id');
344         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
345     }
346
347     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
348     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
349     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
350
351     if(!defined $enddate || $enddate eq '') {
352         if($subtype eq "issues") {
353             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
354         } else {
355             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
356         }
357     }
358     my $subscriptionid = NewSubscription(
359         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
360         $startdate, $periodicity, $numberlength, $weeklength,
361         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
362         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
363         join(";",@irregularity), $numberpattern, $locale, $callnumber,
364         $manualhistory, $internalnotes, $serialsadditems,
365         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
366         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
367     );
368     if ( (C4::Context->preference('Mana')) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){
369         my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription');
370         $template->param( mana_msg => $result->{msg} );
371     }
372
373     Koha::AdditionalField->update_fields_from_query( {
374         tablename => 'subscription',
375         record_id => $subscriptionid,
376         query => $query,
377         marc_record => GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 })
378     } );
379
380     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
381     return;
382 }
383
384 sub redirect_mod_subscription {
385     my $subscriptionid = $query->param('subscriptionid');
386     my @irregularity = $query->multi_param('irregularity');
387     my $auser = $query->param('user');
388     my $librarian => scalar $query->param('librarian'),
389     my $branchcode = $query->param('branchcode');
390     my $cost = $query->param('cost');
391     my $aqbooksellerid = $query->param('aqbooksellerid');
392     my $biblionumber = $query->param('biblionumber');
393     my $aqbudgetid = $query->param('aqbudgetid');
394
395     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
396     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
397     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
398
399     my $nextacquidate  = $query->param('nextacquidate');
400     $nextacquidate = $nextacquidate
401         ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
402         : $firstacquidate;
403
404     my $periodicity = $query->param('frequency');
405     if ($periodicity eq 'mana') {
406         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
407             {
408                 description   => $query->param('sfdescription'),
409                 unit          => $query->param('unit'),
410                 unitsperissue => $query->param('unitsperissue'),
411                 issuesperunit => $query->param('issuesperunit'),
412             }
413         )->store();
414         $periodicity = $subscription_freq->id;
415     }
416     my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars });
417
418     my $subtype = $query->param('subtype');
419     my $sublength = $query->param('sublength');
420     my ($numberlength, $weeklength, $monthlength)
421         = _get_sub_length( $subtype, $sublength );
422     my $locale = $query->param('locale');
423     my $lastvalue1 = $query->param('lastvalue1');
424     my $innerloop1 = $query->param('innerloop1');
425     my $lastvalue2 = $query->param('lastvalue2');
426     my $innerloop2 = $query->param('innerloop2');
427     my $lastvalue3 = $query->param('lastvalue3');
428     my $innerloop3 = $query->param('innerloop3');
429     my $status = 1;
430     my $callnumber = $query->param('callnumber');
431     my $notes = $query->param('notes');
432     my $internalnotes = $query->param('internalnotes');
433     my $letter = $query->param('letter');
434     my $manualhistory = $query->param('manualhist') ? 1 : 0;
435     my $serialsadditems = $query->param('serialsadditems');
436         my $staffdisplaycount = $query->param('staffdisplaycount');
437         my $opacdisplaycount = $query->param('opacdisplaycount');
438     my $graceperiod     = $query->param('graceperiod') || 0;
439     my $location = $query->param('location');
440     my $itemtype          = $query->param('itemtype');
441     my $previousitemtype  = $query->param('previousitemtype');
442     my $skip_serialseq    = $query->param('skip_serialseq');
443
444     my $mana_id;
445     if ( defined( $query->param('mana_id') ) ) {
446         $mana_id = $query->param('mana_id');
447         Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers");
448     }
449     else {
450         $mana_id = undef;
451     }
452
453     # Guess end date
454     if(!defined $enddate || $enddate eq '') {
455         if($subtype eq "issues") {
456             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
457         } else {
458             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
459         }
460     }
461
462     my $nextexpected = GetNextExpected($subscriptionid);
463     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
464     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
465         ModNextExpected($subscriptionid, $nextacquidate);
466         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
467         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
468     }
469
470     ModSubscription(
471         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
472         $periodicity, $firstacquidate, join(";",@irregularity),
473         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
474         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
475         $status, $biblionumber, $callnumber, $notes, $letter,
476         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
477         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
478         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
479     );
480
481     Koha::AdditionalField->update_fields_from_query( {
482         tablename => 'subscription',
483         record_id => $subscriptionid,
484         query => $query,
485         marc_record => GetMarcBiblio({ biblionumber => $biblionumber, embed_items => 1 })
486     } );
487
488     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
489     return;
490 }