GoodERP
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

291 líneas
13KB

  1. from .utils import safe_division
  2. from odoo.exceptions import UserError
  3. from odoo import models, fields, api
  4. from odoo import _
  5. from odoo.tools import float_compare
  6. import logging
  7. _logger = logging.getLogger(__name__)
  8. class Goods(models.Model):
  9. _inherit = 'goods'
  10. net_weight = fields.Float('净重', digits='Weight')
  11. current_qty = fields.Float('当前数量', compute='compute_stock_qty', digits='Quantity')
  12. max_stock_qty = fields.Float('库存上限', digits='Quantity')
  13. min_stock_qty = fields.Float('库存下限', digits='Quantity')
  14. moq = fields.Float('最小订单量', digits='Quantity')
  15. sell_lead_time = fields.Char('销售备货周期')
  16. excess = fields.Boolean('允许订单超发')
  17. bom_count = fields.Integer('Bom个数', compute="_compute_count")
  18. bom_ids = fields.Many2many('wh.bom', string='Bom', compute="_compute_count")
  19. move_line_count = fields.Integer('调拨次数', compute="_compute_count")
  20. incoming_ids = fields.One2many(
  21. string='即将入库',
  22. comodel_name='wh.move.line',
  23. inverse_name='goods_id',
  24. domain=[('type','=','in'),('state','=','draft')],
  25. readonly=True,
  26. )
  27. outgoing_ids = fields.One2many(
  28. string='即将出库',
  29. comodel_name='wh.move.line',
  30. inverse_name='goods_id',
  31. domain=[('type','=','out'),('state','=','draft')],
  32. readonly=True,
  33. )
  34. available_qty = fields.Float('可用数量', compute='compute_stock_qty', digits='Quantity')
  35. # 使用SQL来取得指定商品情况下的库存数量
  36. def get_stock_qty(self):
  37. for Goods in self:
  38. self.env.cr.execute('''
  39. SELECT sum(line.qty_remaining) as qty,
  40. wh.name as warehouse
  41. FROM wh_move_line line
  42. LEFT JOIN warehouse wh ON line.warehouse_dest_id = wh.id
  43. WHERE line.qty_remaining != 0
  44. AND wh.type = 'stock'
  45. AND line.state = 'done'
  46. AND line.goods_id = %s
  47. GROUP BY wh.name
  48. ''' % (Goods.id,))
  49. return self.env.cr.dictfetchall()
  50. def compute_stock_qty(self):
  51. for g in self:
  52. g.current_qty = sum(line.get('qty') for line in g.get_stock_qty())
  53. g.available_qty = g.current_qty \
  54. + sum(l.goods_qty for l in g.incoming_ids) \
  55. - sum(l.goods_qty for l in g.outgoing_ids)
  56. def _get_cost(self, warehouse=None, ignore=None):
  57. # 如果没有历史的剩余数量,计算最后一条move的成本
  58. # 存在一种情况,计算一条line的成本的时候,先done掉该line,之后在通过该函数
  59. # 查询成本,此时百分百搜到当前的line,所以添加ignore参数来忽略掉指定的line
  60. self.ensure_one()
  61. if warehouse:
  62. domain = [
  63. ('state', '=', 'done'),
  64. ('goods_id', '=', self.id),
  65. ('warehouse_dest_id', '=', warehouse.id)
  66. ]
  67. if ignore:
  68. if isinstance(ignore, int):
  69. ignore = [ignore]
  70. domain.append(('id', 'not in', ignore))
  71. move = self.env['wh.move.line'].search(
  72. domain, limit=1, order='cost_time desc, id desc')
  73. if move:
  74. return move.cost_unit
  75. return self.cost
  76. def get_suggested_cost_by_warehouse(
  77. self, warehouse, qty, lot_id=None, attribute=None, ignore_move=None):
  78. # 存在一种情况,计算一条line的成本的时候,先done掉该line,之后在通过该函数
  79. # 查询成本,此时百分百搜到当前的line,所以添加ignore参数来忽略掉指定的line
  80. if lot_id:
  81. print(lot_id)
  82. records, cost = self.get_matching_records_by_lot( # 有批次:优先按批次去取成本;返回:匹配记录和成本
  83. lot_id, qty, suggested=True)
  84. else:
  85. records, cost = self.get_matching_records( # 没有批次:按 库位 就近、先到期先出、先进先出原则 ->查(wh.move.line)匹配记录去取成本
  86. warehouse, qty, attribute=attribute, ignore_stock=True, ignore=ignore_move)
  87. matching_qty = sum(record.get('qty') for record in records)
  88. if matching_qty:
  89. cost_unit = safe_division(cost, matching_qty)
  90. if matching_qty >= qty:
  91. return cost, cost_unit
  92. else:
  93. cost_unit = self._get_cost(warehouse, ignore=ignore_move)
  94. return cost_unit * qty, cost_unit
  95. def is_using_matching(self):
  96. """
  97. 是否需要获取匹配记录
  98. :return:
  99. """
  100. if self.no_stock:
  101. return False
  102. return True
  103. def is_using_batch(self):
  104. """
  105. 是否使用批号管理
  106. :return:
  107. """
  108. self.ensure_one()
  109. return self.using_batch
  110. def get_matching_records_by_lot(self, lot_id, qty, uos_qty=0, suggested=False):
  111. """
  112. 按批号来获取匹配记录
  113. :param lot_id: 明细中输入的批号
  114. :param qty: 明细中输入的数量
  115. :param uos_qty: 明细中输入的辅助数量
  116. :param suggested:
  117. :return: 匹配记录和成本
  118. """
  119. self.ensure_one()
  120. if not lot_id:
  121. raise UserError(u'批号没有被指定,无法获得成本')
  122. if not suggested and lot_id.state != 'done':
  123. raise UserError(u'正在确认ID为{}的移库行。批号%s还没有实际入库,请先确认该入库'
  124. .format(lot_id.id, lot_id.move_id.name))
  125. decimal_quantity = self.env.ref('core.decimal_quantity')
  126. _logger.info('{} / {} / {} / {}'.format(lot_id.lot, qty, lot_id.qty_remaining, decimal_quantity.digits))
  127. if (float_compare(qty, lot_id.qty_remaining, decimal_quantity.digits) > 0
  128. and not self.env.context.get('wh_in_line_ids')):
  129. raise UserError(_(u'商品%s %s 批次 %s 的库存数量 %s 不够本次出库 %s') % (
  130. self.code and '[%s]' % self.code or '', self.name, lot_id.lot, lot_id.qty_remaining, qty))
  131. return [{'line_in_id': lot_id.id, 'qty': qty, 'uos_qty': uos_qty,
  132. 'expiration_date': lot_id.expiration_date}], \
  133. lot_id.get_real_cost_unit() * qty
  134. def get_matching_records(self, warehouse, qty, uos_qty=0, attribute=None,
  135. ignore_stock=False, ignore=None, move_line=False):
  136. """
  137. 获取匹配记录,不考虑批号
  138. :param ignore_stock: 当参数指定为True的时候,此时忽略库存警告
  139. :param ignore: 一个move_line列表,指定查询成本的时候跳过这些move
  140. :return: 匹配记录和成本
  141. """
  142. matching_records = []
  143. for Goods in self:
  144. domain = [
  145. ('qty_remaining', '>', 0),
  146. ('state', '=', 'done'),
  147. ('warehouse_dest_id', '=', warehouse.id),
  148. ('goods_id', '=', Goods.id)
  149. ]
  150. if ignore:
  151. if isinstance(ignore, int):
  152. domain.append(('id', 'not in', [ignore]))
  153. if attribute:
  154. domain.append(('attribute_id', '=', attribute.id))
  155. # 内部移库,从源库位移到目的库位,匹配时从源库位取值; location.py confirm_change 方法
  156. if self.env.context.get('location'):
  157. domain.append(
  158. ('location_id', '=', self.env.context.get('location')))
  159. # 出库单行 填写了库位
  160. if not self.env.context.get('location') and move_line and move_line.location_id:
  161. domain.append(('location_id', '=', move_line.location_id.id))
  162. """@zzx需要在大量数据的情况下评估一下速度"""
  163. # 出库顺序按 库位 就近、先到期先出、先进先出
  164. lines = self.env['wh.move.line'].search(
  165. domain, order='location_id, expiration_date, cost_time, id')
  166. qty_to_go, uos_qty_to_go, cost = qty, uos_qty, 0 # 分别为待出库商品的数量、辅助数量和成本
  167. for line in lines:
  168. if qty_to_go <= 0 and uos_qty_to_go <= 0:
  169. break
  170. matching_qty = min(line.qty_remaining, qty_to_go)
  171. matching_uos_qty = matching_qty / Goods.conversion
  172. matching_records.append({'line_in_id': line.id, 'expiration_date': line.expiration_date,
  173. 'qty': matching_qty, 'uos_qty': matching_uos_qty})
  174. cost += matching_qty * line.get_real_cost_unit()
  175. qty_to_go -= matching_qty
  176. uos_qty_to_go -= matching_uos_qty
  177. else:
  178. decimal_quantity = self.env.ref('core.decimal_quantity')
  179. if not ignore_stock and float_compare(qty_to_go, 0, decimal_quantity.digits) > 0 and not self.env.context.get('wh_in_line_ids'):
  180. raise UserError(_(u'商品%s %s的库存数量不够本次出库') % (Goods.code and '[%s]' % Goods.code or '', Goods.name,))
  181. if self.env.context.get('wh_in_line_ids'):
  182. domain = [('id', 'in', self.env.context.get('wh_in_line_ids')),
  183. ('state', '=', 'done'),
  184. ('warehouse_dest_id', '=', warehouse.id),
  185. ('goods_id', '=', Goods.id)]
  186. if attribute:
  187. domain.append(('attribute_id', '=', attribute.id))
  188. line_in_id = self.env['wh.move.line'].search(
  189. domain, order='expiration_date, cost_time, id')
  190. if line_in_id:
  191. matching_records.append({'line_in_id': line_in_id.id, 'expiration_date': line_in_id.expiration_date,
  192. 'qty': qty_to_go, 'uos_qty': uos_qty_to_go})
  193. return matching_records, cost
  194. _used_not_allowed_modification = ({'uom_id','uos_id','conversion'},
  195. '商品已被使用, 不允许修改单位或转化率')
  196. def write(self, vals):
  197. used_fields, used_msg = self._used_not_allowed_modification
  198. if len(used_fields)>0 and ( set(vals.keys()).intersection(used_fields) ):
  199. # 所有用到了商品的字段
  200. self.env.cr.execute("select imf.name, imf.model from goods_reference_black_list grbl "+
  201. "left join ir_model_fields imf on imf.model_id = grbl.ref_model_id" +
  202. " where imf.relation=%s " +
  203. "and imf.ttype in ('many2one') and imf.store=true;",
  204. ('goods', ))
  205. relation_fields = self.env.cr.fetchall()
  206. for goods in self:
  207. been_used = False
  208. # 所有用到了当前商品的记录
  209. for field, model in relation_fields:
  210. if not been_used:
  211. sql = "select id from " + model.replace('.', '_') + \
  212. " where " + field + "=" + str(goods.id) + ";"
  213. self.env.cr.execute(sql)
  214. if self.env.cr.fetchall():
  215. been_used = True
  216. if been_used:
  217. raise UserError(used_msg)
  218. return super().write(vals)
  219. def _compute_count(self):
  220. ''' 此商品作为组合件的BOM个数 '''
  221. for s in self:
  222. bom_lines = self.env['wh.bom.line'].search(
  223. [('goods_id', '=', s.id),
  224. ('type', '=', 'parent')])
  225. s.bom_ids = [(6, 0, list(set([l.bom_id.id for l in bom_lines])))]
  226. s.bom_count = len(s.bom_ids)
  227. move_lines = self.env['wh.move.line'].search(
  228. [('goods_id', '=', s.id),
  229. ('state', '=', 'done')])
  230. s.move_line_count = len(move_lines)
  231. def button_list_bom(self):
  232. return {
  233. 'name': '%s 物料清单' % self.name,
  234. 'view_mode': 'list,form',
  235. 'res_model': 'wh.bom',
  236. 'type': 'ir.actions.act_window',
  237. 'domain': [('id', 'in', self.bom_ids.ids)],
  238. }
  239. def button_list_move(self):
  240. return {
  241. 'name': '%s 库存调拨' % self.name,
  242. 'view_mode': 'list',
  243. 'res_model': 'wh.move.line',
  244. 'type': 'ir.actions.act_window',
  245. 'domain': [('goods_id', '=', self.id)],
  246. 'context': {'search_default_done':1}
  247. }
  248. class GoodsReferenceBlackList(models.Model):
  249. _name = 'goods.reference.black.list'
  250. _description = '商品引用检测黑名单'
  251. ref_model_id = fields.Many2one('ir.model', '模型', help='指定的模型若有引用商品的,该商品对应的单位或转化率无法进行修改')
上海开阖软件有限公司 沪ICP备12045867号-1