Bug 17047: subscriptions management with Mana-KB
[koha_ffzg] / 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 manage_subscription_numbering_pattern_id {
296     my $params;
297     if ( $query->param('numbering_pattern') eq 'mana' ) {
298         foreach (qw/numberingmethod label1 add1 every1 whenmorethan1 setto1
299                    numbering1 label2 add2 every2 whenmorethan2 setto2 numbering2
300                    label3 add3 every3 whenmorethan3 setto3 numbering3/) {
301             $params->{$_} = $query->param($_) if $query->param($_);
302         }
303
304         my $existing = Koha::Subscription::Numberpatterns->search($params)->next();
305
306         if ($existing) {
307             return $existing->id;
308         }
309
310         $params->{label} = Koha::Subscription::Numberpattern->uniqueLabel($query->param('patternname'));
311         $params->{description} = $query->param('sndescription');
312
313
314         my $subscription_np = Koha::Subscription::Numberpattern->new()->set($params)->store();
315         return $subscription_np->id;
316     }
317
318     return $query->param('numbering_pattern');
319 }
320
321 sub manage_subscription_frequencies_id {
322     my $periodicity;
323     if ( $query->param('frequency') eq 'mana' ) {
324         my $subscription_freq = Koha::Subscription::Frequency->new()->set(
325             {
326                 description   => $query->param('sfdescription'),
327                 unit          => $query->param('unit'),
328                 unitsperissue => $query->param('unitsperissue'),
329                 issuesperunit => $query->param('issuesperunit'),
330             }
331         )->store();
332         $periodicity = $subscription_freq->id;
333     }
334     else {
335         $periodicity = $query->param('frequency');
336     }
337     return $periodicity;
338 }
339
340 sub redirect_add_subscription {
341     my $periodicity = manage_subscription_frequencies_id();
342     my $numberpattern = manage_subscription_numbering_pattern_id();
343
344     my $auser          = $query->param('user');
345     my $branchcode     = $query->param('branchcode');
346     my $aqbooksellerid = $query->param('aqbooksellerid');
347     my $cost           = $query->param('cost');
348     my $aqbudgetid     = $query->param('aqbudgetid');
349     my @irregularity   = $query->multi_param('irregularity');
350     my $locale         = $query->param('locale');
351     my $graceperiod    = $query->param('graceperiod') || 0;
352
353     my $subtype = $query->param('subtype');
354     my $sublength = $query->param('sublength');
355     my ( $numberlength, $weeklength, $monthlength )
356         = _get_sub_length( $subtype, $sublength );
357     my $add1              = $query->param('add1');
358     my $lastvalue1        = $query->param('lastvalue1');
359     my $innerloop1        = $query->param('innerloop1');
360     my $innerloop2        = $query->param('innerloop2');
361     my $lastvalue2        = $query->param('lastvalue2');
362     my $lastvalue3        = $query->param('lastvalue3');
363     my $innerloop3        = $query->param('innerloop3');
364     my $status            = 1;
365     my $biblionumber      = $query->param('biblionumber');
366     my $callnumber        = $query->param('callnumber');
367     my $notes             = $query->param('notes');
368     my $internalnotes     = $query->param('internalnotes');
369     my $letter            = $query->param('letter');
370     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
371     my $serialsadditems   = $query->param('serialsadditems');
372     my $staffdisplaycount = $query->param('staffdisplaycount');
373     my $opacdisplaycount  = $query->param('opacdisplaycount');
374     my $location          = $query->param('location');
375     my $itemtype          = $query->param('itemtype');
376     my $previousitemtype  = $query->param('previousitemtype');
377     my $skip_serialseq    = $query->param('skip_serialseq');
378
379     my $mana_id;
380     if ( $query->param('mana_id') ne "" ) {
381         $mana_id = $query->param('mana_id');
382         Koha::SharedContent::manaNewUserPatchRequest("subscription",$mana_id);
383     }
384     else {
385         $mana_id = undef;
386     }
387
388     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
389     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
390     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
391
392     if(!defined $enddate || $enddate eq '') {
393         if($subtype eq "issues") {
394             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
395         } else {
396             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
397         }
398     }
399     my $subscriptionid = NewSubscription(
400         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
401         $startdate, $periodicity, $numberlength, $weeklength,
402         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
403         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
404         join(";",@irregularity), $numberpattern, $locale, $callnumber,
405         $manualhistory, $internalnotes, $serialsadditems,
406         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
407         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
408     );
409
410     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
411     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
412
413     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
414     return;
415 }
416
417 sub redirect_mod_subscription {
418     my $subscriptionid = $query->param('subscriptionid');
419     my @irregularity = $query->multi_param('irregularity');
420     my $auser = $query->param('user');
421     my $librarian => scalar $query->param('librarian'),
422     my $branchcode = $query->param('branchcode');
423     my $cost = $query->param('cost');
424     my $aqbooksellerid = $query->param('aqbooksellerid');
425     my $biblionumber = $query->param('biblionumber');
426     my $aqbudgetid = $query->param('aqbudgetid');
427
428     my $startdate      = output_pref( { str => scalar $query->param('startdate'),      dateonly => 1, dateformat => 'iso' } );
429     my $enddate        = output_pref( { str => scalar $query->param('enddate'),        dateonly => 1, dateformat => 'iso' } );
430     my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
431
432     my $nextacquidate  = $query->param('nextacquidate');
433     $nextacquidate = $nextacquidate
434         ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
435         : $firstacquidate;
436
437     my $periodicity = manage_subscription_frequencies_id();
438     my $numberpattern = manage_subscription_numbering_pattern_id();
439
440     my $subtype = $query->param('subtype');
441     my $sublength = $query->param('sublength');
442     my ($numberlength, $weeklength, $monthlength)
443         = _get_sub_length( $subtype, $sublength );
444     my $locale = $query->param('locale');
445     my $lastvalue1 = $query->param('lastvalue1');
446     my $innerloop1 = $query->param('innerloop1');
447     my $lastvalue2 = $query->param('lastvalue2');
448     my $innerloop2 = $query->param('innerloop2');
449     my $lastvalue3 = $query->param('lastvalue3');
450     my $innerloop3 = $query->param('innerloop3');
451     my $status = 1;
452     my $callnumber = $query->param('callnumber');
453     my $notes = $query->param('notes');
454     my $internalnotes = $query->param('internalnotes');
455     my $letter = $query->param('letter');
456     my $manualhistory = $query->param('manualhist') ? 1 : 0;
457     my $serialsadditems = $query->param('serialsadditems');
458         my $staffdisplaycount = $query->param('staffdisplaycount');
459         my $opacdisplaycount = $query->param('opacdisplaycount');
460     my $graceperiod     = $query->param('graceperiod') || 0;
461     my $location = $query->param('location');
462     my $itemtype          = $query->param('itemtype');
463     my $previousitemtype  = $query->param('previousitemtype');
464     my $skip_serialseq    = $query->param('skip_serialseq');
465
466     my $mana_id;
467     if ( defined( $query->param('mana_id') ) ) {
468         $mana_id = $query->param('mana_id');
469         Koha::SharedContent::manaNewUserPatchRequest("subscription",$mana_id);
470     }
471     else {
472         $mana_id = undef;
473     }
474
475     # Guess end date
476     if(!defined $enddate || $enddate eq '') {
477         if($subtype eq "issues") {
478             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
479         } else {
480             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
481         }
482     }
483
484     my $nextexpected = GetNextExpected($subscriptionid);
485     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
486     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
487         ModNextExpected($subscriptionid, $nextacquidate);
488         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
489         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
490     }
491
492     ModSubscription(
493         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
494         $periodicity, $firstacquidate, join(";",@irregularity),
495         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
496         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
497         $status, $biblionumber, $callnumber, $notes, $letter,
498         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
499         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
500         $skip_serialseq, $itemtype, $previousitemtype, $mana_id
501     );
502
503     my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
504     insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
505
506     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
507     return;
508 }
509
510 sub insert_additional_fields {
511     my ( $additional_fields, $biblionumber, $subscriptionid ) = @_;
512     my $record = GetMarcBiblio({
513         biblionumber => $biblionumber,
514         embed_items  => 1 });
515     for my $field ( @$additional_fields ) {
516         my $af = Koha::AdditionalField->new({ id => $field->{id} })->fetch;
517         if ( $af->{marcfield} ) {
518             my ( $field, $subfield ) = split /\$/, $af->{marcfield};
519             $af->{values} = undef;
520             if ( $field and $subfield ) {
521                 my $value = $record->subfield( $field, $subfield );
522                 $af->{values} = {
523                     $subscriptionid => $value
524                 };
525             }
526         } else {
527             $af->{values} = {
528                 $subscriptionid => scalar $query->param('additional_field_' . $field->{id})
529             } if defined $query->param('additional_field_' . $field->{id});
530         }
531         $af->insert_values;
532     }
533 }