summaryrefslogtreecommitdiff
path: root/scripts/payment.pl
blob: 6da1d5b6336299e240dd314f7fc87ef1bd10e2fb (plain)
  1. =pod
  2. =head1 NAME
  3. LedgerSMB::Scripts::payment - LedgerSMB class defining the Controller functions for payment handling.
  4. =head1 SYNOPSIS
  5. Defines the controller functions and workflow logic for payment processing.
  6. =head1 COPYRIGHT
  7. Portions Copyright (c) 2007, David Mora R and Christian Ceballos B.
  8. Licensed to the public under the terms of the GNU GPL version 2 or later.
  9. Original copyright notice below.
  10. #=====================================================================
  11. # PLAXIS
  12. # Copyright (c) 2007
  13. #
  14. # Author: David Mora R
  15. # Christian Ceballos B
  16. #
  17. #
  18. #
  19. #
  20. #
  21. # This program is free software; you can redistribute it and/or modify
  22. # it under the terms of the GNU General Public License as published by
  23. # the Free Software Foundation; either version 2 of the License, or
  24. # (at your option) any later version.
  25. #
  26. # This program is distributed in the hope that it will be useful,
  27. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. # GNU General Public License for more details.
  30. # You should have received a copy of the GNU General Public License
  31. # along with this program; if not, write to the Free Software
  32. # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  33. =head1 METHODS
  34. =cut
  35. package LedgerSMB::Scripts::payment;
  36. use LedgerSMB::Template;
  37. use LedgerSMB::Sysconfig;
  38. use LedgerSMB::DBObject::Payment;
  39. use LedgerSMB::DBObject::Date;
  40. use Error::Simple;
  41. use strict;
  42. # CT: A few notes for future refactoring of this code:
  43. # 1: I don't think it is a good idea to make the UI too dependant on internal
  44. # code structures but I don't see a good alternative at the moment.
  45. # 2: CamelCasing: -1
  46. =pod
  47. =item payment
  48. This method is used to set the filter screen and prints it, using the
  49. TT2 system.
  50. =back
  51. =cut
  52. sub payments {
  53. my ($request) = @_;
  54. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  55. $payment->get_metadata();
  56. if (!defined $payment->{batch_date}){
  57. $payment->error("No Batch Date!");
  58. }
  59. my $template = LedgerSMB::Template->new(
  60. user => $request->{_user},
  61. locale => $request->{_locale},
  62. path => 'UI/payments',
  63. template => 'payments_filter',
  64. format => 'HTML',
  65. );
  66. $template->render($payment);
  67. }
  68. sub get_search_criteria {
  69. my ($request) = @_;
  70. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  71. $payment->get_metadata();
  72. if ($payment->{batch_id} && $payment->{batch_date}){
  73. $payment->{date_reversed} = $payment->{batch_date};
  74. }
  75. my $template = LedgerSMB::Template->new(
  76. user => $request->{_user},
  77. locale => $request->{_locale},
  78. path => 'UI/payments',
  79. template => 'search',
  80. format => 'HTML',
  81. );
  82. $template->render($payment);
  83. }
  84. sub get_search_results {
  85. my ($request) = @_;
  86. my $rows = [];
  87. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  88. my @search_results = $payment->search;
  89. my $template = LedgerSMB::Template->new(
  90. user => $request->{_user},
  91. locale => $request->{_locale},
  92. path => 'UI',
  93. template => 'form-dynatable',
  94. format => ($payment->{format}) ? $payment->{format} : 'HTML',
  95. );
  96. my $base_url = "payment.pl?";
  97. my $search_url = "$base_url";
  98. for my $key (keys %{$request->take_top_level}){
  99. if ($base_url =~ /\?$/){
  100. $base_url .= "$key=$request->{key}";
  101. } else {
  102. $base_url .= "&$key=$request->{key}";
  103. }
  104. }
  105. my @columns = qw(selected meta_number date_paid amount source company_paid);
  106. my $contact_type = ($payment->{account_class} == 1) ? 'Vendor' : 'Customer';
  107. # CT: Locale strings for gettext:
  108. # $request->{_locale}->text("Vendor Number");
  109. # $request->{_locale}->text("Customer Number");
  110. my $heading = {
  111. selected => $request->{_locale}->text('Selected'),
  112. company_paid => {
  113. text => $request->{_locale}->text('Company Name'),
  114. href => "$search_url&orderby=company_paid",
  115. },
  116. meta_number => {
  117. text => $request->{_locale}->text(
  118. "$contact_type Number"
  119. ),
  120. href => "$search_url&orderby=meta_number",
  121. },
  122. date_paid => {
  123. text => $request->{_locale}->text('Date Paid'),
  124. href => "$search_url&orderby=date_paid",
  125. },
  126. amount => {
  127. text => $request->{_locale}->text('Total Paid'),
  128. href => "$search_url&orderby=amount",
  129. },
  130. source => {
  131. text => $request->{_locale}->text('Source'),
  132. href => "$search_url&orderby=source",
  133. },
  134. };
  135. my $classcount;
  136. $classcount = 0;
  137. my $rowcount;
  138. $rowcount = 1;
  139. for my $line (@search_results){
  140. $classcount ||= 0;
  141. $rowcount += 1;
  142. push(@$rows, {
  143. company_paid => $line->{company_paid},
  144. amount => $request->format_amount(amount => $line->{amount}),
  145. i => "$classcount",
  146. date_paid => $line->{date_paid},
  147. source => $line->{source},
  148. meta_number => $line->{meta_number},
  149. selected => {
  150. input => {
  151. type => "checkbox",
  152. name => "payment_$rowcount",
  153. value => "1",
  154. },
  155. }
  156. });
  157. $payment->{"credit_id_$rowcount"} = $line->{credit_id};
  158. $payment->{"date_paid_$rowcount"} = $line->{date_paid};
  159. $payment->{"source_$rowcount"} = $line->{source};
  160. $classcount = ($classcount + 1) % 2;
  161. ++$rowcount;
  162. }
  163. $payment->{rowcount} = $rowcount;
  164. $payment->{script} = 'payment.pl';
  165. $payment->{title} = $request->{_locale}->text("Payment Results");
  166. my $hiddens = $payment->take_top_level;
  167. $template->render({
  168. form => $payment,
  169. columns => \@columns,
  170. heading => $heading,
  171. hiddens => $payment->take_top_level,
  172. rows => $rows,
  173. buttons => [{
  174. value => 'reverse_payments',
  175. name => 'action',
  176. class => 'submit',
  177. type => 'submit',
  178. text => $request->{_locale}->text('Reverse Payments'),
  179. }]
  180. });
  181. }
  182. sub get_search_results_reverse_payments {
  183. my ($request) = @_;
  184. my $payment = LedgerSMB::DBObject::Payment->new({base => $request});
  185. for my $count (1 .. $payment->{rowcount}){
  186. if ($payment->{"payment_$count"}){
  187. $payment->{credit_id} = $payment->{"credit_id_$count"};
  188. $payment->{date_paid} = $payment->{"date_paid_$count"};
  189. $payment->{source} = $payment->{"source_$count"};
  190. $payment->reverse;
  191. }
  192. }
  193. get_search_criteria($payment);
  194. }
  195. sub check_job {
  196. my ($request) = @_;
  197. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  198. $payment->check_job;
  199. my $template = LedgerSMB::Template->new(
  200. user => $request->{_user},
  201. locale => $request->{_locale},
  202. path => 'UI/payments',
  203. template => 'check_job',
  204. format => 'HTML',
  205. );
  206. $template->render($payment);
  207. }
  208. sub post_payments_bulk {
  209. my ($request) = @_;
  210. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  211. $payment->post_bulk();
  212. my $template;
  213. if ($payment->{queue_payments}){
  214. $payment->{job_label} = 'Payments';
  215. $template = LedgerSMB::Template->new(
  216. user => $request->{_user},
  217. locale => $request->{_locale},
  218. path => 'UI/payments',
  219. template => 'check_job',
  220. format => 'HTML',
  221. );
  222. } else {
  223. payments($request);
  224. }
  225. $template->render($payment);
  226. }
  227. sub print {
  228. use LedgerSMB::DBObject::Company;
  229. use LedgerSMB::Batch;
  230. my ($request) = @_;
  231. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  232. $payment->{company} = $payment->{_user}->{company};
  233. $payment->{address} = $payment->{_user}->{address};
  234. my $template;
  235. if ($payment->{batch_id}){
  236. my $batch = LedgerSMB::Batch->new(
  237. {base => $payment,
  238. copy => 'base' }
  239. );
  240. $batch->{id} = $payment->{batch_id};
  241. $batch->get;
  242. $payment->{batch_description} = $batch->{description};
  243. $payment->{batch_control_code} = $batch->{control_code};
  244. }
  245. $payment->{format_amount} = sub {return $payment->format_amount(@_); };
  246. if ($payment->{multiple}){
  247. $payment->{checks} = [];
  248. print "Multiple checks printing";
  249. for my $line (1 .. $payment->{contact_count}){
  250. my $id = $payment->{"contact_$line"};
  251. next if !defined $payment->{"id_$id"};
  252. my $check = LedgerSMB::DBObject::Company->new(
  253. {base => $request, copy => 'base' }
  254. );
  255. $check->{entity_class} = $payment->{account_class};
  256. $check->{id} = $id;
  257. $check->get_billing_info;
  258. $check->{amount} = $check->parse_amount(amount => '0');
  259. $check->{invoices} = [];
  260. $check->{source} = $payment->{"source_$id"};
  261. my $inv_count;
  262. if ($LedgerSMB::Sysconfig::check_max_invoices >
  263. $payment->{"invoice_count_$id"})
  264. {
  265. $inv_count = $payment->{"invoice_count_$id"};
  266. } else {
  267. $inv_count = $LedgerSMB::Sysconfig::check_max_invoices;
  268. }
  269. for my $inv (1 .. $inv_count){
  270. my $invhash = {};
  271. my $inv_id = $payment->{"invoice_${id}_$inv"};
  272. for (qw(invnumber invdate)){
  273. $invhash->{$_} = $payment->{"${_}_$inv_id"};
  274. }
  275. if ($payment->{"paid_$id"} eq 'some'){
  276. $invhash->{paid} = $payment->parse_amount(amount => $payment->{"payment_$inv_id"});
  277. } elsif ($payment->{"paid_$id"} eq 'all'){
  278. $invhash->{paid} = $payment->parse_amount(amount => $payment->{"net_$inv_id"});
  279. } else {
  280. $payment->error("Invalid Payment Amount Option");
  281. }
  282. $check->{amount} += $invhash->{paid};
  283. $invhash->{paid} = $check->format_amount(amount => $invhash->{paid});
  284. push @{$check->{invoices}}, $invhash;
  285. }
  286. my $amt = $check->{amount}->copy;
  287. $amt->bfloor();
  288. $check->{text_amount} = $payment->text_amount($amt);
  289. $check->{amount} = $check->format_amount(amount => $check->{amount},
  290. format => '1000.00');
  291. $check->{decimal} = $check->format_amount(amount => ($check->{amount} - $amt) * 100);
  292. push @{$payment->{checks}}, $check;
  293. }
  294. $template = LedgerSMB::Template->new(
  295. user => $payment->{_user}, template => 'check_multiple',
  296. format => uc $payment->{'format'},
  297. no_auto_output => 1,
  298. output_args => $payment,
  299. );
  300. try {
  301. $template->render($payment);
  302. $template->output(%$payment);
  303. }
  304. catch Error::Simple with {
  305. my $E = shift;
  306. $payment->error( $E->stacktrace );
  307. };
  308. } else {
  309. }
  310. }
  311. sub update_payments {
  312. display_payments(@_);
  313. }
  314. sub display_payments {
  315. my ($request) = @_;
  316. my $payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  317. $payment->get_payment_detail_data();
  318. $payment->{grand_total} = 0;
  319. for (@{$payment->{contact_invoices}}){
  320. my $contact_total = 0;
  321. $_->{total_due} = $payment->format_amount(amount => $_->{total_due});
  322. if (($payment->{action} ne 'update_payments')
  323. or (defined $payment->{"id_$_->{contact_id}"})){
  324. if ($payment->{"paid_$_->{contact_id}"} eq 'some'){
  325. for my $invoice (@{$_->{invoices}}){
  326. my $i_id = $invoice->[0];
  327. $contact_total
  328. += $payment->{"paid_$_->{contact_id}_$i_id"};
  329. }
  330. } else {
  331. $contact_total = $_->{total_due};
  332. }
  333. $payment->{grand_total} += $contact_total;
  334. }
  335. $_->{contact_total} = $contact_total;
  336. }
  337. $payment->debug({file => '/tmp/payment'});
  338. @{$payment->{media_options}} = (
  339. {text => $request->{_locale}->text('Screen'),
  340. value => 'screen'});
  341. for (keys %LedgerSMB::Sysconfig::printer){
  342. push @{$payment->{media_options}},
  343. {text => $_,
  344. value => $LedgerSMB::Sysconfig::printer{$_}};
  345. }
  346. if ($LedgerSMB::Sysconfig::latex){
  347. @{$payment->{format_options}} = (
  348. {text => 'PDF', value => 'PDF'},
  349. {text => 'Postscript', value => 'Postscript'},
  350. );
  351. $payment->{can_print} = 1;
  352. }
  353. my $template = LedgerSMB::Template->new(
  354. user => $request->{_user},
  355. locale => $request->{_locale},
  356. path => 'UI/payments',
  357. template => 'payments_detail',
  358. format => 'HTML',
  359. );
  360. $template->render($payment);
  361. }
  362. =item payment
  363. This method is used to set the filter screen and prints it, using the
  364. TT2 system.
  365. =back
  366. =cut
  367. sub payment {
  368. my ($request) = @_;
  369. my $locale = $request->{_locale};
  370. my $dbPayment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  371. # Lets get the project data...
  372. my @projectOptions;
  373. my @arrayOptions = $dbPayment->list_open_projects();
  374. push @projectOptions, {}; #A blank field on the select box
  375. for my $ref (0 .. $#arrayOptions) {
  376. push @projectOptions, { value => $arrayOptions[$ref]->{id}."--".$arrayOptions[$ref]->{projectnumber}."--".$arrayOptions[$ref]->{description},
  377. text => $arrayOptions[$ref]->{projectnumber}."--".$arrayOptions[$ref]->{description}};
  378. }
  379. # Lets get the departments data...
  380. my @departmentOptions;
  381. my $role = $request->{type} eq 'receipt' ? 'P' : 'C';
  382. @arrayOptions = $dbPayment->list_departments($role);
  383. push @departmentOptions, {}; # A blank field on the select box
  384. for my $ref (0 .. $#arrayOptions) {
  385. push @departmentOptions, { value => $arrayOptions[$ref]->{id}."--".$arrayOptions[$ref]->{description},
  386. text => $arrayOptions[$ref]->{description}};
  387. }
  388. # Lets get the currencies (this uses the $dbPayment->{account_class} property)
  389. my @currOptions;
  390. @arrayOptions = $dbPayment->get_open_currencies();
  391. for my $ref (0 .. $#arrayOptions) {
  392. push @currOptions, { value => $arrayOptions[$ref]->{payments_get_open_currencies},
  393. text => $arrayOptions[$ref]->{payments_get_open_currencies} };
  394. }
  395. # Lets build filter by period
  396. my $date = LedgerSMB::DBObject::Date->new({base => $request});
  397. $date->build_filter_by_period($locale);
  398. # Lets set the data in a hash for the template system. :)
  399. my $select = {
  400. stylesheet => $request->{_user}->{stylesheet},
  401. login => { name => 'login',
  402. value => $request->{_user}->{login} },
  403. projects => {
  404. name => 'projects',
  405. options => \@projectOptions
  406. },
  407. department => {
  408. name => 'department',
  409. options => \@departmentOptions
  410. },
  411. curr => {
  412. name => 'curr',
  413. options => \@currOptions
  414. },
  415. month => {
  416. name => 'month',
  417. options => $date->{monthsOptions}
  418. },
  419. year => {
  420. name => 'year',
  421. options => $date->{yearsOptions}
  422. },
  423. interval_radios => $date->{radioOptions},
  424. amountfrom => {
  425. name => 'amountfrom',
  426. },
  427. amountto => {
  428. name => 'amountto',
  429. },
  430. accountclass => {
  431. name => 'account_class',
  432. value => $dbPayment->{account_class}
  433. },
  434. type => {
  435. name => 'type',
  436. value => $request->{type}
  437. },
  438. action => {
  439. name => 'action',
  440. value => 'payment1_5',
  441. text => $locale->text("Continue"),
  442. }
  443. };
  444. my $template;
  445. $template = LedgerSMB::Template->new(
  446. user => $request->{_user},
  447. locale => $request->{_locale},
  448. path => 'UI/payments',
  449. template => 'payment1',
  450. format => 'HTML' );
  451. $template->render($select);# And finally, Lets print the screen :)
  452. }
  453. =pod
  454. =item payment1_5
  455. This method is called between payment and payment2, it will search the database
  456. for entity_credit_accounts that match the parameter, if only one is found it will
  457. run unnoticed by the user, if more than one is found it will ask the user to pick
  458. one to handle the payment against
  459. =back
  460. =cut
  461. sub payment1_5 {
  462. my ($request) = @_;
  463. my $locale = $request->{_locale};
  464. my $dbPayment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  465. my @array_options = $dbPayment->get_entity_credit_account();
  466. if ($#array_options == -1) {
  467. &payment($request);
  468. } elsif ($#array_options == 0) {
  469. $request->{'vendor-customer'} = $array_options[0]->{id}.'--'.$array_options[0]->{name};
  470. &payment2($request);
  471. } else {
  472. # Lets call upon the template system
  473. my @company_options;
  474. for my $ref (0 .. $#array_options) {
  475. push @company_options, { id => $array_options[$ref]->{id},
  476. name => $array_options[$ref]->{name}};
  477. }
  478. my $select = {
  479. companies => \@company_options,
  480. stylesheet => $request->{_user}->{stylesheet},
  481. login => { name => 'login',
  482. value => $request->{_user}->{login}},
  483. department => { name => 'department',
  484. value => $request->{department}},
  485. currency => { name => 'curr',
  486. value => $request->{curr}},
  487. datefrom => { name => 'datefrom',
  488. value => $request->{datefrom}},
  489. dateto => { name => 'dateto',
  490. value => $request->{dateto}},
  491. amountfrom => { name => 'amountfrom',
  492. value => $request->{datefrom}},
  493. amountto => { name => 'amountto',
  494. value => $request->{dateto}},
  495. accountclass => { name => 'account_class',
  496. value => $dbPayment->{account_class}},
  497. type => { name => 'type',
  498. value => $request->{type}},
  499. action => { name => 'action',
  500. value => 'payment2',
  501. text => $locale->text("Continue")}
  502. };
  503. my $template;
  504. $template = LedgerSMB::Template->new(
  505. user => $request->{_user},
  506. locale => $request->{_locale},
  507. path => 'UI/payments',
  508. template => 'payment1_5',
  509. format => 'HTML' );
  510. eval {$template->render($select) };
  511. if ($@) { $request->error("$@"); } # PRINT ERRORS ON THE UI
  512. }
  513. }
  514. =pod
  515. =item payment2
  516. This method is used for the payment module, it is a consecuence of the payment sub,
  517. and its used for all the mechanics of an invoices payment module.
  518. =back
  519. =cut
  520. sub payment2 {
  521. my ($request) = @_;
  522. my $locale = $request->{_locale};
  523. my $Payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  524. # VARIABLES
  525. my ($project_id, $project_number, $project_name, $department_id, $department_name );
  526. my @array_options;
  527. my @project;
  528. my @selected_checkboxes;
  529. my @department;
  530. my @array_options;
  531. my @currency_options;
  532. my $exchangerate;
  533. # LETS GET THE CUSTOMER/VENDOR INFORMATION
  534. ($Payment->{entity_credit_id}, $Payment->{company_name}) = split /--/ , $request->{'vendor-customer'};
  535. # WE NEED TO RETRIEVE A BILLING LOCATION, THIS IS HARDCODED FOR NOW... Should we change it?
  536. $Payment->{location_class_id} = '1';
  537. my @vc_options;
  538. @vc_options = $Payment->get_vc_info();
  539. # LETS BUILD THE PROJECTS INFO
  540. # I DONT KNOW IF I NEED ALL THIS, BUT AS IT IS AVAILABLE I'LL STORE IT FOR LATER USAGE.
  541. if ($request->{projects}) {
  542. ($project_id, $project_number, $project_name) = split /--/ , $request->{projects} ;
  543. @project = { name => 'projects', text => $project_number.' '.$project_name, value => $request->{projects}};
  544. }
  545. # LETS GET THE DEPARTMENT INFO
  546. # WE HAVE TO SET $dbPayment->{department_id} NOW, THIS DATA WILL BE USED LATER WHEN WE
  547. # CALL FOR payment_get_open_invoices. :)
  548. if ($request->{department}) {
  549. ($Payment->{department_id}, $department_name) = split /--/, $request->{department};
  550. @department = { name => 'department', text => $department_name, value => $request->{department}};
  551. }
  552. # LETS GET ALL THE ACCOUNTS
  553. my @account_options = $Payment->list_accounting();
  554. # LETS GET THE POSSIBLE SOURCES
  555. my @sources_options = $Payment->get_sources(\%$locale);
  556. # WE MUST PREPARE THE ENTITY INFORMATION
  557. #@array_options = $Payment->get_vc_info();# IS THIS WORKING?
  558. # LETS BUILD THE CURRENCIES INFORMATION
  559. # FIRST, WE NEED TO KNOW THE DEFAULT CURRENCY
  560. my $default_currency = $Payment->get_default_currency();
  561. # LETS BUILD THE COLUMN HEADERS WE ALWAYS NEED
  562. # THE OTHER HEADERS WILL BE BUILT IF THE RIGHT CONDITIONS ARE MET.
  563. # -----------------------------------------------
  564. # SOME USERS WONT USE MULTIPLE CURRENCIES, AND WONT LIKE THE FACT CURRENCY BEING
  565. # ON THE SCREEN ALL THE TIME, SO IF THEY ARE USING THE DEFAULT CURRENCY WE WONT PRINT IT
  566. my $currency_text = $request->{curr} eq $default_currency ? '' : '('.$request->{curr}.')';
  567. my $default_currency_text = $currency_text ? '('.$default_currency.')' : '';
  568. my @column_headers = ({text => $locale->text('Invoice')},
  569. {text => $locale->text('Date')},
  570. {text => $locale->text('Total').$default_currency_text},
  571. {text => $locale->text('Paid').$default_currency_text},
  572. {text => $locale->text('Discount').$default_currency_text},
  573. {text => $locale->text('Apply Disc')},
  574. {text => $locale->text('Amount Due').$default_currency_text},
  575. {text => $locale->text('To pay').$default_currency_text}
  576. );
  577. # WE NEED TO KNOW IF WE ARE USING A CURRENCY THAT NEEDS AN EXCHANGERATE
  578. if ($default_currency ne $request->{curr} ) {
  579. # FIRST WE PUSH THE OTHER COLUMN HEADERS WE NEED
  580. push @column_headers, {text => $locale->text('Exchange Rate')},
  581. {text => $locale->text('Amount Due').$currency_text},
  582. {text => $locale->text('To pay').$currency_text};
  583. # WE SET THEM IN THE RIGHT ORDER FOR THE TABLE INSIDE THE UI
  584. @column_headers[6,7,8] = @column_headers[7,8,6];
  585. # DOES THE CURRENCY IN USE HAS AN EXCHANGE RATE?, IF SO
  586. # WE MUST SET THE VALUE, OTHERWISE THE UI WILL HANDLE IT
  587. $exchangerate = $request->{exrate} ?
  588. $request->{exrate} :
  589. $Payment->get_exchange_rate($request->{curr},
  590. $request->{datepaid} ? $request->{datepaid} : $Payment->{current_date});
  591. if ($exchangerate) {
  592. @currency_options = {
  593. name => 'exrate',
  594. value => "$exchangerate", #THERE IS A STRANGE BEHAVIOUR WITH THIS,
  595. text => "$exchangerate" #IF I DONT USE THE DOUBLE QUOTES, IT WILL PRINT THE ADDRESS
  596. #THERE MUST BE A REASON FOR THIS, I MUST RETURN TO IT LATER
  597. };
  598. } else {
  599. @currency_options = {
  600. name => 'exrate'};
  601. }
  602. } else {
  603. # WE MUST SET EXCHANGERATE TO 1 FOR THE MATHS SINCE WE
  604. # ARE USING THE DEFAULT CURRENCY
  605. $exchangerate = 1;
  606. @currency_options = {
  607. name => 'exrate',
  608. value => 1,
  609. text => 1
  610. };
  611. }
  612. # FINALLY WE ADD TO THE COLUMN HEADERS A LAST FIELD TO PRINT THE CLOSE INVOICE CHECKBOX TRICK :)
  613. push @column_headers, {text => 'X'};
  614. # WE NEED TO QUERY THE DATABASE TO CHECK FOR OPEN INVOICES
  615. # WE WONT DO ANYTHING IF WE DONT FIND ANY INVOICES, THE USER CAN STILL POST A PREPAYMENT
  616. my @invoice_data;
  617. my @topay_state; # WE WILL USE THIS TO HELP UI TO DETERMINE WHAT IS VISIBLE
  618. @array_options = $Payment->get_open_invoices();
  619. my $unhandled_overpayment;
  620. for my $ref (0 .. $#array_options) {
  621. if ( !$request->{"checkbox_$array_options[$ref]->{invoice_id}"}) {
  622. # SHOULD I APPLY DISCCOUNTS?
  623. $request->{"optional_discount_$array_options[$ref]->{invoice_id}"} = $request->{first_load}? "on": $request->{"optional_discount_$array_options[$ref]->{invoice_id}"};
  624. # LETS SET THE EXCHANGERATE VALUES
  625. my $due_fx; my $topay_fx_value;
  626. if ("$exchangerate") {
  627. $topay_fx_value = $due_fx = $request->round_amount("$array_options[$ref]->{due}"/"$exchangerate");
  628. if ($request->{"optional_discount_$array_options[$ref]->{invoice_id}"}) {
  629. $topay_fx_value = $due_fx = $request->round_amount($due_fx - "$array_options[$ref]->{discount}"/"$exchangerate");
  630. }
  631. } else {
  632. $topay_fx_value = $due_fx = "N/A";
  633. }
  634. # We need to check for unhandled overpayment, see the post function for details
  635. # First we will see if the discount should apply?
  636. my $temporary_discount = 0;
  637. if (($request->{"optional_discount_$array_options[$ref]->{invoice_id}"})&&($due_fx <= $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} + $request->round_amount($array_options[$ref]->{discount}/"$exchangerate"))) {
  638. $temporary_discount = $request->round_amount("$array_options[$ref]->{discount}"/"$exchangerate");
  639. }
  640. # We need to compute the unhandled_overpayment, notice that all the values inside the if already have
  641. # the exchangerate applied
  642. if ( $due_fx < $request->{"topay_fx_$array_options[$ref]->{invoice_id}"}) {
  643. # We need to store all the overpayments so we can use it on the screen
  644. $unhandled_overpayment = $request->round_amount($unhandled_overpayment + $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} - $due_fx );
  645. $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} = "$due_fx";
  646. }
  647. push @invoice_data, { invoice => { number => $array_options[$ref]->{invnumber},
  648. id => $array_options[$ref]->{invoice_id},
  649. href => 'ar.pl?id='."$array_options[$ref]->{invoice_id}"
  650. },
  651. invoice_date => "$array_options[$ref]->{invoice_date}",
  652. amount => "$array_options[$ref]->{amount}",
  653. due => $request->{"optional_discount_$array_options[$ref]->{invoice_id}"}? "$array_options[$ref]->{due}" - "$array_options[$ref]->{discount}": "$array_options[$ref]->{due}",
  654. paid => "$array_options[$ref]->{amount}" - "$array_options[$ref]->{due}",
  655. discount => $request->{"optional_discount_$array_options[$ref]->{invoice_id}"} ? "$array_options[$ref]->{discount}" : 0 ,
  656. optional_discount => $request->{"optional_discount_$array_options[$ref]->{invoice_id}"},
  657. exchange_rate => "$exchangerate",
  658. due_fx => "$due_fx", # This was set at the begining of the for statement
  659. topay => "$array_options[$ref]->{due}" - "$array_options[$ref]->{discount}",
  660. source_text => $request->{"source_text_$array_options[$ref]->{invoice_id}"},
  661. optional => $request->{"optional_pay_$array_options[$ref]->{invoice_id}"},
  662. selected_account => $request->{"account_$array_options[$ref]->{invoice_id}"},
  663. selected_source => $request->{"source_$array_options[$ref]->{invoice_id}"},
  664. topay_fx => { name => "topay_fx_$array_options[$ref]->{invoice_id}",
  665. value => $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} ?
  666. $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} eq 'N/A' ?
  667. "$topay_fx_value" :
  668. $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} :
  669. "$topay_fx_value"
  670. # Ugly hack, but works ;) ...
  671. }#END HASH
  672. };# END PUSH
  673. push @topay_state, {
  674. id => "topaystate_$array_options[$ref]->{invoice_id}",
  675. value => $request->{"topaystate_$array_options[$ref]->{invoice_id}"}
  676. }; #END PUSH
  677. }
  678. else {
  679. push @selected_checkboxes, {name => "checkbox_$array_options[$ref]->{invoice_id}",
  680. value => "checked"} ;
  681. } #END IF
  682. }# END FOR
  683. # And finally, we are going to store the information for the overpayment / prepayment / advanced payment
  684. # and all the stuff, this is only needed for the update function.
  685. my @overpayment;
  686. my @overpayment_account;
  687. # Got to build the account selection box first.
  688. my @overpayment_account = $Payment->list_overpayment_accounting();
  689. # Now we build the structure for the UI
  690. for (my $i=1 ; $i <= $request->{overpayment_qty}; $i++) {
  691. if (!$request->{"overpayment_checkbox_$i"}) {
  692. if ( $request->{"overpayment_topay_$i"} ) {
  693. # Now we split the account selected options
  694. my ($id, $accno, $description) = split(/--/, $request->{"overpayment_account_$i"});
  695. my ($cashid, $cashaccno, $cashdescription ) = split(/--/, $request->{"overpayment_cash_account_$i"});
  696. push @overpayment, {amount => $request->{"overpayment_topay_$i"},
  697. source1 => $request->{"overpayment_source1_$i"},
  698. source2 => $request->{"overpayment_source2_$i"},
  699. memo => $request->{"overpayment_memo_$i"},
  700. account => { id => $id,
  701. accno => $accno,
  702. description => $description
  703. },
  704. cashaccount => { id => $cashid,
  705. accno => $cashaccno,
  706. description => $cashdescription
  707. }
  708. };
  709. } else {
  710. $i = $request->{overpayment_qty} + 1;
  711. }
  712. }
  713. }
  714. # We need to set the availible media and format from printing
  715. my @media_options;
  716. push @media_options, {value => 1, text => "Screen"};
  717. if ($#{LedgerSMB::Sysconfig::printer}) {
  718. for (keys %{LedgerSMB::Sysconfig::printer}) {
  719. push @media_options, {value => 1, text => $_};
  720. }
  721. }
  722. #$request->error("@media_options");
  723. my @format_options;
  724. push @format_options, {value => 1, text => "HTML"};
  725. if (${LedgerSMB::Sysconfig::latex}) {
  726. push @format_options, {value => 2, text => "PDF" }, {value => 3, text => "POSTSCRIPT" };
  727. }
  728. # LETS BUILD THE SELECTION FOR THE UI
  729. # Notice that the first data inside this selection is the firs_load, this
  730. # will help payment2.html to know wether it is beeing called for the first time
  731. my $select = {
  732. first_load => $request->{first_load},
  733. stylesheet => $request->{_user}->{stylesheet},
  734. header => { text => $request->{type} eq 'receipt' ? $locale->text('Receipt') : $locale->text('Payment') },
  735. type => { name => 'type',
  736. value => $request->{type} },
  737. login => { name => 'login',
  738. value => $request->{_user}->{login} },
  739. accountclass => {
  740. name => 'account_class',
  741. value => $Payment->{account_class}
  742. },
  743. project => @project ? @project : '' , # WE NEED TO VERIFY THAT THE ARRAY EXISTS, IF IT DOESNT,
  744. department => @department ? @department : '', # WE WILL PASS A NULL STRING, THIS FIXES THE ISSUES
  745. # I WAS HAVING WITH THE NULL ARRAYS, STILL UGLY :P
  746. account => \@account_options,
  747. selected_account => $request->{account},
  748. datepaid => {
  749. name => 'datepaid',
  750. value => $request->{datepaid} ? $request->{datepaid} : $Payment->{current_date}
  751. },
  752. source => \@sources_options,
  753. selected_source => $request->{source},
  754. source_value => $request->{source_value},
  755. defaultcurrency => {
  756. text => $default_currency
  757. },
  758. curr => { name => 'curr',
  759. value => $request->{curr},
  760. },
  761. column_headers => \@column_headers,
  762. rows => \@invoice_data,
  763. topay_state => \@topay_state,
  764. vendorcustomer => { name => 'vendor-customer',
  765. value => $request->{'vendor-customer'}
  766. },
  767. unhandled_overpayment => { name => 'unhandledoverpayment', value => "$unhandled_overpayment" } ,
  768. vc => { name => $Payment->{company_name}, # We will assume that the first Billing Information as default
  769. address => [ {text => $vc_options[0]->{'line_one'}},
  770. {text => $vc_options[0]->{'line_two'}},
  771. {text => $vc_options[0]->{'line_three'}},
  772. {text => $vc_options[0]->{city}},
  773. {text => $vc_options[0]->{state}},
  774. {text => $vc_options[0]->{country}}]
  775. },
  776. format => {
  777. name => 'FORMAT',
  778. options => \@format_options
  779. },
  780. media => {
  781. name => 'MEDIA',
  782. options => \@media_options
  783. },
  784. exrate => @currency_options,
  785. selectedcheckboxes => @selected_checkboxes ? \@selected_checkboxes : '',
  786. notes => $request->{notes},
  787. overpayment => \@overpayment,
  788. overpayment_account => \@overpayment_account
  789. };
  790. my $template = LedgerSMB::Template->new(
  791. user => $request->{_user},
  792. locale => $request->{_locale},
  793. path => 'UI/payments',
  794. template => 'payment2',
  795. format => 'HTML' );
  796. eval {$template->render($select) };
  797. if ($@) { $request->error("$@"); } # PRINT ERRORS ON THE UI
  798. }
  799. =pod
  800. =item post_payment
  801. This method is used for the payment module (not the bulk payment),
  802. and its used for all the mechanics of storing a payment.
  803. =back
  804. =cut
  805. sub post_payment {
  806. my ($request) = @_;
  807. my $locale = $request->{_locale};
  808. my $Payment = LedgerSMB::DBObject::Payment->new({'base' => $request});
  809. # LETS GET THE CUSTOMER/VENDOR INFORMATION
  810. ($Payment->{entity_credit_id}, $Payment->{company_name}) = split /--/ , $request->{'vendor-customer'};
  811. # LETS GET THE DEPARTMENT INFO
  812. # WE HAVE TO SET $dbPayment->{department_id} in order to process
  813. if ($request->{department}) {
  814. $request->{department} =~ /^(\d+)--*/;
  815. $Payment->{department_id} = $1;
  816. }
  817. #
  818. # We want to set a gl_description,
  819. # since we are using two tables there is no need to use doubled information,
  820. # we could specify this gl is the result of a payment movement...
  821. #
  822. $Payment->{gl_description} = $locale->text('This gl movement, is the result of a payment transaction');
  823. #
  824. # Im not sure what this is for... gotta comment this later
  825. $Payment->{approved} = 'true';
  826. #
  827. # We have to setup a lot of things before we can process the payment
  828. # they are related to payment_post sql function, so if you have any doubts
  829. # look there.
  830. #-------------------------------------------------------------------------
  831. #
  832. # Variable definition
  833. #
  834. # We use the prefix op to refer to the overpayment variables.
  835. my $unhandled_overpayment = 0; # This variable might be fuzzy, we are using it to handle invalid data
  836. # i.e. a user set an overpayment qty inside an invoice.
  837. my @array_options;
  838. my @amount;
  839. my @discount;
  840. my @cash_account_id;
  841. my @source;
  842. my @transaction_id;
  843. my @op_amount;
  844. my @op_cash_account_id;
  845. my @op_source;
  846. my @op_memo;
  847. my @op_account_id;
  848. #
  849. # We need the invoices in order to process the income data, this is done this way
  850. # since the data we have isn't indexed in any way.
  851. #
  852. # Ok, we want to use the disccount information in order to do some accounting movements,
  853. # we will process it with the same logic for a regular payment, and see where does this leave us.
  854. @array_options = $Payment->get_entity_credit_account();# We need to know the disccount account
  855. my $discount_account_id = $array_options[0]->{discount};
  856. @array_options = $Payment->get_open_invoices();
  857. for my $ref (0 .. $#array_options) {
  858. if ( !$request->{"checkbox_$array_options[$ref]->{invoice_id}"}) {
  859. # First i have to determine if discounts will apply
  860. # we will assume that a discount should apply only
  861. # if this is the last payment of an invoice
  862. my $temporary_discount = 0;
  863. if (($request->{"optional_discount_$array_options[$ref]->{invoice_id}"})&&("$array_options[$ref]->{due}"/"$request->{exrate}" <= $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} + $array_options[$ref]->{discount})) {
  864. $temporary_discount = $array_options[$ref]->{discount};
  865. }
  866. #
  867. # The prefix cash is to set the movements of the cash accounts,
  868. # same names are used for ap/ar accounts w/o the cash prefix.
  869. #
  870. if ( "$array_options[$ref]->{due}"/"$request->{exrate}" < $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} + $temporary_discount ) {
  871. # We need to store all the overpayments so we can use it on a new payment2 screen
  872. $unhandled_overpayment = $request->round_amount($unhandled_overpayment + $request->{"topay_fx_$array_options[$ref]->{invoice_id}"} + $temporary_discount - $array_options[$ref]->{amount}) ;
  873. }
  874. if ($request->{"optional_discount_$array_options[$ref]->{invoice_id}"}) {
  875. push @amount, $array_options[$ref]->{discount};
  876. push @cash_account_id, $discount_account_id;
  877. push @source, $locale->text('Applied discount');
  878. push @transaction_id, $array_options[$ref]->{invoice_id};
  879. }
  880. push @amount, $request->{"topay_fx_$array_options[$ref]->{invoice_id}"}; # We'll use this for both cash and ap/ar accounts
  881. push @cash_account_id, $request->{"optional_pay_$array_options[$ref]->{invoice_id}"} ? $request->{"account_$array_options[$ref]->{invoice_id}"} : $request->{account};
  882. push @source, $request->{"source1_$array_options[$ref]->{invoice_id}"}.' '.$request->{"source2_$array_options[$ref]->{invoice_id}"}; # We'll use this for both source and ap/ar accounts
  883. push @transaction_id, $array_options[$ref]->{invoice_id};
  884. }
  885. }
  886. # Check if there is an unhandled overpayment and run payment2 as needed
  887. if ($unhandled_overpayment) {
  888. &payment2($request);
  889. return 0;
  890. }
  891. #
  892. # Now we need the overpayment information.
  893. #
  894. # We will use the prefix op to indicate it is an overpayment information.
  895. #
  896. # note: I love the for's C-like syntax.
  897. for (my $i=1 ; $i <= $request->{overpayment_qty}; $i++) {
  898. if (!$request->{"overpayment_checkbox_$i"}) { # Is overpayment marked as deleted ?
  899. if ( $request->{"overpayment_topay_$i"} ) { # Is this overpayment an used field?
  900. # Now we split the account selected options, using the namespace the if statement
  901. # provides for us.
  902. $request->{"overpayment_account_$i"} =~ /^(\d+)--*/;
  903. my $id = $1;
  904. $request->{"overpayment_cash_account_$i"} =~ /^(\d+)--*/;
  905. my $cashid = $1;
  906. push @op_amount, $request->{"overpayment_topay_$i"};
  907. push @op_cash_account_id, $cashid;
  908. push @op_source, $request->{"overpayment_source1_$i"}.' '.$request->{"overpayment_source2_$i"};
  909. push @op_memo, $request->{"overpayment_memo_$i"};
  910. push @op_account_id, $id;
  911. }
  912. }
  913. }
  914. # Finally we store all the data inside the LedgerSMB::DBObject::Payment object.
  915. $Payment->{cash_account_id} = $Payment->_db_array_scalars(@cash_account_id);
  916. $Payment->{amount} = $Payment->_db_array_scalars(@amount);
  917. $Payment->{source} = $Payment->_db_array_scalars(@source);
  918. $Payment->{transaction_id} = $Payment->_db_array_scalars(@transaction_id);
  919. $Payment->{op_amount} = $Payment->_db_array_scalars(@op_amount);
  920. $Payment->{op_cash_account_id} = $Payment->_db_array_scalars(@op_cash_account_id);
  921. $Payment->{op_source} = $Payment->_db_array_scalars(@op_source);
  922. $Payment->{op_memo} = $Payment->_db_array_scalars(@op_memo);
  923. $Payment->{op_account_id} = $Payment->_db_array_scalars(@op_account_id);
  924. # Ok, hoping for the best...
  925. $Payment->post_payment();
  926. # We've gotta print anything, in the near future this will redirect to a new payment.
  927. my $select = {};
  928. my $template = LedgerSMB::Template->new(
  929. user => $request->{_user},
  930. locale => $request->{_locale},
  931. path => 'UI/payments',
  932. template => 'payment2',
  933. format => 'HTML' );
  934. eval {$template->render($select) };
  935. if ($@) { $request->error("$@"); } # PRINT ERRORS ON THE UI
  936. }
  937. eval { do "scripts/custom/payment.pl"};
  938. 1;