dolibarr 25.0.0-alpha
creditnote_apply.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Dolibarr contributors
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
25if (!defined('NOTOKENRENEWAL')) {
26 define('NOTOKENRENEWAL', '1');
27}
28if (!defined('NOREQUIREMENU')) {
29 define('NOREQUIREMENU', '1');
30}
31if (!defined('NOREQUIREHTML')) {
32 define('NOREQUIREHTML', '1');
33}
34
35// Load Dolibarr environment
36require '../main.inc.php';
44require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
45require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
47require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
48
49$langs->loadLangs(array('main', 'bills', 'cashdesk', 'banks'));
50
51$action = GETPOST('action', 'aZ09');
52$invoiceid = GETPOSTINT('invoiceid');
53$discountid = GETPOSTINT('discountid');
54$place = (GETPOST('place', 'aZ09') ? GETPOST('place', 'aZ09') : '0');
55
56if (!$user->hasRight('takepos', 'run')) {
58}
59
60
61/*
62 * Actions
63 */
64
65$error = 0;
66$successmsg = '';
67
68if ($action == 'confirm_applycredit' && $discountid > 0 && !empty($_POST['token']) && $user->hasRight('takepos', 'run')) {
69 // Apply the selected credit to the invoice (with auto-split if needed)
70 $db->begin();
71
72 $invoice = new Facture($db);
73 $resf = $invoice->fetch($invoiceid);
74 if ($resf <= 0) {
75 $error++;
76 setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors');
77 }
78
79 $discount = new DiscountAbsolute($db);
80 $resd = $discount->fetch($discountid);
81 if ($resd <= 0 || $discount->fk_soc != $invoice->socid) {
82 // Discount not found or does not belong to this customer
83 $error++;
84 setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors');
85 }
86
87 if (!$error && $discount->fk_facture > 0) {
88 // Already consumed
89 $error++;
90 setEventMessages($langs->trans('ErrorDiscountAlreadyUsed'), null, 'errors');
91 }
92
93 // No validation needed for insert_discount. We add the discount as a line to the draft invoice.
94
95 if (!$error) {
96 $remaintopay = (float) price2num($invoice->getRemainToPay(0), 'MT');
97 $creditamount = (float) price2num($discount->amount_ttc, 'MT');
98
99 if ($remaintopay <= 0) {
100 $error++;
101 setEventMessages($langs->trans('TakeposNoRemainToPay'), null, 'errors');
102 } elseif ($creditamount > $remaintopay) {
103 // Auto split: credit is larger than remain_to_pay
104 $remainder = (float) price2num($creditamount - $remaintopay, 'MT');
105
106 $newDiscounts = $discount->splitAmount($remaintopay, $remainder);
108 $newDiscount1 = $newDiscounts[0];
110 $newDiscount2 = $newDiscounts[1];
111
112 $newid1 = 0;
113 $newid2 = 0;
114
115 // Delete the original before creating the two parts (same pattern as remx.php)
116 $discount->fk_facture_source = 0;
117 $discount->fk_invoice_supplier_source = 0;
118 $res = $discount->delete($user);
119 if ($res <= 0) {
120 $error++;
121 setEventMessages($discount->error, $discount->errors, 'errors');
122 }
123
124 if (!$error) {
125 $newid1 = $newDiscount1->create($user);
126 if ($newid1 <= 0) {
127 $error++;
128 setEventMessages($newDiscount1->error, $newDiscount1->errors, 'errors');
129 }
130 }
131
132 if (!$error) {
133 $newid2 = $newDiscount2->create($user);
134 if ($newid2 <= 0) {
135 $error++;
136 setEventMessages($newDiscount2->error, $newDiscount2->errors, 'errors');
137 }
138 }
139
140 if (!$error) {
141 // Apply the first part (= remaintopay) to the invoice as a line
142 $result = $invoice->insert_discount($newid1);
143 if ($result < 0) {
144 $error++;
145 setEventMessages($invoice->error, $invoice->errors, 'errors');
146 }
147 }
148 } else {
149 // Apply directly without split as a line
150 $result = $invoice->insert_discount($discountid);
151 if ($result < 0) {
152 $error++;
153 setEventMessages($invoice->error, $invoice->errors, 'errors');
154 }
155 }
156 }
157
158 if (!$error) {
159 $db->commit();
160 $successmsg = $langs->trans('TakeposCreditApplied');
161 dol_syslog('creditnote_apply.php: credit '.$discountid.' applied to invoice '.$invoiceid, LOG_DEBUG);
162 } else {
163 $db->rollback();
164 }
165}
166
167
168/*
169 * View
170 */
171
172$head = '<link rel="stylesheet" href="css/pos.css.php">';
173if (getDolGlobalInt('TAKEPOS_COLOR_THEME') == 1) {
174 $head .= '<link rel="stylesheet" href="css/colorful.css">';
175}
176
177top_htmlhead($head, $langs->trans('TakeposApplyAvailableCredit'), 0, 0, array(), array('/takepos/css/pos.css.php'));
178?>
179<body>
180<?php
181
182// Load current invoice to get customer
183$invoice = new Facture($db);
184if ($invoiceid > 0) {
185 $invoice->fetch($invoiceid);
186}
187
188// Show flash messages
190
191// If credit was applied successfully, close colorbox and reload parent #poslines
192if ($successmsg) {
193 ?>
194 <div style="padding:20px; text-align:center;">
195 <p class="ok"><?php echo dol_escape_htmltag($successmsg); ?></p>
196 </div>
197 <script>
198 // Reload parent invoice view and close this colorbox
199 parent.$("#poslines").load("invoice.php?place=" + <?php echo "'".dol_escape_js($place)."'"; ?> + "&invoiceid=<?php echo $invoiceid; ?>&token=<?php echo currentToken(); ?>", function() {
200 parent.$.colorbox.close();
201 });
202 </script>
203 <?php
204 llxFooter();
205 exit;
206}
207
208// List available credits for this customer
209$availableDiscounts = array();
210if ($invoice->id > 0 && $invoice->socid > 0) {
211 $sql = 'SELECT rowid, amount_ht, amount_tva, amount_ttc, description, fk_facture_source, datec, tva_tx';
212 $sql .= ' FROM '.$db->prefix().'societe_remise_except';
213 $sql .= ' WHERE entity = '.((int) $conf->entity);
214 $sql .= ' AND discount_type = 0';
215 $sql .= ' AND fk_soc = '.((int) $invoice->socid);
216 $sql .= ' AND fk_facture IS NULL';
217 $sql .= ' AND fk_facture_line IS NULL';
218 $sql .= ' ORDER BY datec ASC';
219
220 $resql = $db->query($sql);
221 if ($resql) {
222 while ($obj = $db->fetch_object($resql)) {
223 $availableDiscounts[] = $obj;
224 }
225 } else {
226 dol_print_error($db);
227 }
228}
229
230// Confirmation step: a credit was selected, show details before executing
231if ($action == 'applycredit' && $discountid > 0 && empty($error) && $user->hasRight('takepos', 'run')) {
232 $discountToConfirm = new DiscountAbsolute($db);
233 $discountToConfirm->fetch($discountid);
234
235 $remaintopay = ($invoice->id > 0) ? (float) price2num($invoice->getRemainToPay(0), 'MT') : 0;
236 $creditamount = (float) price2num($discountToConfirm->amount_ttc, 'MT');
237
238 $willSplit = ($creditamount > $remaintopay);
239
240 ?>
241 <div style="padding:20px;">
242 <h3><?php echo $langs->trans('TakeposConfirmApplyCredit'); ?></h3>
243
244 <?php if ($remaintopay <= 0) { ?>
245 <p class="error"><?php echo $langs->trans('TakeposNoRemainToPay'); ?></p>
246 <div style="text-align:center; margin-top:20px;">
247 <button type="button" class="butActionDelete" onclick="parent.$.colorbox.close();">
248 <?php echo $langs->trans('Close'); ?>
249 </button>
250 </div>
251 <?php } else { ?>
252 <?php if ($willSplit) {
253 $remainder = price2num($creditamount - $remaintopay, 'MT');
254 echo '<p class="warning">'.$langs->transnoentities(
255 'TakeposCreditSplitAuto',
256 '<strong>'.price($remaintopay, 1, $langs, 1, -1, -1, $conf->currency).'</strong>',
257 '<strong>'.price($remainder, 1, $langs, 1, -1, -1, $conf->currency).'</strong>'
258 ).'</p>';
259 } ?>
260
261 <table class="noborder" style="width:100%;">
262 <tr class="liste_titre">
263 <td><?php echo $langs->trans('TakeposCreditOrigin'); ?></td>
264 <td class="right"><?php echo $langs->trans('TakeposCreditAmount'); ?></td>
265 <td class="center"><?php echo $langs->trans('RemainToPay'); ?></td>
266 </tr>
267 <tr class="oddeven">
268 <td>
269 <?php
270 if ($discountToConfirm->description == '(CREDIT_NOTE)') {
271 echo $langs->trans('CreditNote');
272 } elseif ($discountToConfirm->description == '(DEPOSIT)') {
273 echo $langs->trans('Deposit');
274 } else {
275 echo dol_escape_htmltag($discountToConfirm->description);
276 }
277 if ($discountToConfirm->fk_facture_source > 0) {
278 $srcInv = new Facture($db);
279 $srcInv->fetch($discountToConfirm->fk_facture_source);
280 echo ' — '.dol_escape_htmltag($srcInv->ref);
281 }
282 ?>
283 </td>
284 <td class="right"><strong><?php echo price($creditamount, 1, $langs, 1, -1, -1, $conf->currency); ?></strong></td>
285 <td class="center"><?php echo price($remaintopay, 1, $langs, 1, -1, -1, $conf->currency); ?></td>
286 </tr>
287 </table>
288
289 <br>
290
291 <form method="POST" action="creditnote_apply.php">
292 <input type="hidden" name="token" value="<?php echo newToken(); ?>">
293 <input type="hidden" name="action" value="confirm_applycredit">
294 <input type="hidden" name="invoiceid" value="<?php echo $invoiceid; ?>">
295 <input type="hidden" name="discountid" value="<?php echo $discountid; ?>">
296 <input type="hidden" name="place" value="<?php echo dol_escape_htmltag($place); ?>">
297
298 <div style="text-align:center; margin-top:20px;">
299 <button type="submit" class="butAction">
300 <?php echo $langs->trans('Confirm'); ?>
301 </button>
302 &nbsp;
303 <button type="button" class="butActionDelete" onclick="parent.$.colorbox.close();">
304 <?php echo $langs->trans('Cancel'); ?>
305 </button>
306 </div>
307 </form>
308 <?php } ?>
309 </div>
310 <?php
311
312 llxFooter();
313 exit;
314}
315
316// Default view: list of available credits
317?>
318<div style="padding:15px;">
319 <h3><?php echo $langs->trans('TakeposSelectCreditToApply'); ?></h3>
320
321 <?php if (empty($availableDiscounts)) { ?>
322 <p class="opacitymedium"><?php echo $langs->trans('TakeposNoCreditAvailable'); ?></p>
323 <?php } else { ?>
324 <table class="noborder" style="width:100%;">
325 <tr class="liste_titre">
326 <td><?php echo $langs->trans('TakeposCreditOrigin'); ?></td>
327 <td class="center"><?php echo $langs->trans('TakeposCreditDate'); ?></td>
328 <td class="right"><?php echo $langs->trans('TakeposCreditAmount'); ?></td>
329 <td class="center"><?php echo $langs->trans('Action'); ?></td>
330 </tr>
331 <?php foreach ($availableDiscounts as $disc) {
332 $originLabel = '';
333 if ($disc->description == '(CREDIT_NOTE)') {
334 $originLabel = $langs->trans('CreditNote');
335 } elseif ($disc->description == '(DEPOSIT)') {
336 $originLabel = $langs->trans('Deposit');
337 } elseif ($disc->description == '(EXCESS RECEIVED)') {
338 $originLabel = $langs->trans('ExcessReceived');
339 } else {
340 $originLabel = dol_escape_htmltag($disc->description);
341 }
342 if ($disc->fk_facture_source > 0) {
343 $srcInv = new Facture($db);
344 $srcInv->fetch($disc->fk_facture_source);
345 $originLabel .= ' — '.dol_escape_htmltag($srcInv->ref);
346 }
347 ?>
348 <tr class="oddeven">
349 <td><?php echo $originLabel; ?></td>
350 <td class="center"><?php echo dol_print_date($db->jdate($disc->datec), 'day'); ?></td>
351 <td class="right"><strong><?php echo price($disc->amount_ttc, 1, $langs, 1, -1, -1, $conf->currency); ?></strong></td>
352 <td class="center">
353 <?php
354 $remaintopay = ($invoice->id > 0) ? (float) price2num($invoice->getRemainToPay(0), 'MT') : 0;
355 if ($remaintopay <= 0) {
356 echo '<span class="opacitymedium">'.$langs->trans('TakeposNoRemainToPay').'</span>';
357 } else {
358 ?>
359 <form method="POST" action="creditnote_apply.php" style="display:inline;">
360 <input type="hidden" name="token" value="<?php echo newToken(); ?>">
361 <input type="hidden" name="action" value="applycredit">
362 <input type="hidden" name="invoiceid" value="<?php echo $invoiceid; ?>">
363 <input type="hidden" name="discountid" value="<?php echo (int) $disc->rowid; ?>">
364 <input type="hidden" name="place" value="<?php echo dol_escape_htmltag($place); ?>">
365 <button type="submit" class="butAction" style="padding:4px 10px;">
366 <?php echo $langs->trans('TakeposApplyThisCredit'); ?>
367 </button>
368 </form>
369 <?php } ?>
370 </td>
371 </tr>
372 <?php } ?>
373 </table>
374 <?php } ?>
375
376 <div style="text-align:center; margin-top:20px;">
377 <button type="button" class="butActionDelete" onclick="parent.$.colorbox.close();">
378 <?php echo $langs->trans('Close'); ?>
379 </button>
380 </div>
381</div>
382</body>
383</html>
384<?php
385llxFooter();
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage absolute discounts.
Class to manage invoices.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_htmloutput_events($disabledoutputofmessages=0)
Print formatted messages to output (Used to show messages on html output).
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs=array(), $arrayofcss=array(), $disableforlogin=0, $disablenofollow=0, $disablenoindex=0)
Output html header of a page.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
treeview li table
No Email.