Bug 7688: Change subscription numbering pattern and frequencies
[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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use strict;
19 use warnings;
20
21 use CGI;
22 use Date::Calc qw(Today Day_of_Year Week_of_Year Add_Delta_Days Add_Delta_YM);
23 use C4::Koha;
24 use C4::Biblio;
25 use C4::Auth;
26 use C4::Dates qw/format_date format_date_in_iso/;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Context;
30 use C4::Branch; # GetBranches
31 use C4::Serials;
32 use C4::Serials::Frequency;
33 use C4::Serials::Numberpattern;
34 use C4::Letters;
35 use Carp;
36
37 #use Smart::Comments;
38
39 our $query = CGI->new;
40 my $op = $query->param('op') || '';
41 my $dbh = C4::Context->dbh;
42 my $sub_length;
43
44 my @budgets;
45
46 # Permission needed if it is a modification : edit_subscription
47 # Permission needed otherwise (nothing or dup) : create_subscription
48 my $permission = ($op eq "modify") ? "edit_subscription" : "create_subscription";
49
50 my ($template, $loggedinuser, $cookie)
51 = get_template_and_user({template_name => "serials/subscription-add.tt",
52                                 query => $query,
53                                 type => "intranet",
54                                 authnotrequired => 0,
55                                 flagsrequired => {serials => $permission},
56                                 debug => 1,
57                                 });
58
59
60
61 my $sub_on;
62 my @subscription_types = (qw(issues weeks months));
63 my @sub_type_data;
64
65 my $subs;
66 our $firstissuedate;
67
68 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
69
70     my $subscriptionid = $query->param('subscriptionid');
71     $subs = GetSubscription($subscriptionid);
72 ## FIXME : Check rights to edit if mod. Could/Should display an error message.
73     if ($subs->{'cannotedit'} && $op eq 'modify'){
74       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
75       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
76     }
77     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
78     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
79         next unless defined $subs->{$_};
80         # TODO : Handle date formats properly.
81          if ($subs->{$_} eq '0000-00-00') {
82             $subs->{$_} = ''
83         } else {
84             $subs->{$_} = $subs->{$_};
85         }
86           }
87       if (!defined $subs->{letter}) {
88           $subs->{letter}= q{};
89       }
90     letter_loop($subs->{'letter'}, $template);
91     my $nextexpected = GetNextExpected($subscriptionid);
92     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
93     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
94     unless($op eq 'modsubscription') {
95         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
96             if ($subs->{$length_unit}) {
97                 $sub_length=$subs->{$length_unit};
98                 $sub_on=$length_unit;
99                 last;
100             }
101         }
102
103         $template->param( %{$subs} );
104         $template->param(
105                     $op => 1,
106                     "subtype_$sub_on" => 1,
107                     sublength =>$sub_length,
108                     history => ($op eq 'modify'),
109                     firstacquiyear => substr($firstissuedate,0,4),
110                     );
111
112         if($op eq 'modify') {
113             my ($serials_number) = GetSerials($subscriptionid);
114             if($serials_number > 1) {
115                 $template->param(more_than_one_serial => 1);
116             }
117         }
118     }
119
120     if ( $op eq 'dup' ) {
121         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
122         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
123         $template->param( dont_export_field_loop => \@fields_id );
124     }
125 }
126
127 my $onlymine=C4::Context->preference('IndependantBranches') &&
128              C4::Context->userenv &&
129              C4::Context->userenv->{flags} % 2 !=1 &&
130              C4::Context->userenv->{branch};
131 my $branches = GetBranches($onlymine);
132 my $branchloop;
133 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
134     my $selected = 0;
135     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
136     push @{$branchloop}, {
137         value => $thisbranch,
138         selected => $selected,
139         branchname => $branches->{$thisbranch}->{'branchname'},
140     };
141 }
142
143 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
144
145 $template->param(branchloop => $branchloop,
146     locations_loop=>$locations_loop,
147 );
148 # prepare template variables common to all $op conditions:
149 if ($op!~/^mod/) {
150     letter_loop(q{}, $template);
151 }
152
153 if ($op eq 'addsubscription') {
154     redirect_add_subscription();
155 } elsif ($op eq 'modsubscription') {
156     redirect_mod_subscription();
157 } else {
158         while (@subscription_types) {
159            my $sub_type = shift @subscription_types;
160            my %row = ( 'name' => $sub_type );
161            if ( defined $sub_on and $sub_on eq $sub_type ) {
162              $row{'selected'} = ' selected';
163            } else {
164              $row{'selected'} = '';
165            }
166            push( @sub_type_data, \%row );
167         }
168     $template->param(subtype => \@sub_type_data);
169
170     letter_loop( '', $template ) if ($op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify');
171
172     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
173     if (defined $new_biblionumber) {
174         my $bib = GetBiblioData($new_biblionumber);
175         if (defined $bib) {
176             $template->param(bibnum      => $new_biblionumber);
177             $template->param(bibliotitle => $bib->{title});
178         }
179     }
180
181     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
182
183     my @frequencies = GetSubscriptionFrequencies;
184     my @frqloop;
185     foreach my $freq (@frequencies) {
186         my $selected = 0;
187         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
188         my $row = {
189             id => $freq->{'id'},
190             selected => $selected,
191             label => $freq->{'description'},
192         };
193         push @frqloop, $row;
194     }
195     $template->param(frequencies => \@frqloop);
196
197     my @numpatterns = GetSubscriptionNumberpatterns;
198     my @numberpatternloop;
199     foreach my $numpattern (@numpatterns) {
200         my $selected = 0;
201         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
202         my $row = {
203             id => $numpattern->{'id'},
204             selected => $selected,
205             label => $numpattern->{'label'},
206         };
207         push @numberpatternloop, $row;
208     }
209     $template->param(numberpatterns => \@numberpatternloop);
210
211     # Get installed locales
212     # FIXME this will not work with all environments.
213     # If call to locale fails, @locales will be an empty array, which is fine.
214     my @locales = map {
215         chomp;
216         # we don't want POSIX and C locales
217         /^C|^POSIX$/ ? () : $_
218     } `locale -a`;
219     $template->param(locales => \@locales);
220
221     output_html_with_http_headers $query, $cookie, $template->output;
222 }
223
224 sub letter_loop {
225     my ($selected_letter, $templte) = @_;
226     my $letters = GetLetters('serial');
227     my $letterloop;
228     foreach my $thisletter (keys %{$letters}) {
229         push @{$letterloop}, {
230             value => $thisletter,
231             selected => $thisletter eq $selected_letter,
232             lettername => $letters->{$thisletter},
233         };
234     }
235     $templte->param(letterloop => $letterloop);
236     return;
237 }
238
239 sub _get_sub_length {
240     my ($type, $length) = @_;
241     return
242         (
243             $type eq 'issues' ? $length : 0,
244             $type eq 'weeks'   ? $length : 0,
245             $type eq 'months'  ? $length : 0,
246         );
247 }
248
249 sub _guess_enddate {
250     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
251     my ($year, $month, $day);
252     my $enddate;
253     if($numberlength != 0) {
254         my $frequency = GetSubscriptionFrequency($frequencyid);
255         if($frequency->{'unit'} eq 'day') {
256             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
257         } elsif($frequency->{'unit'} eq 'week') {
258             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
259         } elsif($frequency->{'unit'} eq 'month') {
260             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
261         } elsif($frequency->{'unit'} eq 'year') {
262             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
263         }
264     } elsif($weeklength != 0) {
265         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
266     } elsif($monthlength != 0) {
267         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
268     }
269     if(defined $year) {
270         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
271     } else {
272         undef $enddate;
273     }
274     return $enddate;
275 }
276
277 sub redirect_add_subscription {
278     my $auser          = $query->param('user');
279     my $branchcode     = $query->param('branchcode');
280     my $aqbooksellerid = $query->param('aqbooksellerid');
281     my $cost           = $query->param('cost');
282     my $aqbudgetid     = $query->param('aqbudgetid');
283     my $periodicity    = $query->param('frequency');
284     my @irregularity   = $query->param('irregularity');
285     my $numberpattern  = $query->param('numbering_pattern');
286     my $locale         = $query->param('locale');
287     my $graceperiod    = $query->param('graceperiod') || 0;
288
289     my $subtype = $query->param('subtype');
290     my $sublength = $query->param('sublength');
291     my ( $numberlength, $weeklength, $monthlength )
292         = _get_sub_length( $subtype, $sublength );
293     my $add1              = $query->param('add1');
294     my $lastvalue1        = $query->param('lastvalue1');
295     my $innerloop1        = $query->param('innerloop1');
296     my $innerloop2        = $query->param('innerloop2');
297     my $lastvalue2        = $query->param('lastvalue2');
298     my $lastvalue3        = $query->param('lastvalue3');
299     my $innerloop3        = $query->param('innerloop3');
300     my $status            = 1;
301     my $biblionumber      = $query->param('biblionumber');
302     my $callnumber        = $query->param('callnumber');
303     my $notes             = $query->param('notes');
304     my $internalnotes     = $query->param('internalnotes');
305     my $letter            = $query->param('letter');
306     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
307     my $serialsadditems   = $query->param('serialsadditems');
308     my $staffdisplaycount = $query->param('staffdisplaycount');
309     my $opacdisplaycount  = $query->param('opacdisplaycount');
310     my $location          = $query->param('location');
311     my $skip_serialseq    = $query->param('skip_serialseq');
312     my $startdate = format_date_in_iso( $query->param('startdate') );
313     my $enddate = format_date_in_iso( $query->param('enddate') );
314     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
315     if(!defined $enddate || $enddate eq '') {
316         if($subtype eq "issues") {
317             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
318         } else {
319             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
320         }
321     }
322
323     my $subscriptionid = NewSubscription(
324         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
325         $startdate, $periodicity, $numberlength, $weeklength,
326         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
327         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
328         join(";",@irregularity), $numberpattern, $locale, $callnumber,
329         $manualhistory, $internalnotes, $serialsadditems,
330         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
331         $skip_serialseq
332     );
333
334     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
335     return;
336 }
337
338 sub redirect_mod_subscription {
339     my $subscriptionid = $query->param('subscriptionid');
340     my @irregularity = $query->param('irregularity');
341     my $auser = $query->param('user');
342     my $librarian => $query->param('librarian'),
343     my $branchcode = $query->param('branchcode');
344     my $cost = $query->param('cost');
345     my $aqbooksellerid = $query->param('aqbooksellerid');
346     my $biblionumber = $query->param('biblionumber');
347     my $aqbudgetid = $query->param('aqbudgetid');
348     my $startdate = format_date_in_iso($query->param('startdate'));
349     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
350     my $nextacquidate = $query->param('nextacquidate') ?
351                             format_date_in_iso($query->param('nextacquidate')):
352                             $firstacquidate;
353     my $enddate = format_date_in_iso($query->param('enddate'));
354     my $periodicity = $query->param('frequency');
355
356     my $subtype = $query->param('subtype');
357     my $sublength = $query->param('sublength');
358     my ($numberlength, $weeklength, $monthlength)
359         = _get_sub_length( $subtype, $sublength );
360     my $numberpattern = $query->param('numbering_pattern');
361     my $locale = $query->param('locale');
362     my $lastvalue1 = $query->param('lastvalue1');
363     my $innerloop1 = $query->param('innerloop1');
364     my $lastvalue2 = $query->param('lastvalue2');
365     my $innerloop2 = $query->param('innerloop2');
366     my $lastvalue3 = $query->param('lastvalue3');
367     my $innerloop3 = $query->param('innerloop3');
368     my $status = 1;
369     my $callnumber = $query->param('callnumber');
370     my $notes = $query->param('notes');
371     my $internalnotes = $query->param('internalnotes');
372     my $letter = $query->param('letter');
373     my $manualhistory = $query->param('manualhist') ? 1 : 0;
374     my $serialsadditems = $query->param('serialsadditems');
375         my $staffdisplaycount = $query->param('staffdisplaycount');
376         my $opacdisplaycount = $query->param('opacdisplaycount');
377     my $graceperiod     = $query->param('graceperiod') || 0;
378     my $location = $query->param('location');
379     my $skip_serialseq    = $query->param('skip_serialseq');
380
381     # Guess end date
382     if(!defined $enddate || $enddate eq '') {
383         if($subtype eq "issues") {
384             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
385         } else {
386             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
387         }
388     }
389
390     my $nextexpected = GetNextExpected($subscriptionid);
391     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
392     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
393         ModNextExpected($subscriptionid, $nextacquidate);
394         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
395         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
396     }
397
398     ModSubscription(
399         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
400         $periodicity, $firstacquidate, join(";",@irregularity),
401         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
402         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
403         $status, $biblionumber, $callnumber, $notes, $letter,
404         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
405         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
406         $skip_serialseq
407     );
408
409     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
410     return;
411 }