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