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