1<?php
2/* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2003      Jean-Louis Bergamo   <jlb@j1b.org>
4 * Copyright (C) 2004-2018 Laurent Destailleur  <eldy@users.sourceforge.net>
5 * Copyright (C) 2005-2009 Regis Houssin        <regis.houssin@inodbox.com>
6 * Copyright (C) 2013      Peter Fontaine       <contact@peterfontaine.fr>
7 * Copyright (C) 2015-2016 Marcos García        <marcosgdf@gmail.com>
8 * Copyright (C) 2017      Ferran Marcet        <fmarcet@2byte.es>
9 * Copyright (C) 2018 -2021Thibault FOUCART     <support@ptibogxiv.net>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
25/**
26 *	    \file       htdocs/societe/paymentmodes.php
27 *      \ingroup    societe
28 *		\brief      Tab of payment modes for the customer
29 */
30
31require '../main.inc.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
36require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
37require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
38require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
39require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
40require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
41
42$langs->loadLangs(array("companies", "commercial", "banks", "bills", 'paypal', 'stripe', 'withdrawals'));
43
44
45// Security check
46$socid = GETPOST("socid", "int");
47if ($user->socid) {
48	$socid = $user->socid;
49}
50$result = restrictedArea($user, 'societe', '', '');
51
52$id = GETPOST("id", "int");
53$source = GETPOST("source", "alpha"); // source can be a source or a paymentmode
54$ribid = GETPOST("ribid", "int");
55$action = GETPOST("action", 'alpha', 3);
56$cancel = GETPOST('cancel', 'alpha');
57
58$object = new Societe($db);
59$object->fetch($socid);
60
61$companybankaccount = new CompanyBankAccount($db);
62$companypaymentmode = new CompanyPaymentMode($db);
63$prelevement = new BonPrelevement($db);
64
65$extrafields = new ExtraFields($db);
66
67// fetch optionals attributes and labels
68$extrafields->fetch_name_optionals_label($object->table_element);
69
70// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
71$hookmanager->initHooks(array('thirdpartybancard', 'globalcard'));
72
73
74if (!empty($conf->stripe->enabled)) {
75	$service = 'StripeTest';
76	$servicestatus = 0;
77	if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
78		$service = 'StripeLive';
79		$servicestatus = 1;
80	}
81
82	// Force to use the correct API key
83	global $stripearrayofkeysbyenv;
84	$site_account = $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];
85
86	$stripe = new Stripe($db);
87	$stripeacc = $stripe->getStripeAccount($service); // Get Stripe OAuth connect account (no remote access to Stripe here)
88	$stripecu = $stripe->getStripeCustomerAccount($object->id, $servicestatus, $site_account); // Get remote Stripe customer 'cus_...' (no remote access to Stripe here)
89}
90
91
92
93/*
94 *	Actions
95 */
96
97if ($cancel) {
98	$action = '';
99}
100
101$parameters = array('id'=>$socid);
102$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
103if ($reshook < 0) {
104	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
105}
106
107if (empty($reshook)) {
108	if ($cancel) {
109		$action = '';
110		if (!empty($backtopage)) {
111			header("Location: ".$backtopage);
112			exit;
113		}
114	}
115
116	if ($action == 'update') {
117		// Modification
118		if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) {
119			if (!GETPOST('label', 'alpha')) {
120				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
121			}
122			if (!GETPOST('bank', 'alpha')) {
123				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors');
124			}
125			$action = 'edit';
126			$error++;
127		}
128		if ($companybankaccount->needIBAN() == 1) {
129			if (!GETPOST('iban')) {
130				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors');
131				$action = 'edit';
132				$error++;
133			}
134			if (!GETPOST('bic')) {
135				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors');
136				$action = 'edit';
137				$error++;
138			}
139		}
140
141		$companybankaccount->fetch($id);
142		if (!$error) {
143			$companybankaccount->socid           = $object->id;
144
145			$companybankaccount->bank            = GETPOST('bank', 'alpha');
146			$companybankaccount->label           = GETPOST('label', 'alpha');
147			$companybankaccount->courant         = GETPOST('courant', 'alpha');
148			$companybankaccount->clos            = GETPOST('clos', 'alpha');
149			$companybankaccount->code_banque     = GETPOST('code_banque', 'alpha');
150			$companybankaccount->code_guichet    = GETPOST('code_guichet', 'alpha');
151			$companybankaccount->number          = GETPOST('number', 'alpha');
152			$companybankaccount->cle_rib         = GETPOST('cle_rib', 'alpha');
153			$companybankaccount->bic             = GETPOST('bic', 'alpha');
154			$companybankaccount->iban            = GETPOST('iban', 'alpha');
155			$companybankaccount->domiciliation   = GETPOST('domiciliation', 'alpha');
156			$companybankaccount->proprio         = GETPOST('proprio', 'alpha');
157			$companybankaccount->owner_address   = GETPOST('owner_address', 'alpha');
158			$companybankaccount->frstrecur       = GETPOST('frstrecur', 'alpha');
159			$companybankaccount->rum             = GETPOST('rum', 'alpha');
160			$companybankaccount->date_rum        = dol_mktime(0, 0, 0, GETPOST('date_rummonth'), GETPOST('date_rumday'), GETPOST('date_rumyear'));
161			if (empty($companybankaccount->rum)) {
162				$companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id);
163			}
164
165			$result = $companybankaccount->update($user);
166			if (!$result) {
167				setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors');
168			} else {
169				// If this account is the default bank account, we disable others
170				if ($companybankaccount->default_rib) {
171					$companybankaccount->setAsDefault($id); // This will make sure there is only one default rib
172				}
173
174				$url = $_SERVER["PHP_SELF"].'?socid='.$object->id;
175				header('Location: '.$url);
176				exit;
177			}
178		}
179	}
180
181	if ($action == 'updatecard') {
182		// Modification
183		if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) {
184			if (!GETPOST('label', 'alpha')) {
185				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
186			}
187			if (!GETPOST('proprio', 'alpha')) {
188				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors');
189			}
190			//if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors');
191			if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) {
192				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors');
193			}
194			//if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors');
195			$action = 'createcard';
196			$error++;
197		}
198
199		$companypaymentmode->fetch($id);
200		if (!$error) {
201			$companypaymentmode->fk_soc          = $object->id;
202
203			$companypaymentmode->bank            = GETPOST('bank', 'alpha');
204			$companypaymentmode->label           = GETPOST('label', 'alpha');
205			$companypaymentmode->number          = GETPOST('cardnumber', 'alpha');
206			$companypaymentmode->last_four       = substr(GETPOST('cardnumber', 'alpha'), -4);
207			$companypaymentmode->proprio         = GETPOST('proprio', 'alpha');
208			$companypaymentmode->exp_date_month  = GETPOST('exp_date_month', 'int');
209			$companypaymentmode->exp_date_year   = GETPOST('exp_date_year', 'int');
210			$companypaymentmode->cvn             = GETPOST('cvn', 'alpha');
211			$companypaymentmode->country_code    = $object->country_code;
212
213			if (GETPOST('stripe_card_ref', 'alpha') && GETPOST('stripe_card_ref', 'alpha') != $companypaymentmode->stripe_card_ref) {
214				// If we set a stripe value that is different than previous one, we also set the stripe account
215				$companypaymentmode->stripe_account = $stripecu.'@'.$site_account;
216			}
217			$companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref', 'alpha');
218
219			$result = $companypaymentmode->update($user);
220			if (!$result) {
221				setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors');
222			} else {
223				// If this account is the default bank account, we disable others
224				if ($companypaymentmode->default_rib) {
225					$companypaymentmode->setAsDefault($id); // This will make sure there is only one default rib
226				}
227
228				$url = $_SERVER["PHP_SELF"].'?socid='.$object->id;
229				header('Location: '.$url);
230				exit;
231			}
232		}
233	}
234
235	if ($action == 'add') {
236		$error = 0;
237
238		if (!GETPOST('label', 'alpha') || !GETPOST('bank', 'alpha')) {
239			if (!GETPOST('label', 'alpha')) {
240				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
241			}
242			if (!GETPOST('bank', 'alpha')) {
243				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors');
244			}
245			$action = 'create';
246			$error++;
247		}
248
249		if (!$error) {
250			// Ajout
251			$companybankaccount = new CompanyBankAccount($db);
252
253			$companybankaccount->socid           = $object->id;
254
255			$companybankaccount->bank            = GETPOST('bank', 'alpha');
256			$companybankaccount->label           = GETPOST('label', 'alpha');
257			$companybankaccount->courant         = GETPOST('courant', 'alpha');
258			$companybankaccount->clos            = GETPOST('clos', 'alpha');
259			$companybankaccount->code_banque     = GETPOST('code_banque', 'alpha');
260			$companybankaccount->code_guichet    = GETPOST('code_guichet', 'alpha');
261			$companybankaccount->number          = GETPOST('number', 'alpha');
262			$companybankaccount->cle_rib         = GETPOST('cle_rib', 'alpha');
263			$companybankaccount->bic             = GETPOST('bic', 'alpha');
264			$companybankaccount->iban            = GETPOST('iban', 'alpha');
265			$companybankaccount->domiciliation   = GETPOST('domiciliation', 'alpha');
266			$companybankaccount->proprio         = GETPOST('proprio', 'alpha');
267			$companybankaccount->owner_address   = GETPOST('owner_address', 'alpha');
268			$companybankaccount->frstrecur       = GETPOST('frstrecur', 'alpha');
269			$companybankaccount->rum             = GETPOST('rum', 'alpha');
270			$companybankaccount->date_rum        = dol_mktime(0, 0, 0, GETPOST('date_rummonth', 'int'), GETPOST('date_rumday', 'int'), GETPOST('date_rumyear', 'int'));
271			$companybankaccount->datec = dol_now();
272			$companybankaccount->status          = 1;
273
274			$db->begin();
275
276			// This test can be done only once properties were set
277			if ($companybankaccount->needIBAN() == 1) {
278				if (!GETPOST('iban')) {
279					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors');
280					$action = 'create';
281					$error++;
282				}
283				if (!GETPOST('bic')) {
284					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors');
285					$action = 'create';
286					$error++;
287				}
288			}
289
290			if (!$error) {
291				$result = $companybankaccount->create($user);
292				if ($result < 0) {
293					$error++;
294					setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors');
295					$action = 'create'; // Force chargement page création
296				}
297
298				if (empty($companybankaccount->rum)) {
299					$companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id);
300				}
301			}
302
303			if (!$error) {
304				$result = $companybankaccount->update($user); // This will set the UMR number.
305				if ($result < 0) {
306					$error++;
307					setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors');
308					$action = 'create';
309				}
310			}
311
312			if (!$error) {
313				$db->commit();
314
315				$url = $_SERVER["PHP_SELF"].'?socid='.$object->id;
316				header('Location: '.$url);
317				exit;
318			} else {
319				$db->rollback();
320			}
321		}
322	}
323
324	if ($action == 'addcard') {
325		$error = 0;
326
327		if (!GETPOST('label', 'alpha') || !GETPOST('proprio', 'alpha') || !GETPOST('exp_date_month', 'alpha') || !GETPOST('exp_date_year', 'alpha')) {
328			if (!GETPOST('label', 'alpha')) {
329				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
330			}
331			if (!GETPOST('proprio', 'alpha')) {
332				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NameOnCard")), null, 'errors');
333			}
334			//if (!GETPOST('cardnumber', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CardNumber")), null, 'errors');
335			if (!(GETPOST('exp_date_month', 'alpha') > 0) || !(GETPOST('exp_date_year', 'alpha') > 0)) {
336				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpiryDate")), null, 'errors');
337			}
338			//if (!GETPOST('cvn', 'alpha')) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CVN")), null, 'errors');
339			$action = 'createcard';
340			$error++;
341		}
342
343		if (!$error) {
344			// Ajout
345			$companypaymentmode = new CompanyPaymentMode($db);
346
347			$companypaymentmode->fk_soc          = $object->id;
348			$companypaymentmode->bank            = GETPOST('bank', 'alpha');
349			$companypaymentmode->label           = GETPOST('label', 'alpha');
350			$companypaymentmode->number          = GETPOST('cardnumber', 'alpha');
351			$companypaymentmode->last_four       = substr(GETPOST('cardnumber', 'alpha'), -4);
352			$companypaymentmode->proprio         = GETPOST('proprio', 'alpha');
353			$companypaymentmode->exp_date_month  = GETPOST('exp_date_month', 'int');
354			$companypaymentmode->exp_date_year   = GETPOST('exp_date_year', 'int');
355			$companypaymentmode->cvn             = GETPOST('cvn', 'alpha');
356			$companypaymentmode->datec           = dol_now();
357			$companypaymentmode->default_rib     = 0;
358			$companypaymentmode->type            = 'card';
359			$companypaymentmode->country_code    = $object->country_code;
360			$companypaymentmode->status          = $servicestatus;
361
362			if (GETPOST('stripe_card_ref', 'alpha')) {
363				// If we set a stripe value, we also set the stripe account
364				$companypaymentmode->stripe_account = $stripecu.'@'.$site_account;
365			}
366			$companypaymentmode->stripe_card_ref = GETPOST('stripe_card_ref', 'alpha');
367
368			$db->begin();
369
370			if (!$error) {
371				$result = $companypaymentmode->create($user);
372				if ($result < 0) {
373					$error++;
374					setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors');
375					$action = 'createcard'; // Force chargement page création
376				}
377			}
378
379			if (!$error) {
380				$db->commit();
381
382				$url = $_SERVER["PHP_SELF"].'?socid='.$object->id;
383				header('Location: '.$url);
384				exit;
385			} else {
386				$db->rollback();
387			}
388		}
389	}
390
391	if ($action == 'setasbankdefault' && GETPOST('ribid', 'int') > 0) {
392		$companybankaccount = new CompanyBankAccount($db);
393		$res = $companybankaccount->setAsDefault(GETPOST('ribid', 'int'));
394		if ($res) {
395			$url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
396			header('Location: '.$url);
397			exit;
398		} else {
399			setEventMessages($db->lasterror, null, 'errors');
400		}
401	}
402
403	if ($action == 'confirm_deletecard' && GETPOST('confirm', 'alpha') == 'yes') {
404		$companypaymentmode = new CompanyPaymentMode($db);
405		if ($companypaymentmode->fetch($ribid ? $ribid : $id)) {
406			/*if ($companypaymentmode->stripe_card_ref && preg_match('/pm_/', $companypaymentmode->stripe_card_ref))
407			{
408				$payment_method = \Stripe\PaymentMethod::retrieve($companypaymentmode->stripe_card_ref);
409				if ($payment_method)
410				{
411					$payment_method->detach();
412				}
413			}*/
414
415			$result = $companypaymentmode->delete($user);
416			if ($result > 0) {
417				$url = $_SERVER['PHP_SELF']."?socid=".$object->id;
418				header('Location: '.$url);
419				exit;
420			} else {
421				setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors');
422			}
423		} else {
424			setEventMessages($companypaymentmode->error, $companypaymentmode->errors, 'errors');
425		}
426	}
427	if ($action == 'confirm_delete' && GETPOST('confirm', 'alpha') == 'yes') {
428		$companybankaccount = new CompanyBankAccount($db);
429		if ($companybankaccount->fetch($ribid ? $ribid : $id)) {
430			$result = $companybankaccount->delete($user);
431			if ($result > 0) {
432				$url = $_SERVER['PHP_SELF']."?socid=".$object->id;
433				header('Location: '.$url);
434				exit;
435			} else {
436				setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors');
437			}
438		} else {
439			setEventMessages($companybankaccount->error, $companybankaccount->errors, 'errors');
440		}
441	}
442
443	$savid = $id;
444
445	// Actions to build doc
446	if ($action == 'builddocrib') {
447		$action = 'builddoc';
448		$moreparams = array(
449			'use_companybankid'=>GETPOST('companybankid'),
450			'force_dir_output'=>$conf->societe->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->id)
451		);
452		$_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid', 'int'), 'alpha');
453		$_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid', 'int'), 'alpha');
454	}
455
456	$id = $socid;
457	$upload_dir = $conf->societe->multidir_output[$object->entity];
458	$permissiontoadd = $user->rights->societe->creer;
459	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
460
461	$id = $savid;
462
463	// Action for stripe
464	if (!empty($conf->stripe->enabled) && class_exists('Stripe')) {
465		if ($action == 'synccustomertostripe') {
466			if ($object->client == 0) {
467				$error++;
468				setEventMessages('ThisThirdpartyIsNotACustomer', null, 'errors');
469			} else {
470				// Creation of Stripe customer + update of societe_account
471				$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus, 1);
472				if (!$cu) {
473					$error++;
474					setEventMessages($stripe->error, $stripe->errors, 'errors');
475				} else {
476					$stripecu = $cu->id;
477				}
478			}
479		}
480		if ($action == 'synccardtostripe') {
481			$companypaymentmode = new CompanyPaymentMode($db);
482			$companypaymentmode->fetch($id);
483
484			if ($companypaymentmode->type != 'card') {
485				$error++;
486				setEventMessages('ThisPaymentModeIsNotACard', null, 'errors');
487			} else {
488				// Get the Stripe customer
489				$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus);
490				if (!$cu) {
491					$error++;
492					setEventMessages($stripe->error, $stripe->errors, 'errors');
493				}
494
495				if (!$error) {
496					// Creation of Stripe card + update of societe_account
497					// Note that with the new Stripe API, option to create a card is no more available, instead an error message will be returned to
498					// ask to create the crdit card from Stripe backoffice.
499					$card = $stripe->cardStripe($cu, $companypaymentmode, $stripeacc, $servicestatus, 1);
500					if (!$card) {
501						$error++;
502						setEventMessages($stripe->error, $stripe->errors, 'errors');
503					}
504				}
505			}
506		}
507
508		if ($action == 'setkey_account') {
509			$error = 0;
510
511			$newcu = GETPOST('key_account', 'alpha');
512
513			$db->begin();
514
515			if (empty($newcu)) {
516				$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND status = ".((int) $servicestatus)." AND entity = ".$conf->entity;
517			} else {
518				$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."societe_account";
519				$sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".((int) $object->id)." AND status = ".((int) $servicestatus)." AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
520			}
521
522			$resql = $db->query($sql);
523			$num = $db->num_rows($resql); // Note: $num is always 0 on an update and delete, it is defined for select only.
524			if (!empty($newcu)) {
525				if (empty($num)) {
526					$societeaccount = new SocieteAccount($db);
527					$societeaccount->fk_soc = $object->id;
528					$societeaccount->login = '';
529					$societeaccount->pass_encoding = '';
530					$societeaccount->site = 'stripe';
531					$societeaccount->status = $servicestatus;
532					$societeaccount->key_account = $newcu;
533					$societeaccount->site_account = $site_account;
534					$result = $societeaccount->create($user);
535					if ($result < 0) {
536						$error++;
537					}
538				} else {
539					$sql = 'UPDATE '.MAIN_DB_PREFIX."societe_account";
540					$sql .= " SET key_account = '".$db->escape(GETPOST('key_account', 'alpha'))."', site_account = '".$db->escape($site_account)."'";
541					$sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".((int) $object->id)." AND status = ".((int) $servicestatus)." AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
542					$resql = $db->query($sql);
543				}
544			}
545			//var_dump($sql);	var_dump($newcu);		var_dump($num); exit;
546
547			if (!$error) {
548				$stripecu = $newcu;
549				$db->commit();
550			} else {
551				$db->rollback();
552			}
553		}
554
555		if ($action == 'setkey_account_supplier') {
556			$error = 0;
557
558			$newsup = GETPOST('key_account_supplier', 'alpha');
559
560			$db->begin();
561
562			if (empty($newsup)) {
563				$sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
564				// TODO Add site and site_account on oauth_token table
565				//$sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".((int) $object->id)." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
566			} else {
567				try {
568					$stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
569					$tokenstring['stripe_user_id'] = $stripesup->id;
570					$tokenstring['type'] = $stripesup->type;
571					$sql = "UPDATE ".MAIN_DB_PREFIX."oauth_token";
572					$sql .= " SET tokenstring = '".$db->escape(json_encode($tokenstring))."'";
573					$sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".((int) $object->id)." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
574					// TODO Add site and site_account on oauth_token table
575					$sql .= " WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
576				} catch (Exception $e) {
577					$error++;
578					setEventMessages($e->getMessage(), null, 'errors');
579				}
580			}
581
582			$resql = $db->query($sql);
583			$num = $db->num_rows($resql);
584			if (empty($num) && !empty($newsup)) {
585				try {
586					$stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
587					$tokenstring['stripe_user_id'] = $stripesup->id;
588					$tokenstring['type'] = $stripesup->type;
589					$sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token (service, fk_soc, entity, tokenstring)";
590					$sql .= " VALUES ('".$db->escape($service)."', ".$object->id.", ".$conf->entity.", '".$db->escape(json_encode($tokenstring))."')";
591					// TODO Add site and site_account on oauth_token table
592				} catch (Exception $e) {
593					$error++;
594					setEventMessages($e->getMessage(), null, 'errors');
595				}
596				$resql = $db->query($sql);
597			}
598
599			if (!$error) {
600				$stripesupplieracc = $newsup;
601				$db->commit();
602			} else {
603				$db->rollback();
604			}
605		}
606
607		if ($action == 'setlocalassourcedefault') {	// Set as default when payment mode defined locally (and may be also remotely)
608			try {
609				$companypaymentmode->setAsDefault($id);
610
611				$url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
612				header('Location: '.$url);
613				exit;
614			} catch (Exception $e) {
615				$error++;
616				setEventMessages($e->getMessage(), null, 'errors');
617			}
618		} elseif ($action == 'setassourcedefault') {	// Set as default when payment mode defined remotely only
619			try {
620				$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus);
621				if (preg_match('/pm_/', $source)) {
622					$cu->invoice_settings->default_payment_method = (string) $source; // New
623				} else {
624					$cu->default_source = (string) $source; // Old
625				}
626				$result = $cu->save();
627
628				$url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
629				header('Location: '.$url);
630				exit;
631			} catch (Exception $e) {
632				$error++;
633				setEventMessages($e->getMessage(), null, 'errors');
634			}
635		} elseif ($action == 'deletecard' && $source) {
636			try {
637				if (preg_match('/pm_/', $source)) {
638					$payment_method = \Stripe\PaymentMethod::retrieve($source, array("stripe_account" => $stripeacc));
639					if ($payment_method) {
640						$payment_method->detach();
641					}
642				} else {
643					$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus);
644					$card = $cu->sources->retrieve("$source");
645					if ($card) {
646						// $card->detach();  Does not work with card_, only with src_
647						if (method_exists($card, 'detach')) {
648							$card->detach();
649						} else {
650							$card->delete();
651						}
652					}
653				}
654
655				$url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
656				header('Location: '.$url);
657				exit;
658			} catch (Exception $e) {
659				$error++;
660				setEventMessages($e->getMessage(), null, 'errors');
661			}
662		}
663	}
664}
665
666
667
668/*
669 *	View
670 */
671
672$form = new Form($db);
673$formother = new FormOther($db);
674$formfile = new FormFile($db);
675
676$title = $langs->trans("ThirdParty");
677if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
678	$title = $object->name." - ".$langs->trans('PaymentInformation');
679}
680
681llxHeader();
682
683$head = societe_prepare_head($object);
684
685// Show sandbox warning
686/*if (! empty($conf->paypal->enabled) && (! empty($conf->global->PAYPAL_API_SANDBOX) || GETPOST('forcesandbox','alpha')))		// We can force sand box with param 'forcesandbox'
687{
688	dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Paypal'),'','warning');
689}*/
690if (!empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || GETPOST('forcesandbox', 'alpha'))) {
691	dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning');
692}
693
694// Load Bank account
695if (!$id) {
696	$companybankaccount->fetch(0, $object->id);
697	$companypaymentmode->fetch(0, null, $object->id, 'card');
698} else {
699	$companybankaccount->fetch($id);
700	$companypaymentmode->fetch($id);
701}
702if (empty($companybankaccount->socid)) {
703	$companybankaccount->socid = $object->id;
704}
705
706if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) {
707	print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="post">';
708	print '<input type="hidden" name="token" value="'.newToken().'">';
709	$actionforadd = 'update';
710	if ($action == 'editcard') {
711		$actionforadd = 'updatecard';
712	}
713	print '<input type="hidden" name="action" value="'.$actionforadd.'">';
714	print '<input type="hidden" name="id" value="'.GETPOST("id", "int").'">';
715}
716if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) {
717	print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'" method="post">';
718	print '<input type="hidden" name="token" value="'.newToken().'">';
719	$actionforadd = 'add';
720	if ($action == 'createcard') {
721		$actionforadd = 'addcard';
722	}
723	print '<input type="hidden" name="action" value="'.$actionforadd.'">';
724}
725
726
727// View
728if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard' && $action != 'createcard') {
729	print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), -1, 'company');
730
731	// Confirm delete ban
732	if ($action == 'delete') {
733		print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid ? $ribid : $id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $companybankaccount->getRibLabel()), "confirm_delete", '', 0, 1);
734	}
735	// Confirm delete card
736	if ($action == 'deletecard') {
737		print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid ? $ribid : $id), $langs->trans("DeleteACard"), $langs->trans("ConfirmDeleteCard", $companybankaccount->getRibLabel()), "confirm_deletecard", '', 0, 1);
738	}
739
740	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
741
742	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
743
744	print '<div class="fichecenter">';
745
746	print '<div class="underbanner clearboth"></div>';
747	print '<table class="border tableforfield centpercent">';
748
749	// Type Prospect/Customer/Supplier
750	print '<tr><td class="titlefield">'.$langs->trans('NatureOfThirdParty').'</td><td>';
751	print $object->getTypeUrl(1);
752	print '</td></tr>';
753
754	if (!empty($conf->global->SOCIETE_USEPREFIX)) {  // Old not used prefix field
755		print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>';
756	}
757
758	if ($object->client) {
759		print '<tr><td class="titlefield">';
760		print $langs->trans('CustomerCode').'</td><td colspan="2">';
761		print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client));
762		$tmpcheck = $object->check_codeclient();
763		if ($tmpcheck != 0 && $tmpcheck != -5) {
764			print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
765		}
766		print '</td></tr>';
767		$sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."facture where fk_soc = ".((int) $socid);
768		$resql = $db->query($sql);
769		if (!$resql) {
770			dol_print_error($db);
771		}
772
773		$obj = $db->fetch_object($resql);
774		$nbFactsClient = $obj->nb;
775		$thirdTypeArray['customer'] = $langs->trans("customer");
776		if ($conf->propal->enabled && $user->rights->propal->lire) {
777			$elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals');
778		}
779		if ($conf->commande->enabled && $user->rights->commande->lire) {
780			$elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders');
781		}
782		if ($conf->facture->enabled && $user->rights->facture->lire) {
783			$elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices');
784		}
785		if ($conf->contrat->enabled && $user->rights->contrat->lire) {
786			$elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts');
787		}
788
789		if (!empty($conf->stripe->enabled)) {
790			$permissiontowrite = $user->rights->societe->creer;
791			// Stripe customer key 'cu_....' stored into llx_societe_account
792			print '<tr><td class="titlefield">';
793			print $form->editfieldkey("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', 0, 2, 'socid');
794			print '</td><td>';
795			print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid');
796			if (!empty($conf->stripe->enabled) && $stripecu && $action != 'editkey_account') {
797				$connect = '';
798				if (!empty($stripeacc)) {
799					$connect = $stripeacc.'/';
800				}
801				$url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$stripecu;
802				if ($servicestatus) {
803					$url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$stripecu;
804				}
805				print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Publishable key = '.$site_account, 'globe').'</a>';
806			}
807			print '</td><td class="right">';
808			if (empty($stripecu)) {
809				print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
810				print '<input type="hidden" name="action" value="synccustomertostripe">';
811				print '<input type="hidden" name="token" value="'.newToken().'">';
812				print '<input type="hidden" name="socid" value="'.$object->id.'">';
813				print '<input type="submit" class="button buttongen" name="syncstripecustomer" value="'.$langs->trans("CreateCustomerOnStripe").'">';
814				print '</form>';
815			}
816			print '</td></tr>';
817		}
818	}
819
820	if ($object->fournisseur) {
821		print '<tr><td class="titlefield">';
822		print $langs->trans('SupplierCode').'</td><td colspan="2">';
823		print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur));
824		$tmpcheck = $object->check_codefournisseur();
825		if ($tmpcheck != 0 && $tmpcheck != -5) {
826			print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
827		}
828		print '</td></tr>';
829		$sql = "SELECT count(*) as nb from ".MAIN_DB_PREFIX."facture where fk_soc = ".((int) $socid);
830		$resql = $db->query($sql);
831		if (!$resql) {
832			dol_print_error($db);
833		}
834		$obj = $db->fetch_object($resql);
835		$nbFactsClient = $obj->nb;
836		$thirdTypeArray['customer'] = $langs->trans("customer");
837		if ($conf->propal->enabled && $user->rights->propal->lire) {
838			$elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals');
839		}
840		if ($conf->commande->enabled && $user->rights->commande->lire) {
841			$elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders');
842		}
843		if ($conf->facture->enabled && $user->rights->facture->lire) {
844			$elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices');
845		}
846		if ($conf->contrat->enabled && $user->rights->contrat->lire) {
847			$elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts');
848		}
849	}
850
851	if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && $conf->global->MAIN_FEATURES_LEVEL >= 2) {
852		$permissiontowrite = $user->rights->societe->creer;
853		$stripesupplieracc = $stripe->getStripeAccount($service, $object->id); // Get Stripe OAuth connect account (no network access here)
854
855		// Stripe customer key 'cu_....' stored into llx_societe_account
856		print '<tr><td class="titlefield">';
857		print $form->editfieldkey("StripeConnectAccount", 'key_account_supplier', $stripesupplieracc, $object, $permissiontowrite, 'string', '', 0, 2, 'socid');
858		print '</td><td>';
859		print $form->editfieldval("StripeConnectAccount", 'key_account_supplier', $stripesupplieracc, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid');
860		if (!empty($conf->stripe->enabled) && $stripesupplieracc && $action != 'editkey_account_supplier') {
861			$connect = '';
862
863			$url = 'https://dashboard.stripe.com/test/connect/accounts/'.$stripesupplieracc;
864			if ($servicestatus) {
865				$url = 'https://dashboard.stripe.com/connect/accounts/'.$stripesupplieracc;
866			}
867			print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Publishable key '.$site_account, 'globe').'</a>';
868		}
869		print '</td><td class="right">';
870		if (empty($stripesupplieracc)) {
871			print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
872			print '<input type="hidden" name="action" value="syncsuppliertostripe">';
873			print '<input type="hidden" name="token" value="'.newToken().'">';
874			print '<input type="hidden" name="socid" value="'.$object->id.'">';
875			print '<input type="hidden" name="companybankid" value="'.$rib->id.'">';
876			//print '<input type="submit" class="button buttongen" name="syncstripecustomer" value="'.$langs->trans("CreateSupplierOnStripe").'">';
877			print '</form>';
878		}
879		print '</td></tr>';
880	}
881
882	print '</table>';
883	print '</div>';
884
885	print dol_get_fiche_end();
886
887	print '<br>';
888
889	// List of Stripe payment modes
890	if (!(empty($conf->stripe->enabled)) && $object->client) {
891		$morehtmlright = '';
892		if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) {
893			$morehtmlright .= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=createcard');
894		}
895		print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc ? ' (Stripe connection with StripeConnect account '.$stripeacc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s');
896
897		$listofsources = array();
898		if (is_object($stripe)) {
899			try {
900				$customerstripe = $stripe->customerStripe($object, $stripeacc, $servicestatus);
901				if (!empty($customerstripe->id)) {
902					// When using the Charge API architecture
903					if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) {
904						$listofsources = $customerstripe->sources->data;
905					} else {
906						$service = 'StripeTest';
907						$servicestatus = 0;
908						if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
909							$service = 'StripeLive';
910							$servicestatus = 1;
911						}
912
913						// Force to use the correct API key
914						global $stripearrayofkeysbyenv;
915						\Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
916
917						try {
918							if (empty($stripeacc)) {				// If the Stripe connect account not set, we use common API usage
919								$paymentmethodobjsA = \Stripe\PaymentMethod::all(array("customer" => $customerstripe->id, "type" => "card"));
920								$paymentmethodobjsB = \Stripe\PaymentMethod::all(array("customer" => $customerstripe->id, "type" => "sepa_debit"));
921							} else {
922								$paymentmethodobjsA = \Stripe\PaymentMethod::all(array("customer" => $customerstripe->id, "type" => "card"), array("stripe_account" => $stripeacc));
923								$paymentmethodobjsB = \Stripe\PaymentMethod::all(array("customer" => $customerstripe->id, "type" => "sepa_debit"), array("stripe_account" => $stripeacc));
924							}
925
926							if ($paymentmethodobjsA->data != null && $paymentmethodobjsB->data != null) {
927								$listofsources = array_merge((array) $paymentmethodobjsA->data, (array) $paymentmethodobjsB->data);
928							} elseif ($paymentmethodobjsB->data != null) {
929								$listofsources = $paymentmethodobjsB->data;
930							} else {
931								$listofsources = $paymentmethodobjsA->data;
932							}
933						} catch (Exception $e) {
934							$error++;
935							setEventMessages($e->getMessage(), null, 'errors');
936						}
937					}
938				}
939			} catch (Exception $e) {
940				dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id);
941			}
942		}
943
944		print '<!-- List of stripe payments -->'."\n";
945		print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
946		print '<table class="liste centpercent">'."\n";
947		print '<tr class="liste_titre">';
948		if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) {
949			print '<td>'.$langs->trans('LocalID').'</td>';
950		}
951		print '<td>'.$langs->trans('Label').'</td>';
952		print '<td>'.$langs->trans('StripeID').'</td>';
953		print '<td>'.$langs->trans('Type').'</td>';
954		print '<td>'.$langs->trans('Informations').'</td>';
955		print '<td></td>';
956		print '<td class="center">'.$langs->trans('Default').'</td>';
957		print '<td>'.$langs->trans('Note').'</td>';
958		print '<td>'.$langs->trans('DateModification').'</td>';
959		// Hook fields
960		$parameters = array('arrayfields'=>array(), 'param'=>'', 'sortfield'=>'', 'sortorder'=>'', 'linetype'=>'stripetitle');
961		$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
962		print $hookmanager->resPrint;
963		// Action column
964		print "<td></td>";
965		print "</tr>\n";
966
967		$nbremote = 0;
968		$nblocal = 0;
969		$arrayofstripecard = array();
970
971		// Show local sources
972		if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) {
973			//$societeaccount = new SocieteAccount($db);
974			$companypaymentmodetemp = new CompanyPaymentMode($db);
975
976			$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."societe_rib";
977			$sql .= " WHERE type in ('card')";
978			$sql .= " AND fk_soc = ".((int) $object->id);
979			$sql .= " AND status = ".((int) $servicestatus);
980
981			$resql = $db->query($sql);
982			if ($resql) {
983				$num_rows = $db->num_rows($resql);
984				if ($num_rows) {
985					$i = 0;
986					while ($i < $num_rows) {
987						$nblocal++;
988
989						$obj = $db->fetch_object($resql);
990						if ($obj) {
991							$companypaymentmodetemp->fetch($obj->rowid);
992
993							$arrayofstripecard[$companypaymentmodetemp->stripe_card_ref] = $companypaymentmodetemp->stripe_card_ref;
994
995							print '<tr class="oddeven">';
996							print '<td>';
997							print $companypaymentmodetemp->id;
998							print '</td>';
999							print '<td>';
1000							print $companypaymentmodetemp->label;
1001							print '</td>';
1002							print '<td>';
1003							print $companypaymentmodetemp->stripe_card_ref;
1004							if ($companypaymentmodetemp->stripe_card_ref) {
1005								$connect = '';
1006								if (!empty($stripeacc)) {
1007									$connect = $stripeacc.'/';
1008								}
1009								$url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$companypaymentmodetemp->stripe_card_ref;
1010								if ($servicestatus) {
1011									$url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$companypaymentmodetemp->stripe_card_ref;
1012								}
1013								print ' <a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe').' - Customer and Publishable key = '.$companypaymentmodetemp->stripe_account, 'globe').'</a>';
1014							}
1015							print '</td>';
1016							print '<td>';
1017							print img_credit_card($companypaymentmodetemp->type);
1018							print '</td>';
1019							print '<td>';
1020							if ($companypaymentmodetemp->proprio) {
1021								print '<span class="opacitymedium">'.$companypaymentmodetemp->proprio.'</span><br>';
1022							}
1023							if ($companypaymentmodetemp->last_four) {
1024								print '....'.$companypaymentmodetemp->last_four;
1025							}
1026							if ($companypaymentmodetemp->exp_date_month || $companypaymentmodetemp->exp_date_year) {
1027								print ' - '.sprintf("%02d", $companypaymentmodetemp->exp_date_month).'/'.$companypaymentmodetemp->exp_date_year.'';
1028							}
1029							print '</td><td>';
1030							if ($companypaymentmodetemp->country_code) {
1031								$img = picto_from_langcode($companypaymentmodetemp->country_code);
1032								print $img ? $img.' ' : '';
1033								print getCountry($companypaymentmodetemp->country_code, 1);
1034							} else {
1035								print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1036							}
1037							print '</td>';
1038							// Default
1039							print '<td class="center">';
1040							if (empty($companypaymentmodetemp->default_rib)) {
1041								print '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&id='.$companypaymentmodetemp->id.'&action=setlocalassourcedefault&token='.newToken().'">';
1042								print img_picto($langs->trans("Default"), 'off');
1043								print '</a>';
1044							} else {
1045								print img_picto($langs->trans("Default"), 'on');
1046							}
1047							print '</td>';
1048							print '<td>';
1049							if (empty($companypaymentmodetemp->stripe_card_ref)) {
1050								print $langs->trans("Local");
1051							} else {
1052								print $langs->trans("LocalAndRemote");
1053							}
1054							print '</td>';
1055							print '<td>';
1056							print dol_print_date($companypaymentmodetemp->tms, 'dayhour');
1057							print '</td>';
1058							// Fields from hook
1059							$parameters = array('arrayfields'=>array(), 'obj'=>$obj, 'linetype'=>'stripecard');
1060							$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
1061							print $hookmanager->resPrint;
1062							// Action column
1063							print '<td class="right nowraponall">';
1064							if ($user->rights->societe->creer) {
1065								if ($stripecu && empty($companypaymentmodetemp->stripe_card_ref)) {
1066									print '<a href="'.$_SERVER['PHP_SELF'].'?action=synccardtostripe&socid='.$object->id.'&id='.$companypaymentmodetemp->id.'" class="paddingrightonly marginrightonly">'.$langs->trans("CreateCardOnStripe").'</a>';
1067								}
1068
1069								print '<a class="editfielda marginleftonly marginrightonly" href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&id='.$companypaymentmodetemp->id.'&action=editcard&token='.newToken().'">';
1070								print img_picto($langs->trans("Modify"), 'edit');
1071								print '</a>';
1072								print '&nbsp;';
1073								print '<a class="marginleftonly marginrightonly" href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&id='.$companypaymentmodetemp->id.'&action=deletecard&token='.newToken().'">'; // source='.$companypaymentmodetemp->stripe_card_ref.'&
1074								print img_picto($langs->trans("Delete"), 'delete');
1075								print '</a>';
1076							}
1077							print '</td>';
1078							print '</tr>';
1079						}
1080						$i++;
1081					}
1082				}
1083			} else {
1084				dol_print_error($db);
1085			}
1086		}
1087
1088		// Show remote sources (not already shown as local source)
1089		if (is_array($listofsources) && count($listofsources)) {
1090			foreach ($listofsources as $src) {
1091				if (!empty($arrayofstripecard[$src->id])) {
1092					continue; // Already in previous list
1093				}
1094
1095				$nbremote++;
1096
1097				print '<tr class="oddeven">';
1098				// Local ID
1099				if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD)) {
1100					print '<td>';
1101					print '</td>';
1102				}
1103				print '<td>';
1104				print '</td>';
1105				// Src ID
1106				print '<td>';
1107				$connect = '';
1108				print $src->id;
1109				if (!empty($stripeacc)) {
1110					$connect = $stripeacc.'/';
1111				}
1112				//$url='https://dashboard.stripe.com/'.$connect.'test/sources/'.$src->id;
1113				$url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$src->id;
1114				if ($servicestatus) {
1115					//$url='https://dashboard.stripe.com/'.$connect.'sources/'.$src->id;
1116					$url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$src->id;
1117				}
1118				print " <a href='".$url."' target='_stripe'>".img_picto($langs->trans('ShowInStripe'), 'globe')."</a>";
1119				print '</td>';
1120				// Img of credit card
1121				print '<td>';
1122				if ($src->object == 'card') {
1123					print img_credit_card($src->brand);
1124				} elseif ($src->object == 'source' && $src->type == 'card') {
1125					print img_credit_card($src->card->brand);
1126				} elseif ($src->object == 'source' && $src->type == 'sepa_debit') {
1127					print '<span class="fa fa-university fa-2x fa-fw"></span>';
1128				} elseif ($src->object == 'payment_method' && $src->type == 'card') {
1129					print img_credit_card($src->card->brand);
1130				} elseif ($src->object == 'payment_method' && $src->type == 'sepa_debit') {
1131					print '<span class="fa fa-university fa-2x fa-fw"></span>';
1132				}
1133				print'</td>';
1134				// Information
1135				print '<td valign="middle">';
1136				if ($src->object == 'card') {
1137					print '....'.$src->last4.' - '.$src->exp_month.'/'.$src->exp_year.'';
1138					print '</td><td>';
1139					if ($src->country) {
1140						$img = picto_from_langcode($src->country);
1141						print $img ? $img.' ' : '';
1142						print getCountry($src->country, 1);
1143					} else {
1144						print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1145					}
1146				} elseif ($src->object == 'source' && $src->type == 'card') {
1147					print '<span class="opacitymedium">'.$src->owner->name.'</span><br>....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.'';
1148					print '</td><td>';
1149
1150					if ($src->card->country) {
1151						$img = picto_from_langcode($src->card->country);
1152						print $img ? $img.' ' : '';
1153						print getCountry($src->card->country, 1);
1154					} else {
1155						print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1156					}
1157				} elseif ($src->object == 'source' && $src->type == 'sepa_debit') {
1158					print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->sepa_debit->last4;
1159					print '</td><td>';
1160					if ($src->sepa_debit->country) {
1161							$img = picto_from_langcode($src->sepa_debit->country);
1162							print $img ? $img.' ' : '';
1163							print getCountry($src->sepa_debit->country, 1);
1164					} else {
1165						print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1166					}
1167				} elseif ($src->object == 'payment_method' && $src->type == 'card') {
1168					print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->card->last4.' - '.$src->card->exp_month.'/'.$src->card->exp_year.'';
1169					print '</td><td>';
1170
1171					if ($src->card->country) {
1172						$img = picto_from_langcode($src->card->country);
1173						print $img ? $img.' ' : '';
1174						print getCountry($src->card->country, 1);
1175					} else {
1176						print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1177					}
1178				} elseif ($src->object == 'payment_method' && $src->type == 'sepa_debit') {
1179					print '<span class="opacitymedium">'.$src->billing_details->name.'</span><br>....'.$src->sepa_debit->last4;
1180					print '</td><td>';
1181					if ($src->sepa_debit->country) {
1182						$img = picto_from_langcode($src->sepa_debit->country);
1183						print $img ? $img.' ' : '';
1184						print getCountry($src->sepa_debit->country, 1);
1185					} else {
1186						print img_warning().' <font class="error">'.$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CompanyCountry")).'</font>';
1187					}
1188				} else {
1189					print '</td><td>';
1190				}
1191				print '</td>';
1192				// Default
1193				print '<td class="center" width="50">';
1194				if ((empty($customerstripe->invoice_settings) && $customerstripe->default_source != $src->id) ||
1195					(!empty($customerstripe->invoice_settings) && $customerstripe->invoice_settings->default_payment_method != $src->id)) {
1196					print '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&source='.$src->id.'&action=setassourcedefault&token='.newToken().'">';
1197					print img_picto($langs->trans("Default"), 'off');
1198					print '</a>';
1199				} else {
1200					print img_picto($langs->trans("Default"), 'on');
1201				}
1202				print '</td>';
1203				print '<td>';
1204				print $langs->trans("Remote");
1205				//if ($src->cvc_check == 'fail') print ' - CVC check fail';
1206				print '</td>';
1207				print '<td>';
1208				//var_dump($src);
1209				print '';
1210				print '</td>';
1211				// Fields from hook
1212				$parameters = array('arrayfields'=>array(), 'stripesource'=>$src, 'linetype'=>'stripecardremoteonly');
1213				$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
1214				print $hookmanager->resPrint;
1215				// Action column
1216				print '<td class="right nowraponall">';
1217				if ($user->rights->societe->creer) {
1218					print '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id.'&source='.$src->id.'&action=deletecard&token='.newToken().'">';
1219					print img_picto($langs->trans("Delete"), 'delete');
1220					print '</a>';
1221				}
1222				print '</td>';
1223
1224				print '</tr>';
1225			}
1226		}
1227
1228		if ($nbremote == 0 && $nblocal == 0) {
1229			$colspan = (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD) ? 10 : 9);
1230			print '<tr><td class="opacitymedium" colspan="'.$colspan.'">'.$langs->trans("None").'</td></tr>';
1231		}
1232		print "</table>";
1233		print "</div>";
1234		print '<br>';
1235	}
1236
1237	// List of Stripe payment modes
1238	if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && !empty($stripesupplieracc)) {
1239		print load_fiche_titre($langs->trans('StripeBalance').($stripesupplieracc ? ' (Stripe connection with StripeConnect account '.$stripesupplieracc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s');
1240		$balance = \Stripe\Balance::retrieve(array("stripe_account" => $stripesupplieracc));
1241		print '<table class="liste centpercent">'."\n";
1242		print '<tr class="liste_titre">';
1243		print '<td>'.$langs->trans('Currency').'</td>';
1244		print '<td>'.$langs->trans('Available').'</td>';
1245		print '<td>'.$langs->trans('Pending').'</td>';
1246		print '<td>'.$langs->trans('Total').'</td>';
1247		print '</tr>';
1248
1249		$currencybalance = array();
1250		if (is_array($balance->available) && count($balance->available)) {
1251			foreach ($balance->available as $cpt) {
1252				$arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
1253				if (!in_array($cpt->currency, $arrayzerounitcurrency)) {
1254						$currencybalance[$cpt->currency]['available'] = $cpt->amount / 100;
1255				} else {
1256					$currencybalance[$cpt->currency]['available'] = $cpt->amount;
1257				}
1258				$currencybalance[$cpt->currency]['currency'] = $cpt->currency;
1259			}
1260		}
1261
1262		if (is_array($balance->pending) && count($balance->pending)) {
1263			foreach ($balance->pending as $cpt) {
1264				$arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
1265				if (!in_array($cpt->currency, $arrayzerounitcurrency)) {
1266					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount / 100;
1267				} else {
1268					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount;
1269				}
1270			}
1271		}
1272
1273		if (is_array($currencybalance)) {
1274			foreach ($currencybalance as $cpt) {
1275				print '<tr><td>'.$langs->trans("Currency".strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'] + $cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td></tr>';
1276			}
1277		}
1278
1279		print '</table>';
1280		print '<br>';
1281	}
1282
1283	// List of bank accounts
1284
1285	$morehtmlright = dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=create');
1286
1287	print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, 'bank');
1288
1289	$rib_list = $object->get_all_rib();
1290	if (is_array($rib_list)) {
1291		print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
1292		print '<table class="liste centpercent">';
1293
1294		print '<tr class="liste_titre">';
1295		print_liste_field_titre("LabelRIB");
1296		print_liste_field_titre("Bank");
1297		print_liste_field_titre("RIB");
1298		print_liste_field_titre("IBAN");
1299		print_liste_field_titre("BIC");
1300		if (!empty($conf->prelevement->enabled)) {
1301			print_liste_field_titre("RUM");
1302			print_liste_field_titre("DateRUM");
1303			print_liste_field_titre("WithdrawMode");
1304		}
1305		print_liste_field_titre("DefaultRIB", '', '', '', '', '', '', '', 'center ');
1306		print_liste_field_titre('', '', '', '', '', '', '', '', 'center ');
1307		print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch ');
1308		print "</tr>\n";
1309
1310		foreach ($rib_list as $rib) {
1311			print '<tr class="oddeven">';
1312			// Label
1313			print '<td>'.$rib->label.'</td>';
1314			// Bank name
1315			print '<td>'.$rib->bank.'</td>';
1316			// Account number
1317			print '<td>';
1318			$string = '';
1319			foreach ($rib->getFieldsToShow() as $val) {
1320				if ($val == 'BankCode') {
1321					$string .= $rib->code_banque.' ';
1322				} elseif ($val == 'BankAccountNumber') {
1323					$string .= $rib->number.' ';
1324				} elseif ($val == 'DeskCode') {
1325					$string .= $rib->code_guichet.' ';
1326				} elseif ($val == 'BankAccountNumberKey') {
1327					$string .= $rib->cle_rib.' ';
1328				}
1329				// Already output after
1330				// } elseif ($val == 'BIC') {
1331				//     $string .= $rib->bic.' ';
1332				// } elseif ($val == 'IBAN') {
1333				//     $string .= $rib->iban.' ';*/
1334				//}
1335			}
1336			if (!empty($rib->label) && $rib->number) {
1337				if (!checkBanForAccount($rib)) {
1338					$string .= ' '.img_picto($langs->trans("ValueIsNotValid"), 'warning');
1339				} else {
1340					$string .= ' '.img_picto($langs->trans("ValueIsValid"), 'info');
1341				}
1342			}
1343
1344			print $string;
1345			print '</td>';
1346			// IBAN
1347			print '<td>'.$rib->iban;
1348			if (!empty($rib->iban)) {
1349				if (!checkIbanForAccount($rib)) {
1350					print ' '.img_picto($langs->trans("IbanNotValid"), 'warning');
1351				}
1352			}
1353			print '</td>';
1354			// BIC
1355			print '<td>'.$rib->bic;
1356			if (!empty($rib->bic)) {
1357				if (!checkSwiftForAccount($rib)) {
1358					print ' '.img_picto($langs->trans("SwiftNotValid"), 'warning');
1359				}
1360			}
1361			print '</td>';
1362
1363			if (!empty($conf->prelevement->enabled)) {
1364				// RUM
1365				//print '<td>'.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).'</td>';
1366				print '<td>'.$rib->rum.'</td>';
1367
1368				print '<td>'.dol_print_date($rib->date_rum, 'day').'</td>';
1369
1370				// FRSTRECUR
1371				print '<td>'.$rib->frstrecur.'</td>';
1372			}
1373
1374			// Default
1375			print '<td class="center" width="70">';
1376			if (!$rib->default_rib) {
1377				print '<a href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&ribid='.$rib->id.'&action=setasbankdefault&token='.newToken().'">';
1378				print img_picto($langs->trans("Disabled"), 'off');
1379				print '</a>';
1380			} else {
1381				print img_picto($langs->trans("Enabled"), 'on');
1382			}
1383			print '</td>';
1384
1385			// Generate doc
1386			print '<td class="center">';
1387
1388			$buttonlabel = $langs->trans("BuildDoc");
1389			$forname = 'builddocrib'.$rib->id;
1390
1391			include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php';
1392			$modellist = ModeleBankAccountDoc::liste_modeles($db);
1393
1394			$out = '';
1395			if (is_array($modellist) && count($modellist)) {
1396				$out .= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc').'" name="'.$forname.'" id="'.$forname.'_form" method="post">';
1397				$out .= '<input type="hidden" name="action" value="builddocrib">';
1398				$out .= '<input type="hidden" name="token" value="'.newToken().'">';
1399				$out .= '<input type="hidden" name="socid" value="'.$object->id.'">';
1400				$out .= '<input type="hidden" name="companybankid" value="'.$rib->id.'">';
1401
1402				if (is_array($modellist) && count($modellist) == 1) {    // If there is only one element
1403					$arraykeys = array_keys($modellist);
1404					$modelselected = $arraykeys[0];
1405				}
1406				if (!empty($conf->global->BANKADDON_PDF)) {
1407					$modelselected = $conf->global->BANKADDON_PDF;
1408				}
1409
1410				$out .= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
1411				$out .= ajax_combobox('modelrib'.$rib->id);
1412
1413				// Language code (if multilang)
1414				if ($conf->global->MAIN_MULTILANGS) {
1415					include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
1416					$formadmin = new FormAdmin($db);
1417					$defaultlang = $codelang ? $codelang : $langs->getDefaultLang();
1418					$morecss = 'maxwidth150';
1419					if ($conf->browser->layout == 'phone') {
1420						$morecss = 'maxwidth100';
1421					}
1422					$out .= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss);
1423				}
1424				// Button
1425				$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
1426				$genbutton .= ' type="submit" value="'.$buttonlabel.'"';
1427				if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) {
1428					$genbutton .= ' disabled';
1429				}
1430				$genbutton .= '>';
1431				if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
1432					$langs->load("errors");
1433					$genbutton .= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
1434				}
1435				if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
1436					$genbutton = '';
1437				}
1438				if (empty($modellist) && !$showempty && $modulepart != 'unpaid') {
1439					$genbutton = '';
1440				}
1441				$out .= $genbutton;
1442				$out .= '</form>';
1443			}
1444			print $out;
1445			print '</td>';
1446
1447			// Edit/Delete
1448			print '<td class="right nowraponall">';
1449			if ($user->rights->societe->creer) {
1450				print '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&id='.$rib->id.'&action=edit">';
1451				print img_picto($langs->trans("Modify"), 'edit');
1452				print '</a>';
1453
1454				print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&id='.$rib->id.'&action=delete&token='.newToken().'">';
1455				print img_picto($langs->trans("Delete"), 'delete');
1456				print '</a>';
1457			}
1458			print '</td>';
1459
1460			print '</tr>';
1461		}
1462
1463		if (count($rib_list) == 0) {
1464			$colspan = 9;
1465			if (!empty($conf->prelevement->enabled)) {
1466				$colspan += 2;
1467			}
1468			print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoBANRecord").'</td></tr>';
1469		}
1470
1471		print '</table>';
1472		print '</div>';
1473	} else {
1474		dol_print_error($db);
1475	}
1476
1477
1478	if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) {
1479		print '<br>';
1480
1481		print '<div class="fichecenter"><div class="fichehalfleft">';
1482		print '<a name="builddoc"></a>'; // ancre
1483
1484		/*
1485		 * Generated documents
1486		 */
1487		$filedir = $conf->societe->multidir_output[$object->entity].'/'.$object->id;
1488		$urlsource = $_SERVER["PHP_SELF"]."?socid=".$object->id;
1489		$genallowed = $user->rights->societe->lire;
1490		$delallowed = $user->rights->societe->creer;
1491
1492		print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
1493
1494		// Show direct download link
1495		if (!empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
1496			$companybankaccounttemp = new CompanyBankAccount($db);
1497			$companypaymentmodetemp = new CompanyPaymentMode($db);
1498			$result = $companypaymentmodetemp->fetch(0, null, $object->id, 'ban');
1499
1500			include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1501			$ecmfile = new EcmFiles($db);
1502			$result = $ecmfile->fetch(0, '', '', '', '', $companybankaccounttemp->table_element, $companypaymentmodetemp->id);
1503			if ($result > 0) {
1504				$companybankaccounttemp->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
1505				print '<br><!-- Link to download main doc -->'."\n";
1506				print showDirectDownloadLink($companybankaccounttemp).'<br>';
1507			}
1508		}
1509
1510		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
1511
1512
1513		print '</div></div></div>';
1514
1515		print '<br>';
1516	}
1517	/*
1518	include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php';
1519	$modellist=ModeleBankAccountDoc::liste_modeles($db);
1520	//print '<td>';
1521	if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
1522	{
1523		$arraykeys=array_keys($modellist);
1524		$modelselected=$arraykeys[0];
1525	}
1526	$out.= $form->selectarray('model', $modellist, $modelselected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100');
1527	$out.= ajax_combobox('model');
1528	//print $out;
1529	$buttonlabel=$langs->trans("Generate");
1530	$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
1531	$genbutton.= ' type="submit" value="'.$buttonlabel.'"';
1532	$genbutton.= '>';
1533	print $genbutton;
1534	//print '</td>';     // TODO Add link to generate doc
1535	*/
1536}
1537
1538// Edit BAN
1539if ($socid && $action == 'edit' && $user->rights->societe->creer) {
1540	print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company');
1541
1542	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1543
1544	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
1545
1546	print '<div class="underbanner clearboth"></div>';
1547
1548	print '<div class="div-table-responsive-no-min">';
1549	print '<table class="border centpercent">';
1550
1551	print '<tr><td class="titlefield fieldrequired">'.$langs->trans("LabelRIB").'</td>';
1552	print '<td><input class="minwidth300" type="text" name="label" value="'.$companybankaccount->label.'"></td></tr>';
1553
1554	print '<tr><td class="fieldrequired">'.$langs->trans("BankName").'</td>';
1555	print '<td><input class="minwidth200" type="text" name="bank" value="'.$companybankaccount->bank.'"></td></tr>';
1556
1557	// Show fields of bank account
1558	foreach ($companybankaccount->getFieldsToShow(1) as $val) {
1559		$require = false;
1560		$tooltip = '';
1561		if ($val == 'BankCode') {
1562			$name = 'code_banque';
1563			$size = 8;
1564			$content = $companybankaccount->code_banque;
1565		} elseif ($val == 'DeskCode') {
1566			$name = 'code_guichet';
1567			$size = 8;
1568			$content = $companybankaccount->code_guichet;
1569		} elseif ($val == 'BankAccountNumber') {
1570			$name = 'number';
1571			$size = 18;
1572			$content = $companybankaccount->number;
1573		} elseif ($val == 'BankAccountNumberKey') {
1574			$name = 'cle_rib';
1575			$size = 3;
1576			$content = $companybankaccount->cle_rib;
1577		} elseif ($val == 'IBAN') {
1578			$name = 'iban';
1579			$size = 30;
1580			$content = $companybankaccount->iban;
1581			if ($companybankaccount->needIBAN()) {
1582				$require = true;
1583			}
1584			$tooltip = $langs->trans("Example").':<br>LT12 1000 0111 0100 1000<br>FR14 2004 1010 0505 0001 3M02 606<br>LU28 0019 4006 4475 0000<br>DE89 3704 0044 0532 0130 00';
1585		} elseif ($val == 'BIC') {
1586			$name = 'bic';
1587			$size = 12;
1588			$content = $companybankaccount->bic;
1589			if ($companybankaccount->needIBAN()) {
1590				$require = true;
1591			}
1592			$tooltip = $langs->trans("Example").': LIABLT2XXXX';
1593		}
1594
1595		print '<tr><td'.($require ? ' class="fieldrequired" ' : '').'>';
1596		if ($tooltip) {
1597			print $form->textwithpicto($langs->trans($val), $tooltip, 4, 'help', '', 0, 3, $name);
1598		} else {
1599			print $langs->trans($val);
1600		}
1601		print '</td>';
1602		print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.$content.'"></td>';
1603		print '</tr>';
1604	}
1605
1606	print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>';
1607	print '<textarea name="domiciliation" rows="4" cols="40" maxlength="255">';
1608	print $companybankaccount->domiciliation;
1609	print "</textarea></td></tr>";
1610
1611	print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>';
1612	print '<td><input class="minwidth300" type="text" name="proprio" value="'.$companybankaccount->proprio.'"></td></tr>';
1613	print "</td></tr>\n";
1614
1615	print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>';
1616	print '<textarea name="owner_address" rows="'.ROWS_4.'" cols="40" maxlength="255">';
1617	print $companybankaccount->owner_address;
1618	print "</textarea></td></tr>";
1619
1620	print '</table>';
1621	print '</div>';
1622
1623	if ($conf->prelevement->enabled) {
1624		print '<br>';
1625
1626		print '<div class="div-table-responsive-no-min">';
1627		print '<table class="border centpercent">';
1628
1629		if (empty($companybankaccount->rum)) {
1630			$companybankaccount->rum = $prelevement->buildRumNumber($object->code_client, $companybankaccount->datec, $companybankaccount->id);
1631		}
1632
1633		// RUM
1634		print '<tr><td class="titlefield">'.$langs->trans("RUM").'</td>';
1635		print '<td><input class="minwidth300" type="text" name="rum" value="'.dol_escape_htmltag($companybankaccount->rum).'"></td></tr>';
1636
1637		$date_rum = dol_mktime(0, 0, 0, GETPOST('date_rummonth'), GETPOST('date_rumday'), GETPOST('date_rumyear'));
1638
1639		print '<tr><td class="titlefield">'.$langs->trans("DateRUM").'</td>';
1640		print '<td>'.$form->selectDate($date_rum ? $date_rum : $companybankaccount->date_rum, 'date_rum', 0, 0, 1, 'date_rum', 1, 1).'</td></tr>';
1641
1642		print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>';
1643		$tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR"));
1644		print $form->selectarray("frstrecur", $tblArraychoice, dol_escape_htmltag(GETPOST('frstrecur', 'alpha') ?GETPOST('frstrecur', 'alpha') : $companybankaccount->frstrecur), 0);
1645		print '</td></tr>';
1646
1647		print '</table>';
1648		print '</div>';
1649	}
1650
1651
1652	print dol_get_fiche_end();
1653
1654	print '<div class="center">';
1655	print '<input class="button" value="'.$langs->trans("Modify").'" type="submit">';
1656	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1657	print '<input class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'" type="submit">';
1658	print '</div>';
1659}
1660
1661// Edit Card
1662if ($socid && $action == 'editcard' && $user->rights->societe->creer) {
1663	print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company');
1664
1665	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1666
1667	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
1668
1669	print '<div class="fichecenter">';
1670
1671	print '<div class="underbanner clearboth"></div>';
1672	print '<table class="border centpercent">';
1673
1674	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Label").'</td>';
1675	print '<td><input class="minwidth300" type="text" id="label" name="label" value="'.$companypaymentmode->label.'"></td></tr>';
1676
1677	print '<tr><td class="fieldrequired">'.$langs->trans("NameOnCard").'</td>';
1678	print '<td><input class="minwidth200" type="text" name="proprio" value="'.$companypaymentmode->proprio.'"></td></tr>';
1679
1680	print '<tr><td>'.$langs->trans("CardNumber").'</td>';
1681	print '<td><input class="minwidth200" type="text" name="cardnumber" value="'.$companypaymentmode->number.'"></td></tr>';
1682
1683	print '<tr><td class="fieldrequired">'.$langs->trans("ExpiryDate").'</td>';
1684	print '<td>';
1685	print $formother->select_month($companypaymentmode->exp_date_month, 'exp_date_month', 1);
1686	print $formother->select_year($companypaymentmode->exp_date_year, 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly');
1687	print '</td></tr>';
1688
1689	print '<tr><td>'.$langs->trans("CVN").'</td>';
1690	print '<td><input size="8" type="text" name="cvn" value="'.$companypaymentmode->cvn.'"></td></tr>';
1691
1692	print '<tr><td>'.$langs->trans("StripeID")." ('card_....')</td>";
1693	print '<td><input class="minwidth300" type="text" name="stripe_card_ref" value="'.$companypaymentmode->stripe_card_ref.'"></td></tr>';
1694
1695	print '</table>';
1696	print '</div>';
1697
1698	print dol_get_fiche_end();
1699
1700	print '<div class="center">';
1701	print '<input class="button" value="'.$langs->trans("Modify").'" type="submit">';
1702	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1703	print '<input class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'" type="submit">';
1704	print '</div>';
1705}
1706
1707
1708// Create BAN
1709if ($socid && $action == 'create' && $user->rights->societe->creer) {
1710	print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company');
1711
1712	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1713
1714	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
1715
1716	print '<div class="nofichecenter">';
1717
1718	print '<div class="underbanner clearboth"></div>';
1719	print '<table class="border centpercent">';
1720
1721	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("LabelRIB").'</td>';
1722	print '<td><input class="minwidth200" type="text" id="label" name="label" value="'.GETPOST('label').'"></td></tr>';
1723
1724	print '<tr><td class="fieldrequired">'.$langs->trans("Bank").'</td>';
1725	print '<td><input class="minwidth200" type="text" name="bank" value="'.GETPOST('bank').'"></td></tr>';
1726
1727	// Show fields of bank account
1728	foreach ($companybankaccount->getFieldsToShow(1) as $val) {
1729		$require = false;
1730		$tooltip = '';
1731		if ($val == 'BankCode') {
1732			$name = 'code_banque';
1733			$size = 8;
1734			$content = $companybankaccount->code_banque;
1735		} elseif ($val == 'DeskCode') {
1736			$name = 'code_guichet';
1737			$size = 8;
1738			$content = $companybankaccount->code_guichet;
1739		} elseif ($val == 'BankAccountNumber') {
1740			$name = 'number';
1741			$size = 18;
1742			$content = $companybankaccount->number;
1743		} elseif ($val == 'BankAccountNumberKey') {
1744			$name = 'cle_rib';
1745			$size = 3;
1746			$content = $companybankaccount->cle_rib;
1747		} elseif ($val == 'IBAN') {
1748			$name = 'iban';
1749			$size = 30;
1750			$content = $companybankaccount->iban;
1751			if ($companybankaccount->needIBAN()) {
1752				$require = true;
1753			}
1754			$tooltip = $langs->trans("Example").':<br>LT12 1000 0111 0100 1000<br>FR14 2004 1010 0505 0001 3M02 606<br>LU28 0019 4006 4475 0000<br>DE89 3704 0044 0532 0130 00';
1755		} elseif ($val == 'BIC') {
1756			$name = 'bic';
1757			$size = 12;
1758			$content = $companybankaccount->bic;
1759			if ($companybankaccount->needIBAN()) {
1760				$require = true;
1761			}
1762			$tooltip = $langs->trans("Example").': LIABLT2XXXX';
1763		}
1764
1765		print '<tr><td'.($require ? ' class="fieldrequired" ' : '').'>';
1766		if ($tooltip) {
1767			print $form->textwithpicto($langs->trans($val), $tooltip, 4, 'help', '', 0, 3, $name);
1768		} else {
1769			print $langs->trans($val);
1770		}
1771		print '</td>';
1772		print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.GETPOST($name).'"></td>';
1773		print '</tr>';
1774	}
1775
1776	print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>';
1777	print '<textarea name="domiciliation" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">';
1778	print GETPOST('domiciliation');
1779	print "</textarea></td></tr>";
1780
1781	print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>';
1782	print '<td><input class="minwidth200" type="text" name="proprio" value="'.GETPOST('proprio').'"></td></tr>';
1783	print "</td></tr>\n";
1784
1785	print '<tr><td>'.$langs->trans("BankAccountOwnerAddress").'</td><td>';
1786	print '<textarea name="owner_address" rows="'.ROWS_4.'" class="quatrevingtpercent" maxlength="255">';
1787	print GETPOST('owner_address');
1788	print "</textarea></td></tr>";
1789
1790	print '</table>';
1791
1792	if ($conf->prelevement->enabled) {
1793		print '<br>';
1794
1795		print '<table class="border centpercent">';
1796
1797		// RUM
1798		print '<tr><td class="titlefieldcreate">'.$langs->trans("RUM").'</td>';
1799		print '<td colspan="4"><input type="text" class="minwidth300" name="rum" value="'.GETPOST('rum', 'alpha').'"> <div class="opacitymedium">'.$langs->trans("RUMWillBeGenerated").'</div></td></tr>';
1800
1801		$date_rum = dol_mktime(0, 0, 0, GETPOST('date_rummonth'), GETPOST('date_rumday'), GETPOST('date_rumyear'));
1802
1803		print '<tr><td class="titlefieldcreate">'.$langs->trans("DateRUM").'</td>';
1804		print '<td colspan="4">'.$form->selectDate($date_rum, 'date_rum', 0, 0, 1, 'date_rum', 1, 1).'</td></tr>';
1805
1806		print '<tr><td>'.$langs->trans("WithdrawMode").'</td><td>';
1807		$tblArraychoice = array("FRST" => $langs->trans("FRST"), "RECUR" => $langs->trans("RECUR"));
1808		print $form->selectarray("frstrecur", $tblArraychoice, (GETPOSTISSET('frstrecur') ? GETPOST('frstrecur') : 'FRST'), 0);
1809		print '</td></tr>';
1810
1811		print '</table>';
1812	}
1813
1814	print '</div>';
1815
1816	print dol_get_fiche_end();
1817
1818	dol_set_focus('#label');
1819
1820	print '<div class="center">';
1821	print '<input class="button" value="'.$langs->trans("Add").'" type="submit">';
1822	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1823	print '<input name="cancel" class="button button-cancel" value="'.$langs->trans("Cancel").'" type="submit">';
1824	print '</div>';
1825}
1826
1827// Create Card
1828if ($socid && $action == 'createcard' && $user->rights->societe->creer) {
1829	print dol_get_fiche_head($head, 'rib', $langs->trans("ThirdParty"), 0, 'company');
1830
1831	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1832
1833	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
1834
1835	print '<div class="nofichecenter">';
1836
1837	print '<div class="underbanner clearboth"></div>';
1838	print '<table class="border centpercent">';
1839
1840	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Label").'</td>';
1841	print '<td><input class="minwidth200" type="text" id="label" name="label" value="'.GETPOST('label', 'alpha').'"></td></tr>';
1842
1843	print '<tr><td class="fieldrequired">'.$langs->trans("NameOnCard").'</td>';
1844	print '<td><input class="minwidth200" type="text" name="proprio" value="'.GETPOST('proprio', 'alpha').'"></td></tr>';
1845
1846	print '<tr><td>'.$langs->trans("CardNumber").'</td>';
1847	print '<td><input class="minwidth200" type="text" name="cardnumber" value="'.GETPOST('cardnumber', 'alpha').'"></td></tr>';
1848
1849	print '<tr><td class="fieldrequired">'.$langs->trans("ExpiryDate").'</td>';
1850	print '<td>';
1851	print $formother->select_month(GETPOST('exp_date_month', 'int'), 'exp_date_month', 1);
1852	print $formother->select_year(GETPOST('exp_date_year', 'int'), 'exp_date_year', 1, 5, 10, 0, 0, '', 'marginleftonly');
1853	print '</td></tr>';
1854
1855	print '<tr><td>'.$langs->trans("CVN").'</td>';
1856	print '<td><input class="width50" type="text" name="cvn" value="'.GETPOST('cvn', 'alpha').'"></td></tr>';
1857
1858	print '<tr><td>'.$langs->trans("StripeID")." ('card_....')</td>";
1859	print '<td><input class="minwidth300" type="text" name="stripe_card_ref" value="'.GETPOST('stripe_card_ref', 'alpha').'"></td></tr>';
1860
1861	print '</table>';
1862
1863	print '</div>';
1864
1865	print dol_get_fiche_end();
1866
1867	dol_set_focus('#label');
1868
1869	print '<div class="center">';
1870	print '<input class="button" value="'.$langs->trans("Add").'" type="submit">';
1871	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1872	print '<input name="cancel" class="button button-cancel" value="'.$langs->trans("Cancel").'" type="submit">';
1873	print '</div>';
1874}
1875
1876if ($socid && ($action == 'edit' || $action == 'editcard') && $user->rights->societe->creer) {
1877	print '</form>';
1878}
1879if ($socid && ($action == 'create' || $action == 'createcard') && $user->rights->societe->creer) {
1880	print '</form>';
1881}
1882
1883// End of page
1884llxFooter();
1885$db->close();
1886