website_helpdesk_hours.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import logging
  4. from odoo import http
  5. from odoo.http import request
  6. from odoo.osv import expression
  7. _logger = logging.getLogger(__name__)
  8. class WebsiteHelpdeskHours(http.Controller):
  9. """Controller for helpdesk hours widget"""
  10. @http.route("/helpdesk/hours/available", type="json", auth="user", website=True)
  11. def get_available_hours(self):
  12. """
  13. Calculate available hours for the authenticated portal user's partner.
  14. Returns:
  15. dict: {
  16. 'total_available': float, # Total hours available
  17. 'hours_used': float, # Hours already delivered/used
  18. 'prepaid_hours': float, # Hours from prepaid orders (not delivered)
  19. 'credit_hours': float, # Hours calculated from available credit
  20. 'credit_available': float, # Available credit amount
  21. 'highest_price': float, # Highest price unit for hours
  22. }
  23. """
  24. try:
  25. # Get contact information early for use in all return cases
  26. company = request.env.company
  27. config_param = request.env["ir.config_parameter"].sudo()
  28. whatsapp_number = config_param.get_param(
  29. "helpdesk_extras.whatsapp_number", ""
  30. )
  31. company_email = company.email or ""
  32. packages_url = config_param.get_param(
  33. "helpdesk_extras.packages_url", "/shop"
  34. )
  35. # Check if user is portal
  36. if not request.env.user._is_portal():
  37. return {
  38. "error": "Access denied: User is not a portal user",
  39. "total_available": 0.0,
  40. "hours_used": 0.0,
  41. "prepaid_hours": 0.0,
  42. "credit_hours": 0.0,
  43. "credit_available": 0.0,
  44. "highest_price": 0.0,
  45. "whatsapp_number": whatsapp_number,
  46. "email": company_email,
  47. "packages_url": packages_url,
  48. }
  49. partner = request.env.user.partner_id.commercial_partner_id
  50. user_partner = request.env.user.partner_id
  51. # Get UoM hour reference (use sudo to access uom.uom)
  52. try:
  53. uom_hour = request.env.ref("uom.product_uom_hour").sudo()
  54. except Exception as e:
  55. return {
  56. "error": f"Error getting UoM hour: {str(e)}",
  57. "total_available": 0.0,
  58. "hours_used": 0.0,
  59. "prepaid_hours": 0.0,
  60. "credit_hours": 0.0,
  61. "credit_available": 0.0,
  62. "highest_price": 0.0,
  63. "whatsapp_number": whatsapp_number,
  64. "email": company_email,
  65. "packages_url": packages_url,
  66. }
  67. # Get helpdesk teams where this user is a collaborator
  68. # Search by both user's partner and commercial partner (in case registered differently)
  69. collaborator_domain = [
  70. "|",
  71. ("partner_id", "=", user_partner.id),
  72. ("partner_id", "=", partner.id),
  73. ]
  74. collaborator_teams = (
  75. request.env["helpdesk.team.collaborator"]
  76. .sudo()
  77. .search(collaborator_domain)
  78. .mapped("team_id")
  79. )
  80. # If user is not a collaborator in any team, return empty results
  81. if not collaborator_teams:
  82. return {
  83. "total_available": 0.0,
  84. "hours_used": 0.0,
  85. "prepaid_hours": 0.0,
  86. "credit_hours": 0.0,
  87. "credit_available": 0.0,
  88. "highest_price": 0.0,
  89. "whatsapp_number": whatsapp_number,
  90. "email": company_email,
  91. "packages_url": packages_url,
  92. }
  93. # Get all prepaid sale order lines for the partner
  94. # Following Odoo's standard procedure from helpdesk_sale_timesheet
  95. SaleOrderLine = request.env["sale.order.line"].sudo()
  96. # Use the same domain that Odoo uses in _get_last_sol_of_customer
  97. # But extend it to include parent/child commercial partner
  98. # And also include orders where the partner is the invoice or shipping address
  99. # This is important for contacts that act as billing contacts for a company
  100. # Base domain for partner matching
  101. partner_domain = expression.OR([
  102. [("order_partner_id", "child_of", partner.id)],
  103. [("order_id.partner_invoice_id", "child_of", partner.id)],
  104. [("order_id.partner_shipping_id", "child_of", partner.id)],
  105. ])
  106. base_domain = [
  107. ("company_id", "=", company.id),
  108. # ("order_partner_id", "child_of", partner.id), # Replaced by partner_domain
  109. ("state", "in", ["sale", "done"]),
  110. ("remaining_hours", ">", 0), # Only lines with remaining hours
  111. ]
  112. # Combine base domain with partner domain
  113. domain = expression.AND([base_domain, partner_domain])
  114. # Check if sale_timesheet module is installed
  115. has_sale_timesheet = "sale_timesheet" in request.env.registry._init_modules
  116. if has_sale_timesheet:
  117. # Use _domain_sale_line_service to filter service products correctly
  118. # This is the same method Odoo uses internally in _get_last_sol_of_customer
  119. try:
  120. service_domain = SaleOrderLine._domain_sale_line_service(
  121. check_state=False
  122. )
  123. # Combine domains using expression.AND() as Odoo does
  124. domain = expression.AND([domain, service_domain])
  125. except Exception:
  126. # Fallback if _domain_sale_line_service is not available
  127. domain = expression.AND(
  128. [
  129. domain,
  130. [
  131. ("product_id.type", "=", "service"),
  132. ("product_id.service_policy", "=", "ordered_prepaid"),
  133. ("remaining_hours_available", "=", True),
  134. ],
  135. ]
  136. )
  137. # Search for prepaid lines following Odoo's standard procedure
  138. prepaid_sol_lines = SaleOrderLine.search(domain)
  139. # NEW LOGIC: Calculate hours based on invoice payment status
  140. # - paid_hours: hours from PAID invoices only (invoice line qty)
  141. # - unpaid_invoice_hours: hours from UNPAID invoices
  142. # - uninvoiced_hours: hours sold but not yet invoiced
  143. paid_hours = 0.0
  144. unpaid_invoice_hours = 0.0
  145. uninvoiced_hours = 0.0
  146. highest_price = 0.0
  147. for line in prepaid_sol_lines:
  148. try:
  149. # Get quantities for this line
  150. qty_sold = line.product_uom_qty or 0.0
  151. qty_invoiced = line.qty_invoiced or 0.0
  152. qty_delivered = line.qty_delivered or 0.0
  153. if qty_sold <= 0:
  154. continue
  155. # Track highest price unit
  156. if line.price_unit > highest_price:
  157. highest_price = line.price_unit
  158. # Calculate uninvoiced hours (sold but not yet invoiced)
  159. qty_uninvoiced = max(0.0, qty_sold - qty_invoiced)
  160. uninvoiced_hours += qty_uninvoiced
  161. # For invoiced portion, check payment status per invoice
  162. invoice_lines = line.invoice_lines.sudo()
  163. if not invoice_lines:
  164. # No invoices - all goes to uninvoiced (already counted above)
  165. continue
  166. # Process each invoice line
  167. for inv_line in invoice_lines:
  168. inv = inv_line.move_id
  169. # Only count posted customer invoices
  170. if inv.move_type != 'out_invoice' or inv.state != 'posted':
  171. continue
  172. inv_qty = inv_line.quantity or 0.0
  173. if inv.payment_state == 'paid':
  174. # Paid invoice - hours are available
  175. paid_hours += inv_qty
  176. else:
  177. # Not paid (not_paid, partial, in_payment, etc.)
  178. unpaid_invoice_hours += inv_qty
  179. except Exception as e:
  180. _logger.debug(
  181. "Error calculating hours for line %s: %s",
  182. line.id,
  183. str(e),
  184. exc_info=True
  185. )
  186. # If no lines with price, try to get price from all prepaid lines (historical)
  187. if highest_price == 0 and prepaid_sol_lines:
  188. for line in prepaid_sol_lines:
  189. if line.price_unit > highest_price:
  190. highest_price = line.price_unit
  191. # Calculate hours used from ALL prepaid lines (including those fully consumed)
  192. # This gives a complete picture of hours used by the customer
  193. # Use the same extended partner domain
  194. base_hours_used_domain = [
  195. ("company_id", "=", company.id),
  196. ("state", "in", ["sale", "done"]),
  197. ]
  198. hours_used_domain = expression.AND([base_hours_used_domain, partner_domain])
  199. if has_sale_timesheet:
  200. try:
  201. service_domain = SaleOrderLine._domain_sale_line_service(
  202. check_state=False
  203. )
  204. hours_used_domain = expression.AND(
  205. [hours_used_domain, service_domain]
  206. )
  207. except Exception:
  208. hours_used_domain = expression.AND(
  209. [
  210. hours_used_domain,
  211. [
  212. ("product_id.type", "=", "service"),
  213. ("product_id.service_policy", "=", "ordered_prepaid"),
  214. ("remaining_hours_available", "=", True),
  215. ],
  216. ]
  217. )
  218. all_prepaid_lines = SaleOrderLine.search(hours_used_domain)
  219. hours_used = 0.0
  220. for line in all_prepaid_lines:
  221. # Calculate hours used: qty_delivered converted to hours
  222. qty_delivered = line.qty_delivered or 0.0
  223. if qty_delivered > 0:
  224. qty_delivered_hours = (
  225. line.product_uom._compute_quantity(
  226. qty_delivered, uom_hour, raise_if_failure=False
  227. )
  228. or 0.0
  229. )
  230. hours_used += qty_delivered_hours
  231. # Calculate credit hours from partner credit limit
  232. credit_from_limit = 0.0
  233. credit_available = 0.0
  234. # Check if credit limit is configured
  235. partner_sudo = partner.sudo()
  236. if company.account_use_credit_limit and partner_sudo.credit_limit > 0:
  237. credit_used = partner_sudo.credit or 0.0
  238. credit_available = max(0.0, partner_sudo.credit_limit - credit_used)
  239. # Convert credit to hours using highest price
  240. if highest_price > 0 and credit_available > 0:
  241. credit_from_limit = credit_available / highest_price
  242. # NEW: Credit hours = uninvoiced hours + unpaid invoice hours + credit limit hours
  243. credit_hours = uninvoiced_hours + unpaid_invoice_hours + credit_from_limit
  244. # Available hours = paid invoice hours only (minus used hours)
  245. prepaid_hours = max(0.0, paid_hours - hours_used)
  246. total_available = prepaid_hours + credit_hours
  247. return {
  248. "total_available": round(total_available, 2),
  249. "hours_used": round(hours_used, 2),
  250. "prepaid_hours": round(prepaid_hours, 2),
  251. "credit_hours": round(credit_hours, 2),
  252. "credit_available": round(credit_available, 2),
  253. "highest_price": round(highest_price, 2),
  254. "whatsapp_number": whatsapp_number,
  255. "email": company_email,
  256. "packages_url": packages_url,
  257. }
  258. except Exception as e:
  259. # Log critical errors with full traceback
  260. _logger.error(
  261. "Error in get_available_hours for partner %s: %s",
  262. request.env.user.partner_id.id if request.env.user else "unknown",
  263. str(e),
  264. exc_info=True
  265. )
  266. # Get contact information for error case
  267. try:
  268. company = request.env.company
  269. config_param = request.env["ir.config_parameter"].sudo()
  270. whatsapp_number = config_param.get_param(
  271. "helpdesk_extras.whatsapp_number", ""
  272. )
  273. company_email = company.email or ""
  274. packages_url = config_param.get_param(
  275. "helpdesk_extras.packages_url", "/shop"
  276. )
  277. except:
  278. whatsapp_number = ""
  279. company_email = ""
  280. packages_url = "/shop"
  281. return {
  282. "error": f"Error al calcular horas disponibles: {str(e)}",
  283. "total_available": 0.0,
  284. "hours_used": 0.0,
  285. "prepaid_hours": 0.0,
  286. "credit_hours": 0.0,
  287. "credit_available": 0.0,
  288. "highest_price": 0.0,
  289. "whatsapp_number": whatsapp_number,
  290. "email": company_email,
  291. "packages_url": packages_url,
  292. }
  293. @http.route("/helpdesk/form/check_block", type="json", auth="public", website=True)
  294. def check_form_block(self, team_id=None):
  295. """
  296. Check if the helpdesk ticket form should be blocked.
  297. Returns True if form should be blocked (has collaborators and no available hours).
  298. Args:
  299. team_id: ID of the helpdesk team
  300. Returns:
  301. dict: {
  302. 'should_block': bool, # True if form should be blocked
  303. 'has_collaborators': bool, # True if team has collaborators
  304. 'has_hours': bool, # True if user has available hours
  305. 'message': str, # Message to show if blocked
  306. }
  307. """
  308. try:
  309. # If user is not portal or public, don't block
  310. if not request.env.user or not request.env.user._is_portal():
  311. return {
  312. "should_block": False,
  313. "has_collaborators": False,
  314. "has_hours": True,
  315. "message": "",
  316. }
  317. if not team_id:
  318. return {
  319. "should_block": False,
  320. "has_collaborators": False,
  321. "has_hours": True,
  322. "message": "",
  323. }
  324. # Get the team
  325. team = request.env["helpdesk.team"].sudo().browse(team_id)
  326. if not team.exists():
  327. return {
  328. "should_block": False,
  329. "has_collaborators": False,
  330. "has_hours": True,
  331. "message": "",
  332. }
  333. # Check if team has collaborators
  334. has_collaborators = bool(team.collaborator_ids)
  335. # If no collaborators, don't block
  336. if not has_collaborators:
  337. return {
  338. "should_block": False,
  339. "has_collaborators": False,
  340. "has_hours": True,
  341. "message": "",
  342. }
  343. # Check if user has available hours
  344. hours_data = self.get_available_hours()
  345. has_hours = hours_data.get("total_available", 0.0) > 0.0
  346. # Block only if has collaborators AND no hours
  347. should_block = has_collaborators and not has_hours
  348. # Get contact information for message
  349. config_param = request.env["ir.config_parameter"].sudo()
  350. whatsapp_number = config_param.get_param(
  351. "helpdesk_extras.whatsapp_number", ""
  352. )
  353. company_email = request.env.company.email or ""
  354. packages_url = config_param.get_param(
  355. "helpdesk_extras.packages_url", "/shop"
  356. )
  357. message = ""
  358. if should_block:
  359. message = "No tienes horas disponibles para crear un ticket. Por favor, contacta con nosotros para adquirir más horas."
  360. if whatsapp_number or company_email:
  361. contact_info = []
  362. if whatsapp_number:
  363. contact_info.append(f"WhatsApp: {whatsapp_number}")
  364. if company_email:
  365. contact_info.append(f"Email: {company_email}")
  366. if contact_info:
  367. message += " " + " | ".join(contact_info)
  368. return {
  369. "should_block": should_block,
  370. "has_collaborators": has_collaborators,
  371. "has_hours": has_hours,
  372. "message": message,
  373. }
  374. except Exception as e:
  375. # Log critical errors with full traceback
  376. _logger.error(
  377. "Error in check_form_block for team_id %s: %s",
  378. team_id,
  379. str(e),
  380. exc_info=True
  381. )
  382. # On error, don't block to avoid breaking the form
  383. return {
  384. "should_block": False,
  385. "has_collaborators": False,
  386. "has_hours": True,
  387. "message": "",
  388. }