Bug 7677: UT: Remove $dbh->rollback
[koha.git] / serials / subscription-add.pl
blob1aa796421723c4b027588b21755dfb9205173c8a
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
18 use strict;
19 use warnings;
21 use CGI qw ( -utf8 );
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::Acquisition;
27 use C4::Output;
28 use C4::Context;
29 use C4::Serials;
30 use C4::Serials::Frequency;
31 use C4::Serials::Numberpattern;
32 use C4::Letters;
33 use Koha::AdditionalField;
34 use Koha::DateUtils;
35 use Carp;
37 #use Smart::Comments;
39 our $query = CGI->new;
40 my $op = $query->param('op') || '';
41 my $dbh = C4::Context->dbh;
42 my $sub_length;
45 # Permission needed if it is a modification : edit_subscription
46 # Permission needed otherwise (nothing or dup) : create_subscription
47 my $permission = ($op eq "modify") ? "edit_subscription" : "create_subscription";
49 my ($template, $loggedinuser, $cookie)
50 = get_template_and_user({template_name => "serials/subscription-add.tt",
51 query => $query,
52 type => "intranet",
53 authnotrequired => 0,
54 flagsrequired => {serials => $permission},
55 debug => 1,
56 });
60 my $sub_on;
62 my $subs;
63 our $firstissuedate;
65 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
67 my $subscriptionid = $query->param('subscriptionid');
68 $subs = GetSubscription($subscriptionid);
70 ## FIXME : Check rights to edit if mod. Could/Should display an error message.
71 if ($subs->{'cannotedit'} && $op eq 'modify'){
72 carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
73 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
75 $firstissuedate = $subs->{firstacquidate} || ''; # in iso format.
76 for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
77 next unless defined $subs->{$_};
78 # TODO : Handle date formats properly.
79 if ($subs->{$_} eq '0000-00-00') {
80 $subs->{$_} = ''
81 } else {
82 $subs->{$_} = $subs->{$_};
85 if (!defined $subs->{letter}) {
86 $subs->{letter}= q{};
88 my $nextexpected = GetNextExpected($subscriptionid);
89 $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
90 $subs->{nextacquidate} = $nextexpected->{planneddate} if($op eq 'modify');
91 unless($op eq 'modsubscription') {
92 foreach my $length_unit (qw(numberlength weeklength monthlength)) {
93 if ($subs->{$length_unit}) {
94 $sub_length=$subs->{$length_unit};
95 $sub_on=$length_unit;
96 last;
100 $template->param( %{$subs} );
101 $template->param(
102 $op => 1,
103 "subtype_$sub_on" => 1,
104 sublength =>$sub_length,
105 history => ($op eq 'modify'),
106 firstacquiyear => substr($firstissuedate,0,4),
109 if($op eq 'modify') {
110 my ($serials_number) = GetSerials($subscriptionid);
111 if($serials_number > 1) {
112 $template->param(more_than_one_serial => 1);
117 if ( $op eq 'dup' ) {
118 my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
119 my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
120 $template->param( dont_export_field_loop => \@fields_id );
123 my $letters = get_letter_loop( $subs->{letter} );
124 $template->param( letterloop => $letters );
128 my $locations_loop = GetAuthorisedValues("LOC");
130 $template->param(
131 branchcode => $subs->{branchcode},
132 locations_loop=>$locations_loop,
136 my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
137 for my $field ( @$additional_fields ) {
138 if ( $field->{authorised_value_category} ) {
139 $field->{authorised_value_choices} = GetAuthorisedValues( $field->{authorised_value_category} );
142 $template->param( additional_fields_for_subscription => $additional_fields );
144 my $typeloop = GetItemTypes();
146 my @typearg =
147 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
148 my @previoustypearg =
149 map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop};
151 $template->param(
152 branchloop => $branchloop,
153 typeloop => \@typearg,
154 previoustypeloop => \@previoustypearg,
155 locations_loop=>$locations_loop,
158 # prepare template variables common to all $op conditions:
159 $template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable'));
161 if ($op!~/^mod/) {
162 my $letters = get_letter_loop();
163 $template->param( letterloop => $letters );
166 if ($op eq 'addsubscription') {
167 redirect_add_subscription();
168 } elsif ($op eq 'modsubscription') {
169 redirect_mod_subscription();
170 } else {
172 $template->param(
173 subtypes => [ qw( numberlength weeklength monthlength ) ],
174 subtype => $sub_on,
177 if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
178 my $letters = get_letter_loop();
179 $template->param( letterloop => $letters );
182 my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
183 if (defined $new_biblionumber) {
184 my $bib = GetBiblioData($new_biblionumber);
185 if (defined $bib) {
186 $template->param(bibnum => $new_biblionumber);
187 $template->param(bibliotitle => $bib->{title});
191 $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
193 my @frequencies = GetSubscriptionFrequencies;
194 my @frqloop;
195 foreach my $freq (@frequencies) {
196 my $selected = 0;
197 $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
198 my $row = {
199 id => $freq->{'id'},
200 selected => $selected,
201 label => $freq->{'description'},
203 push @frqloop, $row;
205 $template->param(frequencies => \@frqloop);
207 my @numpatterns = GetSubscriptionNumberpatterns;
208 my @numberpatternloop;
209 foreach my $numpattern (@numpatterns) {
210 my $selected = 0;
211 $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
212 my $row = {
213 id => $numpattern->{'id'},
214 selected => $selected,
215 label => $numpattern->{'label'},
217 push @numberpatternloop, $row;
219 $template->param(numberpatterns => \@numberpatternloop);
221 my $languages = [ map {
223 language => $_->{iso639_2_code},
224 description => $_->{language_description} || $_->{language}
226 } @{ C4::Languages::getAllLanguages() } ];
228 $template->param( locales => $languages );
230 output_html_with_http_headers $query, $cookie, $template->output;
233 sub get_letter_loop {
234 my ($selected_lettercode) = @_;
235 $selected_lettercode //= '';
236 my $letters = GetLetters({ module => 'serial' });
237 return [
238 map {
240 value => $_->{code},
241 lettername => $_->{name},
242 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
244 } @$letters
248 sub _get_sub_length {
249 my ($type, $length) = @_;
250 return
252 $type eq 'issues' ? $length : 0,
253 $type eq 'weeks' ? $length : 0,
254 $type eq 'months' ? $length : 0,
258 sub _guess_enddate {
259 my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
260 my ($year, $month, $day);
261 my $enddate;
262 if($numberlength != 0) {
263 my $frequency = GetSubscriptionFrequency($frequencyid);
264 if($frequency->{'unit'} eq 'day') {
265 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
266 } elsif($frequency->{'unit'} eq 'week') {
267 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
268 } elsif($frequency->{'unit'} eq 'month') {
269 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
270 } elsif($frequency->{'unit'} eq 'year') {
271 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
273 } elsif($weeklength != 0) {
274 ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
275 } elsif($monthlength != 0) {
276 ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
278 if(defined $year) {
279 $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
280 } else {
281 undef $enddate;
283 return $enddate;
286 sub redirect_add_subscription {
287 my $auser = $query->param('user');
288 my $branchcode = $query->param('branchcode');
289 my $aqbooksellerid = $query->param('aqbooksellerid');
290 my $cost = $query->param('cost');
291 my $aqbudgetid = $query->param('aqbudgetid');
292 my $periodicity = $query->param('frequency');
293 my @irregularity = $query->multi_param('irregularity');
294 my $numberpattern = $query->param('numbering_pattern');
295 my $locale = $query->param('locale');
296 my $graceperiod = $query->param('graceperiod') || 0;
298 my $subtype = $query->param('subtype');
299 my $sublength = $query->param('sublength');
300 my ( $numberlength, $weeklength, $monthlength )
301 = _get_sub_length( $subtype, $sublength );
302 my $add1 = $query->param('add1');
303 my $lastvalue1 = $query->param('lastvalue1');
304 my $innerloop1 = $query->param('innerloop1');
305 my $innerloop2 = $query->param('innerloop2');
306 my $lastvalue2 = $query->param('lastvalue2');
307 my $lastvalue3 = $query->param('lastvalue3');
308 my $innerloop3 = $query->param('innerloop3');
309 my $status = 1;
310 my $biblionumber = $query->param('biblionumber');
311 my $callnumber = $query->param('callnumber');
312 my $notes = $query->param('notes');
313 my $internalnotes = $query->param('internalnotes');
314 my $letter = $query->param('letter');
315 my $manualhistory = $query->param('manualhist') ? 1 : 0;
316 my $serialsadditems = $query->param('serialsadditems');
317 my $staffdisplaycount = $query->param('staffdisplaycount');
318 my $opacdisplaycount = $query->param('opacdisplaycount');
319 my $location = $query->param('location');
320 my $itemtype = $query->param('itemtype');
321 my $previousitemtype = $query->param('previousitemtype');
322 my $skip_serialseq = $query->param('skip_serialseq');
324 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
325 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
326 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
328 if(!defined $enddate || $enddate eq '') {
329 if($subtype eq "issues") {
330 $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength)
331 } else {
332 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength)
336 my $subscriptionid = NewSubscription(
337 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
338 $startdate, $periodicity, $numberlength, $weeklength,
339 $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
340 $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
341 join(";",@irregularity), $numberpattern, $locale, $callnumber,
342 $manualhistory, $internalnotes, $serialsadditems,
343 $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
344 $skip_serialseq
347 my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
348 insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
350 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
351 return;
354 sub redirect_mod_subscription {
355 my $subscriptionid = $query->param('subscriptionid');
356 my @irregularity = $query->multi_param('irregularity');
357 my $auser = $query->param('user');
358 my $librarian => scalar $query->param('librarian'),
359 my $branchcode = $query->param('branchcode');
360 my $cost = $query->param('cost');
361 my $aqbooksellerid = $query->param('aqbooksellerid');
362 my $biblionumber = $query->param('biblionumber');
363 my $aqbudgetid = $query->param('aqbudgetid');
365 my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } );
366 my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } );
367 my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } );
369 my $nextacquidate = $query->param('nextacquidate');
370 $nextacquidate = $nextacquidate
371 ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } )
372 : $firstacquidate;
374 my $periodicity = $query->param('frequency');
376 my $subtype = $query->param('subtype');
377 my $sublength = $query->param('sublength');
378 my ($numberlength, $weeklength, $monthlength)
379 = _get_sub_length( $subtype, $sublength );
380 my $numberpattern = $query->param('numbering_pattern');
381 my $locale = $query->param('locale');
382 my $lastvalue1 = $query->param('lastvalue1');
383 my $innerloop1 = $query->param('innerloop1');
384 my $lastvalue2 = $query->param('lastvalue2');
385 my $innerloop2 = $query->param('innerloop2');
386 my $lastvalue3 = $query->param('lastvalue3');
387 my $innerloop3 = $query->param('innerloop3');
388 my $status = 1;
389 my $callnumber = $query->param('callnumber');
390 my $notes = $query->param('notes');
391 my $internalnotes = $query->param('internalnotes');
392 my $letter = $query->param('letter');
393 my $manualhistory = $query->param('manualhist') ? 1 : 0;
394 my $serialsadditems = $query->param('serialsadditems');
395 my $staffdisplaycount = $query->param('staffdisplaycount');
396 my $opacdisplaycount = $query->param('opacdisplaycount');
397 my $graceperiod = $query->param('graceperiod') || 0;
398 my $location = $query->param('location');
399 my $itemtype = $query->param('itemtype');
400 my $previousitemtype = $query->param('previousitemtype');
401 my $skip_serialseq = $query->param('skip_serialseq');
403 # Guess end date
404 if(!defined $enddate || $enddate eq '') {
405 if($subtype eq "issues") {
406 $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
407 } else {
408 $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
412 my $nextexpected = GetNextExpected($subscriptionid);
413 # If it's a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
414 if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
415 ModNextExpected($subscriptionid, $nextacquidate);
416 # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
417 $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
420 ModSubscription(
421 $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
422 $periodicity, $firstacquidate, join(";",@irregularity),
423 $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
424 $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
425 $status, $biblionumber, $callnumber, $notes, $letter,
426 $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
427 $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
428 $skip_serialseq, $itemtype, $previousitemtype
431 my $additional_fields = Koha::AdditionalField->all( { tablename => 'subscription' } );
432 insert_additional_fields( $additional_fields, $biblionumber, $subscriptionid );
434 print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
435 return;
438 sub insert_additional_fields {
439 my ( $additional_fields, $biblionumber, $subscriptionid ) = @_;
440 my $record = GetMarcBiblio( $biblionumber, 1 );
441 for my $field ( @$additional_fields ) {
442 my $af = Koha::AdditionalField->new({ id => $field->{id} })->fetch;
443 if ( $af->{marcfield} ) {
444 my ( $field, $subfield ) = split /\$/, $af->{marcfield};
445 $af->{values} = undef;
446 if ( $field and $subfield ) {
447 my $value = $record->subfield( $field, $subfield );
448 $af->{values} = {
449 $subscriptionid => $value
452 } else {
453 $af->{values} = {
454 $subscriptionid => scalar $query->param('additional_field_' . $field->{id})
455 } if defined $query->param('additional_field_' . $field->{id});
457 $af->insert_values;