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