Merge pull request #3283 from expsa/dev_odex25_mobile

Dev odex25 mobile
This commit is contained in:
mohammed-alkhazrji 2025-05-21 23:32:35 +03:00 committed by GitHub
commit 2a54f450f2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 161 additions and 51 deletions

View File

@ -2,13 +2,15 @@
import logging
import traceback
from odoo import http, _
from odoo import http, _ ,SUPERUSER_ID
from odoo.exceptions import UserError, AccessError, ValidationError
from odoo.http import request
from ...http_helper import http_helper
from ...validator import validator
from datetime import date, datetime
from odoo.addons.web.controllers.main import ReportController
from werkzeug import exceptions
import json
_logger = logging.getLogger(__name__)
@ -329,48 +331,90 @@ class EmployeeOtherRequestController(http.Controller):
Build a dictionary of fields to return for a single record
(similar to the detailed response in 3.3 Get Request by ID)
"""
dict_type_report_name={
'salary_define/detail':'employee_requests.action_report_employee_identification',
'salary_define/no_detail':'employee_requests.action_report_employee_identify_2',
'salary_define/no_salary':'employee_requests.action_report_employee_identify_3',
'salary_fixing':'employee_requests.salary_conf_report_act',
}
define_key = f'{req.request_type}/{req.print_type}' if req.request_type=='salary_define' else req.request_type
res = {
"id": req.id,
"from_hr": req.from_hr,
"date": req.date,
"comment": req.comment or "",
"state": req.state,
'request_type': req.request_type,
'request_type_lable': self.get_lable_selection(req, 'request_type', req.request_type),
'state': req.state,
'state_name': self.get_lable_selection(req, 'state', req.state),
"request_type": req.request_type,
"employee_id": req.employee_id.id if req.employee_id else None,
"employee_name": req.employee_id.name if req.employee_id else None,
"employee_dependant": [],
"qualification_employee": [],
"certification_employee": [],
"create_insurance_request": req.create_insurance_request,
"print_type": req.print_type,
"print_type_name": self.get_lable_selection(req, 'print_type', req.print_type),
"destination": req.destination.id if req.destination else None,
'destination_name': req.destination.name if req.destination else None,
"parent_request_id": req.parent_request_id.id if req.parent_request_id else None,
"company_id": req.company_id.id if req.company_id else None,
"company_name": req.company_id.name if req.company_id else None,
"report_url": f'/rest_api/v2/public_report/pdf/{dict_type_report_name.get(define_key,"No Report")}/{req.id}'
}
res = convert_dates_in_data(res)
# Build One2many lines for employee_dependant
for dep in req.employee_dependant:
res["employee_dependant"].append({
"name": dep.name,
"relation": dep.relation,
"date_of_birth": dep.date_of_birth,
'name': dep.name or '',
'age': dep.age or '',
'birthday': str(dep.birthday or ''),
'gender': dep.gender or '',
'gender_lable': self.get_lable_selection(dep, 'gender', dep.gender),
'relation': dep.relation or '',
'relation_lable': self.get_lable_selection(dep, 'relation', dep.relation),
'nationality': dep.nationality.read(['id', 'name'])[0] or {},
'passport_no': dep.passport_no or '',
'passport_issue_date': str(dep.passport_issue_date or ''),
'passport_expire_date': str(dep.passport_expire_date or ''),
'degree_medical_insu': dep.degree_medical_insu or '',
'medical_insurance_num': dep.medical_insurance_num or '',
'identity_num': dep.identity_num or '',
'has_ticket': dep.has_ticket,
})
# Build One2many lines for qualification_employee
for q in req.qualification_employee:
for qua in req.qualification_employee:
res["qualification_employee"].append({
"qualification_name": q.qualification_name,
"date_obtained": q.date_obtained,
"institute": q.institute,
'uni_name_UniversityName': qua.uni_name.read(['id', 'name'])[0] or {},
'col_name_CollegeName': qua.col_name.read(['id', 'name'])[0] or {},
'prg_status': qua.prg_status or '',
'comp_date': str(qua.comp_date or ''),
'end_date': str(qua.end_date or ''),
'degree': qua.degree or 0.0,
'contact_name': qua.contact_name or '',
'contact_phn': qua.contact_phn or '',
'contact_email': qua.contact_email or '',
'country_name': qua.country_name.read(['id', 'name'])[0] or {},
'qualification_degree': qua.qualification_degree or '',
'qualification_degree_lable': self.get_lable_selection(qua, 'qualification_degree',
qua.qualification_degree),
'qualification_specification_id': qua.qualification_specification_id.read(['id', 'name'])[
0] or {},
'qualification_id': qua.qualification_id.read(['id', 'name'])[0] or {},
})
res["qualification_employee"] = convert_dates_in_data(res["qualification_employee"])
# Build One2many lines for certification_employee
for c in req.certification_employee:
for cer in req.certification_employee:
res["certification_employee"].append({
"certification_name": c.certification_name,
"date_obtained": c.date_obtained,
"organization": c.organization,
'id': cer.id,
'cer_name': cer.car_name or '',
'certification_specification': cer.certification_specification_id.name or '',
'issue_org': cer.issue_org or '',
'certification_degree': cer.certification_degree or '',
'certification_degree_lable': self.get_lable_selection(cer, 'certification_degree',
cer.certification_degree),
'issue_date': str(cer.issue_date or ''),
'exp_date': str(cer.exp_date or ''),
'country_id': cer.country_name.read(['id', 'name'])[0] or {},
})
res["certification_employee"] = convert_dates_in_data(res["certification_employee"])
@ -389,15 +433,16 @@ class EmployeeOtherRequestController(http.Controller):
if not result['status']:
return http_helper.errcode(code=result['code'], message=result['message'])
user = validator.verify(token)
if not user:
return http_helper.response(
code=400,
message=_("Authentication failed or user is not allowed."),
success=False
)
employee = request.env['hr.employee'].sudo().search([('user_id', '=', user.id)], limit=1)
# 2) Validate/Parse Body
required_fields = ["date", "request_type", "employee_id", "company_id"]
required_fields = ["date", "request_type"]
missing = [f for f in required_fields if f not in body]
if missing:
return http_helper.response(
@ -413,8 +458,8 @@ class EmployeeOtherRequestController(http.Controller):
"from_hr": body.get("from_hr", False),
"date": body["date"],
"comment": body.get("comment") or "",
"request_type": body["request_type"],
"employee_id": body["employee_id"],
"request_type": body.get('request_type'),
"employee_id": employee.id,
"employee_dependant": self._prepare_employee_dependant_lines(body.get("employee_dependant", [])),
"qualification_employee": self._prepare_qualification_employee_lines(
body.get("qualification_employee", [])),
@ -422,9 +467,9 @@ class EmployeeOtherRequestController(http.Controller):
body.get("certification_employee", [])),
"create_insurance_request": body.get("create_insurance_request", False),
"print_type": body.get("print_type", ""),
"destination": body.get("destination") or False,
"parent_request_id": body.get("parent_request_id") or False,
"company_id": body["company_id"],
"destination": int(body.get("destination")) if body.get("destination") else False,
"parent_request_id": int(body.get("parent_request_id")) if body.get("parent_request_id") else False,
"company_id": 1,
}
# Create record
@ -470,11 +515,13 @@ class EmployeeOtherRequestController(http.Controller):
try:
# 2) Parse Query params
page = int(kw.get("page", 1))
limit = int(kw.get("limit", 10))
sort = kw.get("sort", "") # e.g. 'date' or '-state'
approvel = kw.get("approvel", 0)
filters_str = kw.get("filters", "") # e.g. 'state=approved'
page, offset, limit, prev = validator.get_page_pagination(page)
domain = []
if approvel:
domain.append(('state', '!=', 'draft'))
if filters_str:
# Very naive filter parser: "state=approved;request_type=insurance"
for part in filters_str.split(";"):
@ -487,7 +534,7 @@ class EmployeeOtherRequestController(http.Controller):
domain.append(('request_type', 'in', ['salary_define', 'salary_fixing']))
offset = (page - 1) * limit if page > 0 else 0
order = False
order = "create_date desc"
if sort:
if sort.startswith("-"):
order = sort[1:] + " desc"
@ -495,23 +542,32 @@ class EmployeeOtherRequestController(http.Controller):
order = sort + " asc"
RequestObj = request.env["employee.other.request"].with_user(user.id)
total_count = RequestObj.search_count(domain)
records = RequestObj.search(domain, offset=offset, limit=limit, order=order)
all_records = RequestObj.search_count(domain)
# Build minimal list
request_list = []
for r in records:
request_list.append(self._get_request_return_data(r))
request_list = convert_dates_in_data(request_list)
result_data = {
"page": page,
"limit": limit,
"total_records": total_count,
"requests": request_list,
next_page = validator.get_page_pagination_next(page, all_records)
next_url = "/rest_api/v2/employee_other_request?approvel=%s&page=%s" % (
approvel, next_page) if next_page else False
prev_url = "/rest_api/v2/employee_other_request?approvel=%s&page=%s" % (approvel, prev) if prev else False
data = {
'links': {
'prev': prev_url,
'next': next_url,
},
'count': limit,
'results': {
'employeeRequests': request_list,
}
}
return http_helper.response(
message=_("Requests retrieved successfully"),
data=result_data
data=data
)
except (UserError, AccessError, ValidationError) as e:
@ -611,7 +667,7 @@ class EmployeeOtherRequestController(http.Controller):
vals = {}
for field_name in updatable_fields:
if field_name in body:
vals[field_name] = body[field_name]
vals[field_name] = int(body[field_name]) if field_name in ["destination", "parent_request_id", "company_id"] else body[field_name]
# Handle One2many lines if needed
if "employee_dependant" in body:
@ -797,6 +853,8 @@ class EmployeeOtherRequestRelatedModelsController(http.Controller):
"prg_status": q.prg_status or "",
"comp_date": q.comp_date or "",
"qualification_degree": q.qualification_degree or "",
'qualification_degree_lable': self.get_lable_selection(q, 'qualification_degree',
q.qualification_degree),
"country_name": q.country_name.id if q.country_name else None,
"attachment": None,
})
@ -847,20 +905,23 @@ class EmployeeOtherRequestRelatedModelsController(http.Controller):
records = DependentModel.search(domain, offset=offset, limit=limit)
dep_list = []
for d in records:
for dep in records:
dep_list.append({
"id": d.id,
"name": d.name,
"birthday": d.birthday,
"age": d.age,
"gender": d.gender,
"relation": d.relation,
"nationality": d.nationality.name if d.nationality else "",
"passport_no": d.passport_no,
"passport_issue_date": d.passport_issue_date,
"passport_expire_date": d.passport_expire_date,
"remarks": d.remarks,
"has_ticket": d.has_ticket,
'name': dep.name or '',
'age': dep.age or '',
'birthday': str(dep.birthday or ''),
'gender': dep.gender or '',
'gender_lable': self.get_lable_selection(dep, 'gender', dep.gender),
'relation': dep.relation or '',
'relation_lable': self.get_lable_selection(dep, 'relation', dep.relation),
'nationality': dep.nationality.read(['id', 'name'])[0] or {},
'passport_no': dep.passport_no or '',
'passport_issue_date': str(dep.passport_issue_date or ''),
'passport_expire_date': str(dep.passport_expire_date or ''),
'degree_medical_insu': dep.degree_medical_insu or '',
'medical_insurance_num': dep.medical_insurance_num or '',
'identity_num': dep.identity_num or '',
'has_ticket': dep.has_ticket,
})
data = {
@ -936,4 +997,53 @@ class EmployeeOtherRequestRelatedModelsController(http.Controller):
except Exception as e:
_logger.exception("Error listing certifications")
return http_helper.response(code=400, message=str(e), success=False)
return http_helper.response(code=400, message=str(e), success=False)
class ReportControllerInherit(ReportController):
@http.route([
'/rest_api/v2/public_report/pdf/<reportname>/<docids>',
], type="http", auth="none", methods=["GET"])
def public_report_routes(self, reportname, docids=None, converter="pdf", **data):
if not converter:
converter = 'pdf'
http_method, body, headers, token = http_helper.parse_request()
# If needed, check token:
result = validator.verify_token(token)
if not result['status']:
return http_helper.errcode(code=result['code'], message=result['message'])
user = validator.verify(token)
if not user:
return http_helper.response(code=400, message=_(
"You are not allowed to perform this operation. please check with one of your team admins"),
success=False)
env = request.env(user=user.id)
report = env['ir.actions.report']._get_report_from_name(reportname) or env.ref(reportname)
context = dict(request.env.context)
if docids:
docids = [int(i) for i in docids.split(',')]
if data.get('options'):
data.update(json.loads(data.pop('options')))
if data.get('context'):
# Ignore 'lang' here, because the context in data is the one from the webclient *but* if
# the user explicitely wants to change the lang, this mechanism overwrites it.
data['context'] = json.loads(data['context'])
if data['context'].get('lang') and not data.get('force_context_lang'):
del data['context']['lang']
context.update(data['context'])
if converter == 'html':
html = report.with_context(context)._render_qweb_html(docids, data=data)[0]
return request.make_response(html)
elif converter == 'pdf':
pdf = report.with_context(context)._render_qweb_pdf(docids, data=data)[0]
pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
return request.make_response(pdf, headers=pdfhttpheaders)
elif converter == 'text':
text = report.with_context(context)._render_qweb_text(docids, data=data)[0]
texthttpheaders = [('Content-Type', 'text/plain'), ('Content-Length', len(text))]
return request.make_response(text, headers=texthttpheaders)
else:
raise exceptions.HTTPException(description='Converter %s not implemented.' % converter)