website_helpdesk_hours.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. # Get UoM hour reference (use sudo to access uom.uom)
  51. try:
  52. uom_hour = request.env.ref("uom.product_uom_hour").sudo()
  53. except Exception as e:
  54. return {
  55. "error": f"Error getting UoM hour: {str(e)}",
  56. "total_available": 0.0,
  57. "hours_used": 0.0,
  58. "prepaid_hours": 0.0,
  59. "credit_hours": 0.0,
  60. "credit_available": 0.0,
  61. "highest_price": 0.0,
  62. "whatsapp_number": whatsapp_number,
  63. "email": company_email,
  64. "packages_url": packages_url,
  65. }
  66. # Get helpdesk teams where this user is a collaborator
  67. collaborator_teams = (
  68. request.env["helpdesk.team.collaborator"]
  69. .sudo()
  70. .search([("partner_id", "=", partner.id)])
  71. .mapped("team_id")
  72. )
  73. # If user is not a collaborator in any team, return empty results
  74. if not collaborator_teams:
  75. return {
  76. "total_available": 0.0,
  77. "hours_used": 0.0,
  78. "prepaid_hours": 0.0,
  79. "credit_hours": 0.0,
  80. "credit_available": 0.0,
  81. "highest_price": 0.0,
  82. "whatsapp_number": whatsapp_number,
  83. "email": company_email,
  84. "packages_url": packages_url,
  85. }
  86. # Get all prepaid sale order lines for the partner
  87. # Following Odoo's standard procedure from helpdesk_sale_timesheet
  88. SaleOrderLine = request.env["sale.order.line"].sudo()
  89. # Use the same domain that Odoo uses in _get_last_sol_of_customer
  90. # This ensures we follow Odoo's standard procedure
  91. domain = [
  92. ("company_id", "=", company.id),
  93. ("order_partner_id", "child_of", partner.id),
  94. ("state", "in", ["sale", "done"]),
  95. ("remaining_hours", ">", 0), # Only lines with remaining hours
  96. ]
  97. # Check if sale_timesheet module is installed
  98. has_sale_timesheet = "sale_timesheet" in request.env.registry._init_modules
  99. if has_sale_timesheet:
  100. # Use _domain_sale_line_service to filter service products correctly
  101. # This is the same method Odoo uses internally in _get_last_sol_of_customer
  102. try:
  103. service_domain = SaleOrderLine._domain_sale_line_service(
  104. check_state=False
  105. )
  106. # Combine domains using expression.AND() as Odoo does
  107. domain = expression.AND([domain, service_domain])
  108. except Exception:
  109. # Fallback if _domain_sale_line_service is not available
  110. domain = expression.AND(
  111. [
  112. domain,
  113. [
  114. ("product_id.type", "=", "service"),
  115. ("product_id.service_policy", "=", "ordered_prepaid"),
  116. ("remaining_hours_available", "=", True),
  117. ],
  118. ]
  119. )
  120. # Search for prepaid lines following Odoo's standard procedure
  121. prepaid_sol_lines = SaleOrderLine.search(domain)
  122. # Filter lines from orders that have received payment
  123. # Only consider hours from orders with paid invoices
  124. helpdesk_team_model = request.env["helpdesk.team"]
  125. # Filter lines from orders that have received payment
  126. # Use explicit loop to handle exceptions properly
  127. paid_prepaid_lines = request.env["sale.order.line"].sudo()
  128. for line in prepaid_sol_lines:
  129. try:
  130. if helpdesk_team_model._is_order_paid(line.order_id):
  131. paid_prepaid_lines |= line
  132. except Exception as e:
  133. # Log exception only in debug mode
  134. _logger.debug(
  135. "Error checking payment for line %s, order %s: %s",
  136. line.id,
  137. line.order_id.id,
  138. str(e),
  139. exc_info=True
  140. )
  141. # Calculate prepaid hours using Odoo's remaining_hours field
  142. # This is the correct way as it handles UOM conversion automatically
  143. prepaid_hours = 0.0
  144. highest_price = 0.0
  145. for line in paid_prepaid_lines:
  146. # Use remaining_hours directly (already in hours, handles UOM conversion)
  147. # This is the field Odoo uses and calculates correctly
  148. remaining = line.remaining_hours or 0.0
  149. prepaid_hours += max(0.0, remaining)
  150. # Track highest price unit
  151. if line.price_unit > highest_price:
  152. highest_price = line.price_unit
  153. # If no paid lines with price, try to get price from all prepaid lines (historical)
  154. # This is needed to calculate credit_hours even if there are no paid lines currently
  155. if highest_price == 0 and prepaid_sol_lines:
  156. for line in prepaid_sol_lines:
  157. if line.price_unit > highest_price:
  158. highest_price = line.price_unit
  159. # Calculate hours used from ALL prepaid lines (including those fully consumed)
  160. # This gives a complete picture of hours used by the customer
  161. hours_used_domain = [
  162. ("company_id", "=", company.id),
  163. ("order_partner_id", "child_of", partner.id),
  164. ("state", "in", ["sale", "done"]),
  165. ]
  166. if has_sale_timesheet:
  167. try:
  168. service_domain = SaleOrderLine._domain_sale_line_service(
  169. check_state=False
  170. )
  171. hours_used_domain = expression.AND(
  172. [hours_used_domain, service_domain]
  173. )
  174. except Exception:
  175. hours_used_domain = expression.AND(
  176. [
  177. hours_used_domain,
  178. [
  179. ("product_id.type", "=", "service"),
  180. ("product_id.service_policy", "=", "ordered_prepaid"),
  181. ("remaining_hours_available", "=", True),
  182. ],
  183. ]
  184. )
  185. all_prepaid_lines = SaleOrderLine.search(hours_used_domain)
  186. # Filter lines from orders that have received payment
  187. # Only consider hours used from orders with paid invoices
  188. # Use explicit loop to handle exceptions properly
  189. paid_all_prepaid_lines = request.env["sale.order.line"].sudo()
  190. for line in all_prepaid_lines:
  191. try:
  192. if helpdesk_team_model._is_order_paid(line.order_id):
  193. paid_all_prepaid_lines |= line
  194. except Exception as e:
  195. # Log exception only in debug mode
  196. _logger.debug(
  197. "Error checking payment for line %s, order %s: %s",
  198. line.id,
  199. line.order_id.id,
  200. str(e),
  201. exc_info=True
  202. )
  203. hours_used = 0.0
  204. for line in paid_all_prepaid_lines:
  205. # Calculate hours used: qty_delivered converted to hours
  206. # Use the same UOM conversion that Odoo uses
  207. qty_delivered = line.qty_delivered or 0.0
  208. if qty_delivered > 0:
  209. qty_delivered_hours = (
  210. line.product_uom._compute_quantity(
  211. qty_delivered, uom_hour, raise_if_failure=False
  212. )
  213. or 0.0
  214. )
  215. hours_used += qty_delivered_hours
  216. # Calculate credit hours
  217. credit_hours = 0.0
  218. credit_available = 0.0
  219. # Check if credit limit is configured
  220. # Use sudo to access credit fields which may have restricted access
  221. partner_sudo = partner.sudo()
  222. if company.account_use_credit_limit and partner_sudo.credit_limit > 0:
  223. credit_used = partner_sudo.credit or 0.0
  224. credit_available = max(0.0, partner_sudo.credit_limit - credit_used)
  225. # Convert credit to hours using highest price
  226. if highest_price > 0 and credit_available > 0:
  227. credit_hours = credit_available / highest_price
  228. elif highest_price == 0 and credit_available > 0:
  229. # If no hours sold yet, we can't calculate credit hours
  230. # But we still show the credit available
  231. credit_hours = 0.0
  232. total_available = prepaid_hours + credit_hours
  233. return {
  234. "total_available": round(total_available, 2),
  235. "hours_used": round(hours_used, 2),
  236. "prepaid_hours": round(prepaid_hours, 2),
  237. "credit_hours": round(credit_hours, 2),
  238. "credit_available": round(credit_available, 2),
  239. "highest_price": round(highest_price, 2),
  240. "whatsapp_number": whatsapp_number,
  241. "email": company_email,
  242. "packages_url": packages_url,
  243. }
  244. except Exception as e:
  245. # Log critical errors with full traceback
  246. _logger.error(
  247. "Error in get_available_hours for partner %s: %s",
  248. request.env.user.partner_id.id if request.env.user else "unknown",
  249. str(e),
  250. exc_info=True
  251. )
  252. # Get contact information for error case
  253. try:
  254. company = request.env.company
  255. config_param = request.env["ir.config_parameter"].sudo()
  256. whatsapp_number = config_param.get_param(
  257. "helpdesk_extras.whatsapp_number", ""
  258. )
  259. company_email = company.email or ""
  260. packages_url = config_param.get_param(
  261. "helpdesk_extras.packages_url", "/shop"
  262. )
  263. except:
  264. whatsapp_number = ""
  265. company_email = ""
  266. packages_url = "/shop"
  267. return {
  268. "error": f"Error al calcular horas disponibles: {str(e)}",
  269. "total_available": 0.0,
  270. "hours_used": 0.0,
  271. "prepaid_hours": 0.0,
  272. "credit_hours": 0.0,
  273. "credit_available": 0.0,
  274. "highest_price": 0.0,
  275. "whatsapp_number": whatsapp_number,
  276. "email": company_email,
  277. "packages_url": packages_url,
  278. }
  279. @http.route("/helpdesk/form/check_block", type="json", auth="public", website=True)
  280. def check_form_block(self, team_id=None):
  281. """
  282. Check if the helpdesk ticket form should be blocked.
  283. Returns True if form should be blocked (has collaborators and no available hours).
  284. Args:
  285. team_id: ID of the helpdesk team
  286. Returns:
  287. dict: {
  288. 'should_block': bool, # True if form should be blocked
  289. 'has_collaborators': bool, # True if team has collaborators
  290. 'has_hours': bool, # True if user has available hours
  291. 'message': str, # Message to show if blocked
  292. }
  293. """
  294. try:
  295. # If user is not portal or public, don't block
  296. if not request.env.user or not request.env.user._is_portal():
  297. return {
  298. "should_block": False,
  299. "has_collaborators": False,
  300. "has_hours": True,
  301. "message": "",
  302. }
  303. if not team_id:
  304. return {
  305. "should_block": False,
  306. "has_collaborators": False,
  307. "has_hours": True,
  308. "message": "",
  309. }
  310. # Get the team
  311. team = request.env["helpdesk.team"].sudo().browse(team_id)
  312. if not team.exists():
  313. return {
  314. "should_block": False,
  315. "has_collaborators": False,
  316. "has_hours": True,
  317. "message": "",
  318. }
  319. # Check if team has collaborators
  320. has_collaborators = bool(team.collaborator_ids)
  321. # If no collaborators, don't block
  322. if not has_collaborators:
  323. return {
  324. "should_block": False,
  325. "has_collaborators": False,
  326. "has_hours": True,
  327. "message": "",
  328. }
  329. # Check if user has available hours
  330. hours_data = self.get_available_hours()
  331. has_hours = hours_data.get("total_available", 0.0) > 0.0
  332. # Block only if has collaborators AND no hours
  333. should_block = has_collaborators and not has_hours
  334. # Get contact information for message
  335. config_param = request.env["ir.config_parameter"].sudo()
  336. whatsapp_number = config_param.get_param(
  337. "helpdesk_extras.whatsapp_number", ""
  338. )
  339. company_email = request.env.company.email or ""
  340. packages_url = config_param.get_param(
  341. "helpdesk_extras.packages_url", "/shop"
  342. )
  343. message = ""
  344. if should_block:
  345. message = "No tienes horas disponibles para crear un ticket. Por favor, contacta con nosotros para adquirir más horas."
  346. if whatsapp_number or company_email:
  347. contact_info = []
  348. if whatsapp_number:
  349. contact_info.append(f"WhatsApp: {whatsapp_number}")
  350. if company_email:
  351. contact_info.append(f"Email: {company_email}")
  352. if contact_info:
  353. message += " " + " | ".join(contact_info)
  354. return {
  355. "should_block": should_block,
  356. "has_collaborators": has_collaborators,
  357. "has_hours": has_hours,
  358. "message": message,
  359. }
  360. except Exception as e:
  361. # Log critical errors with full traceback
  362. _logger.error(
  363. "Error in check_form_block for team_id %s: %s",
  364. team_id,
  365. str(e),
  366. exc_info=True
  367. )
  368. # On error, don't block to avoid breaking the form
  369. return {
  370. "should_block": False,
  371. "has_collaborators": False,
  372. "has_hours": True,
  373. "message": "",
  374. }