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