7 protected function _getCurrentExercice()
9 $db = DB
::getInstance();
10 $id = $db->querySingle('SELECT id FROM compta_exercices WHERE cloture = 0 LIMIT 1;');
14 throw new UserException('Aucun exercice en cours.');
20 public function checkExercice()
22 return $this->_getCurrentExercice();
25 protected function _checkOpenExercice($id)
30 $db = DB
::getInstance();
31 $id = $db->simpleQuerySingle('SELECT id FROM compta_exercices
32 WHERE cloture = 0 AND id = ? LIMIT 1;', false, (int)$id);
40 public function getSolde($id_compte, $inclure_sous_comptes = false)
42 $db = DB
::getInstance();
43 $exercice = $this->_getCurrentExercice();
44 $compte = $inclure_sous_comptes
45 ?
'LIKE \'' . $db->escapeString(trim($id_compte)) . '%\''
46 : '= \'' . $db->escapeString(trim($id_compte)) . '\'';
48 $debit = 'COALESCE((SELECT SUM(montant) FROM compta_journal WHERE compte_debit '.$compte.' AND id_exercice = '.(int)$exercice.'), 0)';
49 $credit = 'COALESCE((SELECT SUM(montant) FROM compta_journal WHERE compte_credit '.$compte.' AND id_exercice = '.(int)$exercice.'), 0)';
51 // L'actif augmente au débit, le passif au crédit
52 $position = $db->simpleQuerySingle('SELECT position FROM compta_comptes WHERE id = ?;', false, $id_compte);
54 if (($position & Compta_Comptes
::ACTIF
) ||
($position & Compta_Comptes
::CHARGE
))
56 $query = $debit . ' - ' . $credit;
60 $query = $credit . ' - ' . $debit;
63 return $db->querySingle('SELECT ' . $query . ';');
66 public function getJournalCompte($compte, $inclure_sous_comptes = false)
68 $db = DB
::getInstance();
70 $position = $db->simpleQuerySingle('SELECT position FROM compta_comptes WHERE id = ?;', false, $compte);
72 $exercice = $this->_getCurrentExercice();
73 $compte = $inclure_sous_comptes
74 ?
'LIKE \'' . $db->escapeString(trim($compte)) . '%\''
75 : '= \'' . $db->escapeString(trim($compte)) . '\'';
77 // L'actif et les charges augmentent au débit, le passif et les produits au crédit
78 if (($position & Compta_Comptes
::ACTIF
) ||
($position & Compta_Comptes
::CHARGE
))
89 $query = 'SELECT *, strftime(\'%s\', date) AS date,
90 running_sum(CASE WHEN compte_debit '.$compte.' THEN '.$d.'montant ELSE '.$c.'montant END) AS solde
91 FROM compta_journal WHERE (compte_debit '.$compte.' OR compte_credit '.$compte.') AND id_exercice = '.(int)$exercice.'
94 // Obligatoire pour bien taper dans l'index de la date
95 // sinon running_sum est appelé 2 fois et ça marche pas du coup
96 // FIXME mettre ça ailleurs pour que ça soit appelé moins souvent
97 $db->exec('ANALYZE compta_journal;');
99 $db->resetRunningSum();
100 return $db->simpleStatementFetch($query);
103 public function add($data)
105 $this->_checkFields($data);
107 $db = DB
::getInstance();
109 $data['id_exercice'] = $this->_getCurrentExercice();
111 $db->simpleInsert('compta_journal', $data);
112 $id = $db->lastInsertRowId();
117 public function edit($id, $data)
119 $db = DB
::getInstance();
121 // Vérification que l'on peut éditer cette opération
122 if (!$this->_checkOpenExercice($db->simpleQuerySingle('SELECT id_exercice FROM compta_journal WHERE id = ?;', false, $id)))
124 throw new UserException('Cette opération fait partie d\'un exercice qui a été clôturé.');
127 $this->_checkFields($data);
129 $db->simpleUpdate('compta_journal', $data,
130 'id = \''.trim($id).'\'');
135 public function delete($id)
137 $db = DB
::getInstance();
139 // Vérification que l'on peut éditer cette opération
140 if (!$this->_checkOpenExercice($db->simpleQuerySingle('SELECT id_exercice FROM compta_journal WHERE id = ?;', false, $id)))
142 throw new UserException('Cette opération fait partie d\'un exercice qui a été clôturé.');
145 $db->simpleExec('DELETE FROM membres_operations WHERE id_operation = ?;', (int)$id);
146 $db->simpleExec('DELETE FROM compta_journal WHERE id = ?;', (int)$id);
151 public function get($id)
153 $db = DB
::getInstance();
154 return $db->simpleQuerySingle('SELECT *, strftime(\'%s\', date) AS date FROM compta_journal WHERE id = ?;', true, $id);
157 public function countForMember($id)
159 $db = DB
::getInstance();
160 return $db->simpleQuerySingle('SELECT COUNT(*)
161 FROM compta_journal WHERE id_auteur = ?;', false, (int)$id);
164 public function listForMember($id, $exercice)
166 $db = DB
::getInstance();
167 return $db->simpleStatementFetch('SELECT * FROM compta_journal
168 WHERE id_auteur = ? AND id_exercice = ?;', \SQLITE3_ASSOC
, (int)$id, (int)$exercice);
171 protected function _checkFields(&$data)
173 $db = DB
::getInstance();
175 if (empty($data['libelle']) ||
!trim($data['libelle']))
177 throw new UserException('Le libellé ne peut rester vide.');
180 $data['libelle'] = trim($data['libelle']);
182 if (!empty($data['moyen_paiement'])
183 && !$db->simpleQuerySingle('SELECT 1 FROM compta_moyens_paiement WHERE code = ?;', false, $data['moyen_paiement']))
185 throw new UserException('Moyen de paiement invalide.');
188 if (empty($data['date']) ||
!utils
::checkDate($data['date']))
190 throw new UserException('Date vide ou invalide.');
193 if (!$db->simpleQuerySingle('SELECT 1 FROM compta_exercices WHERE cloture = 0
194 AND debut <= :date AND fin >= :date;', false, ['date' => $data['date']]))
196 throw new UserException('La date ne correspond pas à l\'exercice en cours.');
199 if (empty($data['moyen_paiement']))
201 $data['moyen_paiement'] = null;
202 $data['numero_cheque'] = null;
206 $data['moyen_paiement'] = strtoupper($data['moyen_paiement']);
208 if ($data['moyen_paiement'] != 'CH')
210 $data['numero_cheque'] = null;
213 if (!$db->simpleQuerySingle('SELECT 1 FROM compta_moyens_paiement WHERE code = ? LIMIT 1;',
214 false, $data['moyen_paiement']))
216 throw new UserException('Moyen de paiement invalide.');
220 $data['montant'] = str_replace(',', '.', $data['montant']);
221 $data['montant'] = (float)$data['montant'];
223 if ($data['montant'] <= 0)
225 throw new UserException('Le montant ne peut être égal ou inférieur à zéro.');
228 foreach (['remarques', 'numero_piece', 'numero_cheque'] as $champ)
230 if (empty($data[$champ]) ||
!trim($data[$champ]))
236 $data[$champ] = trim($data[$champ]);
240 if (!array_key_exists('compte_debit', $data) ||
241 (!is_null($data['compte_debit']) &&
242 !$db->simpleQuerySingle('SELECT 1 FROM compta_comptes WHERE id = ?;', false, $data['compte_debit'])))
244 throw new UserException('Compte débité inconnu.');
247 if (!array_key_exists('compte_credit', $data) ||
248 (!is_null($data['compte_credit']) &&
249 !$db->simpleQuerySingle('SELECT 1 FROM compta_comptes WHERE id = ?;', false, $data['compte_credit'])))
251 throw new UserException('Compte crédité inconnu.');
254 $data['compte_credit'] = is_null($data['compte_credit']) ?
null : strtoupper(trim($data['compte_credit']));
255 $data['compte_debit'] = is_null($data['compte_debit']) ?
null : strtoupper(trim($data['compte_debit']));
257 if ($data['compte_credit'] == $data['compte_debit'])
259 throw new UserException('Compte crédité identique au compte débité.');
262 if (isset($data['id_categorie']))
264 if (!$db->simpleQuerySingle('SELECT 1 FROM compta_categories WHERE id = ?;', false, (int)$data['id_categorie']))
266 throw new UserException('Catégorie inconnue.');
269 $data['id_categorie'] = (int)$data['id_categorie'];
273 $data['id_categorie'] = NULL;
276 if (isset($data['id_auteur']))
278 $data['id_auteur'] = (int)$data['id_auteur'];
284 public function getListForCategory($type = null, $cat = null)
286 $db = DB
::getInstance();
287 $exercice = $this->_getCurrentExercice();
289 $query = 'SELECT compta_journal.*, strftime(\'%s\', compta_journal.date) AS date ';
291 if (is_null($cat) && !is_null($type))
293 $query.= ', compta_categories.intitule AS categorie
294 FROM compta_journal LEFT JOIN compta_categories
295 ON compta_journal.id_categorie = compta_categories.id ';
299 $query.= ' FROM compta_journal ';
306 $query .= 'id_categorie = ' . (int)$cat;
308 elseif (is_null($type) && is_null($cat))
310 $query .= 'id_categorie IS NULL';
314 $query.= 'id_categorie IN (SELECT id FROM compta_categories WHERE type = '.(int)$type.')';
317 $query .= ' AND id_exercice = ' . (int)$exercice;
318 $query .= ' ORDER BY date;';
320 return $db->simpleStatementFetch($query);
323 public function searchSQL($query)
325 $db = DB
::getInstance();
327 if (!preg_match('/LIMIT\s+/', $query))
329 $query = preg_replace('/;?\s*$/', '', $query);
330 $query .= ' LIMIT 100';
333 $st = $db->prepare($query);
335 if (!$st->readOnly())
337 throw new UserException('Seules les requêtes en lecture sont autorisées.');
340 $res = $st->execute();
343 while ($row = $res->fetchArray(SQLITE3_ASSOC
))
351 public function schemaSQL()
353 $db = DB
::getInstance();
356 'journal' => $db->querySingle('SELECT sql FROM sqlite_master WHERE type = \'table\' AND name = \'compta_journal\';'),