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