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