dolibarr 25.0.0-alpha
mod_codecompta_minga.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (C) 2026 Joachim Kueter <joachim.kueter@bloxera.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 * or see https://www.gnu.org/
18 */
19
25require_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
26
27
34{
38 public $name = 'Minga';
39
43 public $code;
44
49 public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr'
50
54 public $position = 40;
55
56
60 public $method;
61
65 public $ranges = array();
66
70 public $nbdigits;
71
75 const METHODS = array('code', 'next', 'random', 'fixed');
76
80 const RANDOM_TRIES = 50;
81
82
86 public function __construct()
87 {
88 $this->ranges = array(
89 'customer' => array(
90 'start' => $this->cleanNumber(getDolGlobalString('COMPANY_MINGA_CUSTOMER_START'), 10000),
91 'end' => $this->cleanNumber(getDolGlobalString('COMPANY_MINGA_CUSTOMER_END'), 69999),
92 ),
93 'supplier' => array(
94 'start' => $this->cleanNumber(getDolGlobalString('COMPANY_MINGA_SUPPLIER_START'), 70000),
95 'end' => $this->cleanNumber(getDolGlobalString('COMPANY_MINGA_SUPPLIER_END'), 99999),
96 ),
97 );
98
99 $method = getDolGlobalString('COMPANY_MINGA_METHOD', 'code');
100 $this->method = in_array($method, self::METHODS) ? $method : 'code';
101
102 // Hidden option to use only the last digits of codes made of a date and a counter without separator (CU26070435 with 4 gives 435)
103 $this->nbdigits = max(0, getDolGlobalInt('COMPANY_MINGA_CODE_LAST_DIGITS'));
104 }
105
113 private function cleanNumber($value, $default)
114 {
115 $value = preg_replace('/\D/', '', $value);
116 return ($value === '' ? $default : (int) $value);
117 }
118
119
126 public function info($langs)
127 {
128 global $form;
129
130 $langs->loadLangs(array("admin", "companies"));
131
132 $texte = $langs->trans("ModuleCompanyCode".$this->name)."<br>\n";
133 $texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
134 $texte .= '<input type="hidden" name="token" value="'.newToken().'">';
135 $texte .= '<input type="hidden" name="page_y" value="">';
136 $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
137 $texte .= '<input type="hidden" name="param1" value="COMPANY_MINGA_CUSTOMER_START">';
138 $texte .= '<input type="hidden" name="param2" value="COMPANY_MINGA_CUSTOMER_END">';
139 $texte .= '<input type="hidden" name="param3" value="COMPANY_MINGA_SUPPLIER_START">';
140 $texte .= '<input type="hidden" name="param4" value="COMPANY_MINGA_SUPPLIER_END">';
141 $texte .= '<input type="hidden" name="param5" value="COMPANY_MINGA_METHOD">';
142 $texte .= '<table class="nobordernopadding centpercent">';
143 $texte .= '<tr><td>';
144 $s1 = '<input type="text" class="flat width75" name="value1" value="'.$this->ranges['customer']['start'].'">';
145 $s2 = '<input type="text" class="flat width75" name="value2" value="'.$this->ranges['customer']['end'].'">';
146 $s3 = '<input type="text" class="flat width75" name="value3" value="'.$this->ranges['supplier']['start'].'">';
147 $s4 = '<input type="text" class="flat width75" name="value4" value="'.$this->ranges['supplier']['end'].'">';
148 // trans remove html entities
149 $texte .= $langs->trans("ModuleCompanyCodeCustomer".$this->name, '{s1}', '{s2}')."<br>\n";
150 $texte .= $langs->trans("ModuleCompanyCodeSupplier".$this->name, '{s3}', '{s4}')."<br>\n";
151 $texte = str_replace(array('{s1}', '{s2}', '{s3}', '{s4}'), array($s1, $s2, $s3, $s4), $texte);
152
153 $arrayofmethods = array();
154 foreach (self::METHODS as $method) {
155 $arrayofmethods[$method] = $langs->trans("AccountancyCodeMingaMethod".ucfirst($method));
156 }
157 $texte .= $form->textwithpicto($langs->trans("AccountancyCodeMingaMethod"), $langs->trans("AccountancyCodeMingaMethodHelp"), 1, 'help', '', 1).' ';
158 $texte .= $form->selectarray('value5', $arrayofmethods, $this->method, 0, 0, 0, '', 0, 0, 0, '', 'minwidth300');
159 if ($this->nbdigits > 0) {
160 $texte .= "<br>\n".$langs->trans('COMPANY_MINGA_CODE_LAST_DIGITS').' = '.$this->nbdigits."\n";
161 }
162 $texte .= '</td>';
163 $texte .= '<td class="right"><input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="'.$langs->trans("Modify").'"></td>';
164 $texte .= '</tr></table>';
165 $texte .= '</form>';
166
167 return $texte;
168 }
169
178 public function getExample($langs = null, $objsoc = '', $type = -1)
179 {
180 $examples = array();
181 foreach (array('customer' => 'CU2607-0435', 'supplier' => 'SU2607-0012') as $typetouse => $codeexample) {
182 $start = $this->ranges[$typetouse]['start'];
183 $end = $this->ranges[$typetouse]['end'];
184 if ($this->method == 'code') {
185 $examples[] = $codeexample.' &rarr; '.($start + (int) $this->getNumberFromCode($codeexample));
186 } elseif ($this->method == 'next') {
187 $examples[] = $start.', '.($start + 1).', ...';
188 } elseif ($this->method == 'random') {
189 $examples[] = $start.' ... '.$end;
190 } else {
191 $examples[] = (string) $start;
192 }
193 }
194
195 return implode("<br>\n", $examples);
196 }
197
198
199 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
208 public function get_code($db, $societe, $type = '')
209 {
210 // phpcs:enable
211 global $langs;
212
213 $this->db = $db;
214 $this->code = '';
215
216 if ($type != 'customer' && $type != 'supplier') {
217 $this->error = 'Bad value for parameter type';
218 return -1;
219 }
220
221 $start = $this->ranges[$type]['start'];
222 $end = $this->ranges[$type]['end'];
223
224 dol_syslog(__METHOD__." search code for type=".$type." method=".$this->method." range=".$start."-".$end." company=".(!empty($societe->name) ? $societe->name : ''));
225
226 // Same account for all thirdparties of this type (collective account), so no check if it is already used
227 if ($this->method == 'fixed') {
228 $this->code = (string) $start;
229 dol_syslog(__METHOD__." found code=".$this->code);
230 return 1;
231 }
232
233 $code = -1;
234 if ($start <= $end) {
235 $used = $this->getUsedNumbers($db, $start, $end);
236 if (!is_array($used)) {
237 return -1;
238 }
239
240 if ($this->method == 'code') {
241 $number = $this->getNumberFromCode(is_object($societe) ? (string) ($type == 'customer' ? $societe->code_client : $societe->code_fournisseur) : '');
242 if ($number !== '' && $start + (int) $number <= $end && !isset($used[$start + (int) $number])) {
243 $code = $start + (int) $number;
244 } else {
245 // Derived numbers grow from the start of the range, so the fallback is taken from the end to avoid future collisions
246 $code = $this->findFreeNumber($used, $start, $end, $end, -1);
247 }
248 } elseif ($this->method == 'random') {
249 for ($i = 0; $i < self::RANDOM_TRIES && $code < 0; $i++) {
250 $candidate = random_int($start, $end);
251 if (!isset($used[$candidate])) {
252 $code = $candidate;
253 }
254 }
255 if ($code < 0) {
256 $code = $this->findFreeNumber($used, $start, $end, random_int($start, $end), 1);
257 }
258 } else {
259 // Lowest free number of the range, so numbers already used further in the range (set manually, fallbacks of method 'code', ...) do not move the sequence
260 $code = $this->findFreeNumber($used, $start, $end, $start, 1);
261 }
262 }
263
264 if ($code < 0) {
265 $langs->load("errors");
266 $this->error = $langs->trans("ErrorNoFreeAccountancyCodeInRange", $start, $end);
267 dol_syslog(__METHOD__." ".$this->error, LOG_WARNING);
268 return -1;
269 }
270
271 $this->code = (string) $code;
272 dol_syslog(__METHOD__." found code=".$this->code);
273 return 1;
274 }
275
283 public function getNumberFromCode($code)
284 {
285 $reg = array();
286 if (preg_match('/(\d+)\D*$/', $code, $reg)) {
287 return (string) ((int) ($this->nbdigits > 0 ? substr($reg[1], -$this->nbdigits) : $reg[1]));
288 }
289 return '';
290 }
291
301 private function getUsedNumbers($db, $start, $end)
302 {
303 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
304 $table = 'societe_perentity';
305 $fields = array('accountancy_code_customer', 'accountancy_code_supplier');
306 } else {
307 $table = 'societe';
308 $fields = array('code_compta', 'code_compta_fournisseur');
309 }
310
311 $used = array();
312 foreach ($fields as $field) {
313 $sql = "SELECT ".$db->sanitize($field)." as code FROM ".MAIN_DB_PREFIX.$table;
314 $sql .= " WHERE entity IN (".getEntity('societe').")";
315 if (strlen((string) $start) == strlen((string) $end)) {
316 // Strings of digits with the same length sort like numbers. Other values are filtered below.
317 $sql .= " AND ".$db->sanitize($field)." >= '".$db->escape((string) $start)."'";
318 $sql .= " AND ".$db->sanitize($field)." <= '".$db->escape((string) $end)."'";
319 } else {
320 $sql .= " AND ".$db->sanitize($field)." IS NOT NULL";
321 }
322
323 $resql = $db->query($sql);
324 if (!$resql) {
325 $this->error = $db->lasterror();
326 return -1;
327 }
328 while ($obj = $db->fetch_object($resql)) {
329 $code = trim((string) $obj->code);
330 if (ctype_digit($code) && (int) $code >= $start && (int) $code <= $end) {
331 $used[(int) $code] = 1;
332 }
333 }
334 $db->free($resql);
335 }
336
337 return $used;
338 }
339
351 private function findFreeNumber($used, $min, $max, $from, $step)
352 {
353 $candidate = $from;
354 // Each used number moves the candidate by one, so count($used) + 1 tries are enough to find a free number if there is one
355 $nbtries = min(count($used), $max - $min) + 1;
356 for ($i = 0; $i < $nbtries; $i++) {
357 if (!isset($used[$candidate])) {
358 return $candidate;
359 }
360 $candidate += $step;
361 if ($candidate > $max) {
362 $candidate = $min;
363 } elseif ($candidate < $min) {
364 $candidate = $max;
365 }
366 }
367 return -1;
368 }
369}
Parent class for third parties accountancy code generators.
Class to manage accountancy code of thirdparties with Minga rules.
const RANDOM_TRIES
Max number of random picks before scanning the range for a free number.
getUsedNumbers($db, $start, $end)
Load the numbers of the range already used as customer or supplier accountancy code.
getNumberFromCode($code)
Return the last group of digits of a thirdparty code ('CU2607-0435' gives '435'), limited to its last...
getExample($langs=null, $objsoc='', $type=-1)
Return an example of result returned by getNextValue.
get_code($db, $societe, $type='')
Set accountancy account code for a third party into this->code.
cleanNumber($value, $default)
Return the number made of the digits of a string, or the default value if there is no digit.
info($langs)
Return description of module.
findFreeNumber($used, $min, $max, $from, $step)
Return the first free number of the range, starting at $from and moving in direction $step.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165