@@ -4,6 +4,7 @@ use Modern::Perl;
44
55use File::Slurp qw( write_file ) ;
66use File::Temp qw( tempfile ) ;
7+ use JSON qw( to_json ) ;
78use PDF::API2;
89use Try::Tiny;
910
@@ -148,7 +149,10 @@ sub create_print_job_and_file {
148149
149150=head2 calculate_job_cost
150151
151- Helper function to calculate the cost of a print job for a given printer
152+ Helper function to calculate the cost of a print job for a given printer.
153+ Returns a list containing the calculated cost and the gratis discount applied.
154+
155+ my ( $cost, $gratis_discount ) = calculate_job_cost( $c, { print_job => $job } );
152156
153157=cut
154158
@@ -179,18 +183,31 @@ sub calculate_job_cost {
179183
180184 my $total_pages = $pages * $copies ;
181185
182- # Fetch grais print settings and decrement pages or balance as needed
186+ my $gratis_discount = 0;
187+
183188 if ( $GratisPrintingMethod eq ' pages' ) {
184- $total_pages -= $c -> user-> gratis_print_balance;
189+ if ( $total_pages >= $c -> user-> gratis_print_balance ) {
190+ $gratis_discount = $c -> user-> gratis_print_balance;
191+ $total_pages -= $c -> user-> gratis_print_balance;
192+ } else {
193+ $gratis_discount = $total_pages ;
194+ $total_pages = 0;
195+ }
185196 }
186197
187198 my $cost = $total_pages * $cpp ;
188199
189200 if ( $GratisPrintingMethod eq ' balance' ) {
190- $cost -= $c -> user-> gratis_print_balance;
201+ if ( $cost >= $c -> user-> gratis_print_balance ) {
202+ $gratis_discount = $c -> user-> gratis_print_balance;
203+ $cost -= $c -> user-> gratis_print_balance;
204+ } else {
205+ $gratis_discount = $cost ;
206+ $cost = 0;
207+ }
191208 }
192209
193- return $cost ;
210+ return ( $cost , $gratis_discount ) ;
194211}
195212
196213=head2 cancel
@@ -311,7 +328,7 @@ sub release {
311328 printer => $printer ,
312329 };
313330
314- my $total_cost = calculate_job_cost( $c ,
331+ my ( $total_cost , $gratis_discount ) = calculate_job_cost( $c ,
315332 {
316333 print_job => $print_job ,
317334 printer => $printer ,
@@ -323,12 +340,33 @@ sub release {
323340 if ( $total_cost <= $user -> funds ) {
324341 $user -> debit_funds( $c , $total_cost );
325342
343+ $user -> gratis_print_balance( $user -> gratis_print_balance - $gratis_discount );
344+
326345 $print_job -> status(PRINT_STATUS_PENDING);
327346
328347 $c -> model(' DB' )-> txn_do(
329348 sub {
330349 $user -> update();
331350 $print_job -> update();
351+
352+ # Add statistic indicating gratis discount was used
353+ if ( $gratis_discount > 0 ) {
354+ $c -> model(' DB::Statistic' )-> create(
355+ {
356+ instance => $c -> instance,
357+ username => $c -> user-> username,
358+ action => ' GRATIS_DISCOUNT' ,
359+ created_on => $c -> now,
360+ session_id => $c -> sessionid,
361+ info => to_json(
362+ {
363+ print_job_id => $print_job -> id,
364+ gratis_discount => $gratis_discount ,
365+ }
366+ ),
367+ }
368+ );
369+ }
332370 }
333371 );
334372 }
0 commit comments