ir_sequence.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from datetime import datetime, timedelta
  4. import logging
  5. import pytz
  6. from psycopg2 import sql
  7. from odoo import api, fields, models, _
  8. from odoo.exceptions import UserError
  9. _logger = logging.getLogger(__name__)
  10. def _create_sequence(cr, seq_name, number_increment, number_next):
  11. """ Create a PostreSQL sequence. """
  12. if number_increment == 0:
  13. raise UserError(_('Step must not be zero.'))
  14. sql = "CREATE SEQUENCE %s INCREMENT BY %%s START WITH %%s" % seq_name
  15. cr.execute(sql, (number_increment, number_next))
  16. def _drop_sequences(cr, seq_names):
  17. """ Drop the PostreSQL sequences if they exist. """
  18. names = sql.SQL(',').join(map(sql.Identifier, seq_names))
  19. # RESTRICT is the default; it prevents dropping the sequence if an
  20. # object depends on it.
  21. cr.execute(sql.SQL("DROP SEQUENCE IF EXISTS {} RESTRICT").format(names))
  22. def _alter_sequence(cr, seq_name, number_increment=None, number_next=None):
  23. """ Alter a PostreSQL sequence. """
  24. if number_increment == 0:
  25. raise UserError(_("Step must not be zero."))
  26. cr.execute("SELECT relname FROM pg_class WHERE relkind=%s AND relname=%s", ('S', seq_name))
  27. if not cr.fetchone():
  28. # sequence is not created yet, we're inside create() so ignore it, will be set later
  29. return
  30. statement = sql.SQL("ALTER SEQUENCE") + sql.Identifier(seq_name)
  31. params = []
  32. if number_increment is not None:
  33. statement += sql.SQL("INCREMENT BY") + sql.Placeholder()
  34. params.append(number_increment)
  35. if number_next is not None:
  36. statement += sql.SQL("RESTART WITH") + sql.Placeholder()
  37. params.append(number_next)
  38. cr.execute(statement.join(' '), params)
  39. def _select_nextval(cr, seq_name):
  40. cr.execute("SELECT nextval(%s)", [seq_name])
  41. return cr.fetchone()
  42. def _update_nogap(self, number_increment):
  43. self.flush_recordset(['number_next'])
  44. number_next = self.number_next
  45. self._cr.execute("SELECT number_next FROM %s WHERE id=%%s FOR UPDATE NOWAIT" % self._table, [self.id])
  46. self._cr.execute("UPDATE %s SET number_next=number_next+%%s WHERE id=%%s " % self._table, (number_increment, self.id))
  47. self.invalidate_recordset(['number_next'])
  48. return number_next
  49. def _predict_nextval(self, seq_id):
  50. """Predict next value for PostgreSQL sequence without consuming it"""
  51. # Cannot use currval() as it requires prior call to nextval()
  52. seqname = 'ir_sequence_%s' % seq_id
  53. seqtable = sql.Identifier(seqname)
  54. query = sql.SQL("""SELECT last_value,
  55. (SELECT increment_by
  56. FROM pg_sequences
  57. WHERE sequencename = %s),
  58. is_called
  59. FROM {}""")
  60. params = [seqname]
  61. if self.env.cr._cnx.server_version < 100000:
  62. query = sql.SQL("SELECT last_value, increment_by, is_called FROM {}")
  63. params = []
  64. self.env.cr.execute(query.format(seqtable), params)
  65. (last_value, increment_by, is_called) = self.env.cr.fetchone()
  66. if is_called:
  67. return last_value + increment_by
  68. # sequence has just been RESTARTed to return last_value next time
  69. return last_value
  70. class IrSequence(models.Model):
  71. """ Sequence model.
  72. The sequence model allows to define and use so-called sequence objects.
  73. Such objects are used to generate unique identifiers in a transaction-safe
  74. way.
  75. """
  76. _name = 'ir.sequence'
  77. _description = 'Sequence'
  78. _order = 'name'
  79. def _get_number_next_actual(self):
  80. '''Return number from ir_sequence row when no_gap implementation,
  81. and number from postgres sequence when standard implementation.'''
  82. for seq in self:
  83. if not seq.id:
  84. seq.number_next_actual = 0
  85. elif seq.implementation != 'standard':
  86. seq.number_next_actual = seq.number_next
  87. else:
  88. seq_id = "%03d" % seq.id
  89. seq.number_next_actual = _predict_nextval(self, seq_id)
  90. def _set_number_next_actual(self):
  91. for seq in self:
  92. seq.write({'number_next': seq.number_next_actual or 1})
  93. @api.model
  94. def _get_current_sequence(self, sequence_date=None):
  95. '''Returns the object on which we can find the number_next to consider for the sequence.
  96. It could be an ir.sequence or an ir.sequence.date_range depending if use_date_range is checked
  97. or not. This function will also create the ir.sequence.date_range if none exists yet for today
  98. '''
  99. if not self.use_date_range:
  100. return self
  101. sequence_date = sequence_date or fields.Date.today()
  102. seq_date = self.env['ir.sequence.date_range'].search(
  103. [('sequence_id', '=', self.id), ('date_from', '<=', sequence_date), ('date_to', '>=', sequence_date)], limit=1)
  104. if seq_date:
  105. return seq_date[0]
  106. #no date_range sequence was found, we create a new one
  107. return self._create_date_range_seq(sequence_date)
  108. name = fields.Char(required=True)
  109. code = fields.Char(string='Sequence Code')
  110. implementation = fields.Selection([('standard', 'Standard'), ('no_gap', 'No gap')],
  111. string='Implementation', required=True, default='standard',
  112. help="While assigning a sequence number to a record, the 'no gap' sequence implementation ensures that each previous sequence number has been assigned already. "
  113. "While this sequence implementation will not skip any sequence number upon assignment, there can still be gaps in the sequence if records are deleted. "
  114. "The 'no gap' implementation is slower than the standard one.")
  115. active = fields.Boolean(default=True)
  116. prefix = fields.Char(help="Prefix value of the record for the sequence", trim=False)
  117. suffix = fields.Char(help="Suffix value of the record for the sequence", trim=False)
  118. number_next = fields.Integer(string='Next Number', required=True, default=1, help="Next number of this sequence")
  119. number_next_actual = fields.Integer(compute='_get_number_next_actual', inverse='_set_number_next_actual',
  120. string='Actual Next Number',
  121. help="Next number that will be used. This number can be incremented "
  122. "frequently so the displayed value might already be obsolete")
  123. number_increment = fields.Integer(string='Step', required=True, default=1,
  124. help="The next number of the sequence will be incremented by this number")
  125. padding = fields.Integer(string='Sequence Size', required=True, default=0,
  126. help="Odoo will automatically adds some '0' on the left of the "
  127. "'Next Number' to get the required padding size.")
  128. company_id = fields.Many2one('res.company', string='Company',
  129. default=lambda s: s.env.company)
  130. use_date_range = fields.Boolean(string='Use subsequences per date_range')
  131. date_range_ids = fields.One2many('ir.sequence.date_range', 'sequence_id', string='Subsequences')
  132. @api.model_create_multi
  133. def create(self, vals_list):
  134. """ Create a sequence, in implementation == standard a fast gaps-allowed PostgreSQL sequence is used.
  135. """
  136. seqs = super().create(vals_list)
  137. for seq in seqs:
  138. if seq.implementation == 'standard':
  139. _create_sequence(self._cr, "ir_sequence_%03d" % seq.id, seq.number_increment or 1, seq.number_next or 1)
  140. return seqs
  141. def unlink(self):
  142. _drop_sequences(self._cr, ["ir_sequence_%03d" % x.id for x in self])
  143. return super(IrSequence, self).unlink()
  144. def write(self, values):
  145. new_implementation = values.get('implementation')
  146. for seq in self:
  147. # 4 cases: we test the previous impl. against the new one.
  148. i = values.get('number_increment', seq.number_increment)
  149. n = values.get('number_next', seq.number_next)
  150. if seq.implementation == 'standard':
  151. if new_implementation in ('standard', None):
  152. # Implementation has NOT changed.
  153. # Only change sequence if really requested.
  154. if values.get('number_next'):
  155. _alter_sequence(self._cr, "ir_sequence_%03d" % seq.id, number_next=n)
  156. if seq.number_increment != i:
  157. _alter_sequence(self._cr, "ir_sequence_%03d" % seq.id, number_increment=i)
  158. seq.date_range_ids._alter_sequence(number_increment=i)
  159. else:
  160. _drop_sequences(self._cr, ["ir_sequence_%03d" % seq.id])
  161. for sub_seq in seq.date_range_ids:
  162. _drop_sequences(self._cr, ["ir_sequence_%03d_%03d" % (seq.id, sub_seq.id)])
  163. else:
  164. if new_implementation in ('no_gap', None):
  165. pass
  166. else:
  167. _create_sequence(self._cr, "ir_sequence_%03d" % seq.id, i, n)
  168. for sub_seq in seq.date_range_ids:
  169. _create_sequence(self._cr, "ir_sequence_%03d_%03d" % (seq.id, sub_seq.id), i, n)
  170. res = super(IrSequence, self).write(values)
  171. # DLE P179
  172. self.flush_model(values.keys())
  173. return res
  174. def _next_do(self):
  175. if self.implementation == 'standard':
  176. number_next = _select_nextval(self._cr, 'ir_sequence_%03d' % self.id)
  177. else:
  178. number_next = _update_nogap(self, self.number_increment)
  179. return self.get_next_char(number_next)
  180. def _get_prefix_suffix(self, date=None, date_range=None):
  181. def _interpolate(s, d):
  182. return (s % d) if s else ''
  183. def _interpolation_dict():
  184. now = range_date = effective_date = datetime.now(pytz.timezone(self._context.get('tz') or 'UTC'))
  185. if date or self._context.get('ir_sequence_date'):
  186. effective_date = fields.Datetime.from_string(date or self._context.get('ir_sequence_date'))
  187. if date_range or self._context.get('ir_sequence_date_range'):
  188. range_date = fields.Datetime.from_string(date_range or self._context.get('ir_sequence_date_range'))
  189. sequences = {
  190. 'year': '%Y', 'month': '%m', 'day': '%d', 'y': '%y', 'doy': '%j', 'woy': '%W',
  191. 'weekday': '%w', 'h24': '%H', 'h12': '%I', 'min': '%M', 'sec': '%S'
  192. }
  193. res = {}
  194. for key, format in sequences.items():
  195. res[key] = effective_date.strftime(format)
  196. res['range_' + key] = range_date.strftime(format)
  197. res['current_' + key] = now.strftime(format)
  198. return res
  199. self.ensure_one()
  200. d = _interpolation_dict()
  201. try:
  202. interpolated_prefix = _interpolate(self.prefix, d)
  203. interpolated_suffix = _interpolate(self.suffix, d)
  204. except ValueError:
  205. raise UserError(_('Invalid prefix or suffix for sequence \'%s\'') % self.name)
  206. return interpolated_prefix, interpolated_suffix
  207. def get_next_char(self, number_next):
  208. interpolated_prefix, interpolated_suffix = self._get_prefix_suffix()
  209. return interpolated_prefix + '%%0%sd' % self.padding % number_next + interpolated_suffix
  210. def _create_date_range_seq(self, date):
  211. year = fields.Date.from_string(date).strftime('%Y')
  212. date_from = '{}-01-01'.format(year)
  213. date_to = '{}-12-31'.format(year)
  214. date_range = self.env['ir.sequence.date_range'].search([('sequence_id', '=', self.id), ('date_from', '>=', date), ('date_from', '<=', date_to)], order='date_from desc', limit=1)
  215. if date_range:
  216. date_to = date_range.date_from + timedelta(days=-1)
  217. date_range = self.env['ir.sequence.date_range'].search([('sequence_id', '=', self.id), ('date_to', '>=', date_from), ('date_to', '<=', date)], order='date_to desc', limit=1)
  218. if date_range:
  219. date_from = date_range.date_to + timedelta(days=1)
  220. seq_date_range = self.env['ir.sequence.date_range'].sudo().create({
  221. 'date_from': date_from,
  222. 'date_to': date_to,
  223. 'sequence_id': self.id,
  224. })
  225. return seq_date_range
  226. def _next(self, sequence_date=None):
  227. """ Returns the next number in the preferred sequence in all the ones given in self."""
  228. if not self.use_date_range:
  229. return self._next_do()
  230. # date mode
  231. dt = sequence_date or self._context.get('ir_sequence_date', fields.Date.today())
  232. seq_date = self.env['ir.sequence.date_range'].search([('sequence_id', '=', self.id), ('date_from', '<=', dt), ('date_to', '>=', dt)], limit=1)
  233. if not seq_date:
  234. seq_date = self._create_date_range_seq(dt)
  235. return seq_date.with_context(ir_sequence_date_range=seq_date.date_from)._next()
  236. def next_by_id(self, sequence_date=None):
  237. """ Draw an interpolated string using the specified sequence."""
  238. self.check_access_rights('read')
  239. return self._next(sequence_date=sequence_date)
  240. @api.model
  241. def next_by_code(self, sequence_code, sequence_date=None):
  242. """ Draw an interpolated string using a sequence with the requested code.
  243. If several sequences with the correct code are available to the user
  244. (multi-company cases), the one from the user's current company will
  245. be used.
  246. """
  247. self.check_access_rights('read')
  248. company_id = self.env.company.id
  249. seq_ids = self.search([('code', '=', sequence_code), ('company_id', 'in', [company_id, False])], order='company_id')
  250. if not seq_ids:
  251. _logger.debug("No ir.sequence has been found for code '%s'. Please make sure a sequence is set for current company." % sequence_code)
  252. return False
  253. seq_id = seq_ids[0]
  254. return seq_id._next(sequence_date=sequence_date)
  255. @api.model
  256. def get_id(self, sequence_code_or_id, code_or_id='id'):
  257. """ Draw an interpolated string using the specified sequence.
  258. The sequence to use is specified by the ``sequence_code_or_id``
  259. argument, which can be a code or an id (as controlled by the
  260. ``code_or_id`` argument. This method is deprecated.
  261. """
  262. _logger.warning("ir_sequence.get() and ir_sequence.get_id() are deprecated. "
  263. "Please use ir_sequence.next_by_code() or ir_sequence.next_by_id().")
  264. if code_or_id == 'id':
  265. return self.browse(sequence_code_or_id).next_by_id()
  266. else:
  267. return self.next_by_code(sequence_code_or_id)
  268. @api.model
  269. def get(self, code):
  270. """ Draw an interpolated string using the specified sequence.
  271. The sequence to use is specified by its code. This method is
  272. deprecated.
  273. """
  274. return self.get_id(code, 'code')
  275. class IrSequenceDateRange(models.Model):
  276. _name = 'ir.sequence.date_range'
  277. _description = 'Sequence Date Range'
  278. _rec_name = "sequence_id"
  279. def _get_number_next_actual(self):
  280. '''Return number from ir_sequence row when no_gap implementation,
  281. and number from postgres sequence when standard implementation.'''
  282. for seq in self:
  283. if seq.sequence_id.implementation != 'standard':
  284. seq.number_next_actual = seq.number_next
  285. else:
  286. seq_id = "%03d_%03d" % (seq.sequence_id.id, seq.id)
  287. seq.number_next_actual = _predict_nextval(self, seq_id)
  288. def _set_number_next_actual(self):
  289. for seq in self:
  290. seq.write({'number_next': seq.number_next_actual or 1})
  291. @api.model
  292. def default_get(self, fields):
  293. result = super(IrSequenceDateRange, self).default_get(fields)
  294. result['number_next_actual'] = 1
  295. return result
  296. date_from = fields.Date(string='From', required=True)
  297. date_to = fields.Date(string='To', required=True)
  298. sequence_id = fields.Many2one("ir.sequence", string='Main Sequence', required=True, ondelete='cascade')
  299. number_next = fields.Integer(string='Next Number', required=True, default=1, help="Next number of this sequence")
  300. number_next_actual = fields.Integer(compute='_get_number_next_actual', inverse='_set_number_next_actual',
  301. string='Actual Next Number',
  302. help="Next number that will be used. This number can be incremented "
  303. "frequently so the displayed value might already be obsolete")
  304. def _next(self):
  305. if self.sequence_id.implementation == 'standard':
  306. number_next = _select_nextval(self._cr, 'ir_sequence_%03d_%03d' % (self.sequence_id.id, self.id))
  307. else:
  308. number_next = _update_nogap(self, self.sequence_id.number_increment)
  309. return self.sequence_id.get_next_char(number_next)
  310. def _alter_sequence(self, number_increment=None, number_next=None):
  311. for seq in self:
  312. _alter_sequence(self._cr, "ir_sequence_%03d_%03d" % (seq.sequence_id.id, seq.id), number_increment=number_increment, number_next=number_next)
  313. @api.model_create_multi
  314. def create(self, vals_list):
  315. """ Create a sequence, in implementation == standard a fast gaps-allowed PostgreSQL sequence is used.
  316. """
  317. seqs = super().create(vals_list)
  318. for seq in seqs:
  319. main_seq = seq.sequence_id
  320. if main_seq.implementation == 'standard':
  321. _create_sequence(self._cr, "ir_sequence_%03d_%03d" % (main_seq.id, seq.id), main_seq.number_increment, seq.number_next_actual or 1)
  322. return seqs
  323. def unlink(self):
  324. _drop_sequences(self._cr, ["ir_sequence_%03d_%03d" % (x.sequence_id.id, x.id) for x in self])
  325. return super(IrSequenceDateRange, self).unlink()
  326. def write(self, values):
  327. if values.get('number_next'):
  328. seq_to_alter = self.filtered(lambda seq: seq.sequence_id.implementation == 'standard')
  329. seq_to_alter._alter_sequence(number_next=values.get('number_next'))
  330. # DLE P179: `test_in_invoice_line_onchange_sequence_number_1`
  331. # _update_nogap do a select to get the next sequence number_next
  332. # When changing (writing) the number next of a sequence, the number next must be flushed before doing the select.
  333. # Normally in such a case, we flush just above the execute, but for the sake of performance
  334. # I believe this is better to flush directly in the write:
  335. # - Changing the number next of a sequence is really really rare,
  336. # - But selecting the number next happens a lot,
  337. # Therefore, if I chose to put the flush just above the select, it would check the flush most of the time for no reason.
  338. res = super(IrSequenceDateRange, self).write(values)
  339. self.flush_model(values.keys())
  340. return res