fix 00100

This commit is contained in:
odex 2024-07-21 12:37:21 +03:00
parent 3e05dc485f
commit 8c5804ba22
7 changed files with 697 additions and 525 deletions

View File

@ -4,7 +4,7 @@ import calendar
from odoo import http, tools
from odoo.http import request, Response
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.exceptions import UserError
from odoo.exceptions import UserError ,AccessError, ValidationError
from datetime import datetime ,timedelta
import base64
from ...validator import validator
@ -49,7 +49,12 @@ class AttendanceController(http.Controller):
'loc_ch_intv': z.loc_ch_intv, 'loc_ch_dist':z.loc_ch_dist, 'srv_ch_tmout':z.srv_ch_tmout}
li.append(value)
return http_helper.response(message="Data Found", data={'general_zoons':general_zoons, 'specific_zoons':li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -90,7 +95,12 @@ class AttendanceController(http.Controller):
data = self.get_check_records(out_rec[0])
li.append(data)
return http_helper.response(message="Data Found", data={'checks': li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -124,31 +134,36 @@ class AttendanceController(http.Controller):
"You are not allowed to perform this operation. please check with one of your team admins"),
success=False)
try:
data = {}
records = employee.resource_calendar_id
shifts = {}
if records:
data.update({
'shift_start_time': '{0:02.0f}:{1:02.0f}'.format(*divmod(records.full_min_sign_in * 60, 60))if records.is_full_day else
['{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_one_min_sign_in * 60, 60)),
'{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_two_min_sign_in * 60, 60)), ],
'shift_end_time': '{0:02.0f}:{1:02.0f}'.format(*divmod(records.full_min_sign_out * 60, 60)) if records.is_full_day else
['{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_one_min_sign_out * 60, 60)),
'{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_two_min_sign_out * 60, 60)), ],
})
with request.env.cr.savepoint():
data = {}
records = employee.resource_calendar_id
shifts = {}
if records:
data.update({
'shift_start_time': '{0:02.0f}:{1:02.0f}'.format(*divmod(records.full_min_sign_in * 60, 60))if records.is_full_day else
['{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_one_min_sign_in * 60, 60)),
'{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_two_min_sign_in * 60, 60)), ],
'shift_end_time': '{0:02.0f}:{1:02.0f}'.format(*divmod(records.full_min_sign_out * 60, 60)) if records.is_full_day else
['{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_one_min_sign_out * 60, 60)),
'{0:02.0f}:{1:02.0f}'.format(*divmod(records.shift_two_min_sign_out * 60, 60)), ],
})
attendance = http.request.env['attendance.attendance'].sudo().search([('employee_id', '=', employee.id), ], order='name desc',
limit=1)
if attendance:
date = attendance.name.time()
data.update({'id': attendance.id , 'action': attendance.action,
'attendance_status': attendance.action, 'time': str(date), 'zone': attendance.zone,
'longitude': attendance.longitude, 'latitude': attendance.latitude})
_logger.error(data)
return http_helper.response(message="Refresh Successfully", data=data)
else:
data.update({'attendance_status':'sign_out'})
return http_helper.response(message="Refresh Successfully", data=data)
attendance = http.request.env['attendance.attendance'].sudo().search([('employee_id', '=', employee.id), ], order='name desc',
limit=1)
if attendance:
date = attendance.name.time()
data.update({'id': attendance.id , 'action': attendance.action,
'attendance_status': attendance.action, 'time': str(date), 'zone': attendance.zone,
'longitude': attendance.longitude, 'latitude': attendance.latitude})
_logger.error(data)
return http_helper.response(message="Refresh Successfully", data=data)
else:
data.update({'attendance_status':'sign_out'})
return http_helper.response(message="Refresh Successfully", data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -177,48 +192,53 @@ class AttendanceController(http.Controller):
if employee.device_id != body.get('device_id'):
return http_helper.errcode(code=403, message=_("Device id not matching with already exist in system please contact system admin"))
try:
zones = http.request.env['attendance.zone'].search([('employee_ids', 'in', employee.id)])
if not zones:
return http_helper.errcode(code=403, message=_("Employee not in any Zone,Contact Admin "))
zone = http.request.env['attendance.zone'].search([('id', '=', body.get('id'))]) if body.get(
'id') else False
rec = http.request.env['attendance.attendance'].sudo().search([('employee_id', '=', employee.id), ],
order='name desc',
limit=1)
system_checkout = json.loads(body.get('system_checkout')) if 'system_checkout' in body else False
if not rec or rec and rec.action != body.get('action'):
attendance = http.request.env['attendance.attendance'].create({
'employee_id':employee.id,
'action':body.get('action'),
'action_type':"system_checkout" if body.get('action') == 'sign_out' and system_checkout == True else 'application',
'name': fields.datetime.now(),
# 'device_id':body.get('device_id'),
'zone':zone.zone if zone else "%s,%s" % (body.get('longitude'), body.get('latitude')),
'longitude': body.get('longitude'),
'latitude':body.get('latitude'),
})
if attendance:
if body.get('action') == 'sign_out' and system_checkout == True:
msg = (_("System Force Sign out Due to Change Location Permission "))
subject = (_("System Force Sign out"))
self.send_msg(employee, msg, subject)
with request.env.cr.savepoint():
zones = http.request.env['attendance.zone'].search([('employee_ids', 'in', employee.id)])
if not zones:
return http_helper.errcode(code=403, message=_("Employee not in any Zone,Contact Admin "))
zone = http.request.env['attendance.zone'].search([('id', '=', body.get('id'))]) if body.get(
'id') else False
rec = http.request.env['attendance.attendance'].sudo().search([('employee_id', '=', employee.id), ],
order='name desc',
limit=1)
system_checkout = json.loads(body.get('system_checkout')) if 'system_checkout' in body else False
if not rec or rec and rec.action != body.get('action'):
attendance = http.request.env['attendance.attendance'].create({
'employee_id':employee.id,
'action':body.get('action'),
'action_type':"system_checkout" if body.get('action') == 'sign_out' and system_checkout == True else 'application',
'name': fields.datetime.now(),
# 'device_id':body.get('device_id'),
'zone':zone.zone if zone else "%s,%s" % (body.get('longitude'), body.get('latitude')),
'longitude': body.get('longitude'),
'latitude':body.get('latitude'),
})
if attendance:
if body.get('action') == 'sign_out' and system_checkout == True:
msg = (_("System Force Sign out Due to Change Location Permission "))
subject = (_("System Force Sign out"))
self.send_msg(employee, msg, subject)
date = attendance.name.time()
data = {
"id": attendance.id,
"action": attendance.action,
"attendance_status": attendance.action,
"time": str(date),
"zone": attendance.zone,
"longitude": attendance.longitude,
"latitude": attendance.latitude,
"range": zone.allowed_range if zone else False,
}
msg = (_("Check Out successfully")) if body.get('action') == 'sign_out' else (_("Check in successfully"))
else:
msg = (_("Check Fail Due To Duplication"))
data = {}
return http_helper.response(msg, data={'checks': [data]})
date = attendance.name.time()
data = {
"id": attendance.id,
"action": attendance.action,
"attendance_status": attendance.action,
"time": str(date),
"zone": attendance.zone,
"longitude": attendance.longitude,
"latitude": attendance.latitude,
"range": zone.allowed_range if zone else False,
}
msg = (_("Check Out successfully")) if body.get('action') == 'sign_out' else (_("Check in successfully"))
else:
msg = (_("Check Fail Due To Duplication"))
data = {}
return http_helper.response(msg, data={'checks': [data]})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -299,11 +319,15 @@ class AttendanceController(http.Controller):
}
li.append(attendance)
return http_helper.response(message="Data Found", data={'attendaces': li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
# Get shift
@http.route(['/rest_api/v2/shifts'], type='http', auth='none', csrf=False, methods=['GET'])
def get_shift(self, **kw):
@ -348,72 +372,78 @@ class AttendanceController(http.Controller):
"You are not allowed to perform this operation. please check with one of your team admins"),
success=False)
try:
if json.loads(body['in_zone']):
records = employee.attendance_log_ids.sudo().filtered(lambda r: str(r.date) == str(datetime.today().date()) and r.old == False)
for r in records:
r.old = True
employee.message_sent = False
return http_helper.response(message="Old Record Done", data={'status': True})
with request.env.cr.savepoint():
if json.loads(body['in_zone']):
records = employee.attendance_log_ids.sudo().filtered(lambda r: str(r.date) == str(datetime.today().date()) and r.old == False)
for r in records:
r.old = True
employee.message_sent = False
return http_helper.response(message="Old Record Done", data={'status': True})
else:
attendance = http.request.env['attendance.attendance'].sudo().search(
[('employee_id', '=', employee.id), ], order='name desc',
limit=1)
if attendance.action == 'sign_in':
records = employee.attendance_log_ids.sudo().filtered(lambda r: r.old == False and str(r.date) == str(datetime.today().date()))
if records:
n = len(records)
last = records[n - 1]
last = fields.Datetime.from_string(last.time)
now = datetime.now()
if now > last:
diff = now - last
diff = diff.seconds / 60
zone = http.request.env['attendance.zone'].search([('employee_ids', 'in', employee.id)],limit=1)
zone_general = http.request.env['attendance.zone'].search([('general', '=', True)],limit=1)
auto = zone.auto_checkout or zone_general.auto_checkout or request.env.user.company_id.auto_checkout or 20
if diff >= auto:
attendance = http.request.env['attendance.attendance'].create({
'employee_id': employee.id,
'action': 'sign_out',
'action_type': 'auto',
'name': fields.datetime.now(),
'zone': "%s,%s" % (body.get('longitude'), body.get('latitude')),
'longitude': body.get('longitude'),
'latitude': body.get('latitude'),
})
msg = _("Auto Checkout successfully")
subject = _("Auto Checkout")
self.send_msg(employee, msg, subject)
records = employee.attendance_log_ids.sudo().filtered(
lambda r: str(r.date) == str(datetime.today().date()) and r.old == False)
for r in records:
r.old = True
employee.message_sent = False
return http_helper.response(message="Auto Checkout successfully", data={'status': True})
else:
if not employee.message_sent:
msg = _("You are out of attendance zone you will be auto sign out")
subject = _("Auto Sign out")
self.send_msg(employee, msg, subject)
employee.message_sent = True
return http_helper.response(message="Auto Checkout Fail and Send", data={'status': False})
else:
self.create_log(employee, body.get('longitude'), body.get('latitude'))
if not employee.message_sent:
msg = _("You are out of attendance zone you will be auto sign out")
subject = _("Auto Sign out")
self.send_msg(employee, msg, subject)
employee.message_sent = True
return http_helper.response(message="Auto Checkout Fail and Send", data={'status': False})
else:
return http_helper.response(message="You are not Checked in yet", data={'status': True})
attendance = http.request.env['attendance.attendance'].sudo().search(
[('employee_id', '=', employee.id), ], order='name desc',
limit=1)
if attendance.action == 'sign_in':
records = employee.attendance_log_ids.sudo().filtered(lambda r: r.old == False and str(r.date) == str(datetime.today().date()))
if records:
n = len(records)
last = records[n - 1]
last = fields.Datetime.from_string(last.time)
now = datetime.now()
if now > last:
diff = now - last
diff = diff.seconds / 60
zone = http.request.env['attendance.zone'].search([('employee_ids', 'in', employee.id)],limit=1)
zone_general = http.request.env['attendance.zone'].search([('general', '=', True)],limit=1)
auto = zone.auto_checkout or zone_general.auto_checkout or request.env.user.company_id.auto_checkout or 20
if diff >= auto:
attendance = http.request.env['attendance.attendance'].create({
'employee_id': employee.id,
'action': 'sign_out',
'action_type': 'auto',
'name': fields.datetime.now(),
'zone': "%s,%s" % (body.get('longitude'), body.get('latitude')),
'longitude': body.get('longitude'),
'latitude': body.get('latitude'),
})
msg = _("Auto Checkout successfully")
subject = _("Auto Checkout")
self.send_msg(employee, msg, subject)
records = employee.attendance_log_ids.sudo().filtered(
lambda r: str(r.date) == str(datetime.today().date()) and r.old == False)
for r in records:
r.old = True
employee.message_sent = False
return http_helper.response(message="Auto Checkout successfully", data={'status': True})
else:
if not employee.message_sent:
msg = _("You are out of attendance zone you will be auto sign out")
subject = _("Auto Sign out")
self.send_msg(employee, msg, subject)
employee.message_sent = True
return http_helper.response(message="Auto Checkout Fail and Send", data={'status': False})
else:
self.create_log(employee, body.get('longitude'), body.get('latitude'))
if not employee.message_sent:
msg = _("You are out of attendance zone you will be auto sign out")
subject = _("Auto Sign out")
self.send_msg(employee, msg, subject)
employee.message_sent = True
return http_helper.response(message="Auto Checkout Fail and Send", data={'status': False})
else:
return http_helper.response(message="You are not Checked in yet", data={'status': True})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
def send_msg(self, emp, msg, subject):
if emp.user_id.partner_id:
partner_id = emp.user_id.partner_id
@ -425,17 +455,20 @@ class AttendanceController(http.Controller):
emp.user_push_notification(data)
def create_log(self, employee, longitude, latitude):
attendance = http.request.env['attendance.log'].create({
'employee_id': employee.id,
'time': fields.datetime.now(),
'date': datetime.today().date(),
'longitude': longitude,
'latitude':latitude,
})
with request.env.cr.savepoint():
attendance = http.request.env['attendance.log'].create({
'employee_id': employee.id,
'time': fields.datetime.now(),
'date': datetime.today().date(),
'longitude': longitude,
'latitude':latitude,
})
def convert_float_2time(self,time):
td = timedelta(hours=time)
dt = datetime.min + td
time = "{:%H:%M}".format(dt)
return time
def get_translation_field(self,rec,field):
return request.env['ir.translation'].get_field_string(rec._name)[field]

View File

@ -5,7 +5,7 @@ from odoo import http, tools
from datetime import datetime
from odoo.http import request, Response
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.exceptions import UserError
from odoo.exceptions import UserError ,AccessError, ValidationError
import base64
from ...validator import validator
from ...http_helper import http_helper
@ -161,7 +161,12 @@ class LeaveController(http.Controller):
# 'groups': ['group_hr_holidays_user', 'group_division_manager']
}}
return http_helper.response(message="Data Found", data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -186,7 +191,12 @@ class LeaveController(http.Controller):
return http_helper.response(message=_("GET Leave Successfully"), data={'leave': data})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -209,43 +219,48 @@ class LeaveController(http.Controller):
return http_helper.response(code=400, message=_(
"You Have issue in your employee profile. please check with one of your team admins"), success=False)
try:
vals = {'employee_id': employee.id, 'date_from': body['start_date'], 'date_to': body['end_date']
, 'name': body['description'] if body.get('description') else '',
'holiday_status_id': int(body['type_id']),
'delegate_acc': body['delegated_permission'],
# 'replace_by': int(body['replacement_id']) if body['replacement_id'] else False
}
if 'ticket' in body and body['ticket']:
vals.update({'issuing_clearance_form': body['issuing_clearance_form'],
'issuing_deliver_custdy': body[
'issuing_deliver_custdy'] if 'issuing_deliver_custdy' in body else False,
'permission_request_for': body[
'permission_request_for'] if 'permission_request_for' in body else False,
'issuing_exit_return': body[
'exit_return_duration'] if 'exit_return_duration' in body else False,
'ticket_cash_request_type': body[
'ticket_cash_request_type'] if 'ticket_cash_request_type' in body else False,
'ticket_cash_request_for': body[
'ticket_cash_request_for'] if 'ticket_cash_request_for' in body else False,
'issuing_ticket': body['issuing_ticket'] if 'issuing_ticket' in body else False, })
with request.env.cr.savepoint():
vals = {'employee_id': employee.id, 'date_from': body['start_date'], 'date_to': body['end_date']
, 'name': body['description'] if body.get('description') else '',
'holiday_status_id': int(body['type_id']),
'delegate_acc': body['delegated_permission'],
# 'replace_by': int(body['replacement_id']) if body['replacement_id'] else False
}
if 'ticket' in body and body['ticket']:
vals.update({'issuing_clearance_form': body['issuing_clearance_form'],
'issuing_deliver_custdy': body[
'issuing_deliver_custdy'] if 'issuing_deliver_custdy' in body else False,
'permission_request_for': body[
'permission_request_for'] if 'permission_request_for' in body else False,
'issuing_exit_return': body[
'exit_return_duration'] if 'exit_return_duration' in body else False,
'ticket_cash_request_type': body[
'ticket_cash_request_type'] if 'ticket_cash_request_type' in body else False,
'ticket_cash_request_for': body[
'ticket_cash_request_for'] if 'ticket_cash_request_for' in body else False,
'issuing_ticket': body['issuing_ticket'] if 'issuing_ticket' in body else False, })
holidays = http.request.env['hr.holidays'].sudo().create(vals)
if 'attachment' in body and body['attachment']:
attach = http.request.env['ir.attachment'].sudo().create({
'name': body['attachment'].filename,
'datas': base64.b64encode(body['attachment'].read()),
'store_fname': body['attachment'].filename,
'res_model': 'hr.holidays',
'res_id': holidays.id,
'att_holiday_ids': holidays.id,
})
holidays.attach_ids = [(4,attach.id)]
if holidays:
# holidays.confirm()
holidays.number_of_days_temp = holidays._get_number_of_days(body['start_date'], body['end_date'],
employee)
data = self.get_return_data(holidays)
return http_helper.response(message=_("Leave Created Successfully"), data={'leaves': [data]})
holidays = http.request.env['hr.holidays'].sudo().create(vals)
if 'attachment' in body and body['attachment']:
attach = http.request.env['ir.attachment'].sudo().create({
'name': body['attachment'].filename,
'datas': base64.b64encode(body['attachment'].read()),
'store_fname': body['attachment'].filename,
'res_model': 'hr.holidays',
'res_id': holidays.id,
'att_holiday_ids': holidays.id,
})
holidays.attach_ids = [(4,attach.id)]
if holidays:
# holidays.confirm()
holidays.number_of_days_temp = holidays._get_number_of_days(body['start_date'], body['end_date'],
employee)
data = self.get_return_data(holidays)
return http_helper.response(message=_("Leave Created Successfully"), data={'leaves': [data]})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -276,52 +291,57 @@ class LeaveController(http.Controller):
"You Have issue in your employee profile. please check with one of your team admins"),
success=False)
try:
holidays = http.request.env['hr.holidays'].search([('id', '=', int(id))])
if holidays:
days = holidays._get_number_of_days(body['start_date'], body['end_date'], employee)
vals = {
'date_from': body['start_date'], 'date_to': body['end_date'],
'name': body['description'] if body.get('description') else '',
'holiday_status_id': int(body['type_id']),
'number_of_days_temp': days, 'delegate_acc': json.loads(body['delegated_permission']),
}
if approvel and 'replacement_id' in body:
vals.update({
'replace_by': int(body['replacement_id'])
})
if 'ticket' in body and body['ticket']:
vals.update({'issuing_clearance_form': body['issuing_clearance_form'],
'issuing_deliver_custdy': body[
'issuing_deliver_custdy'] if 'issuing_deliver_custdy' in body else False,
'permission_request_for': body[
'permission_request_for'] if 'permission_request_for' in body else False,
'exit_return_duration': body[
'exit_return_duration'] if 'exit_return_duration' in body else False,
'ticket_cash_request_type': body[
'ticket_cash_request_type'] if 'ticket_cash_request_type' in body else False,
'ticket_cash_request_for': body[
'ticket_cash_request_for'] if 'ticket_cash_request_for' in body else False,
'issuing_ticket': body['issuing_ticket'] if 'issuing_ticket' in body else False, })
holidays.write(vals)
if 'attachment' in body and body['attachment']:
attach = http.request.env['ir.attachment'].sudo().create({
'name': body['attachment'].filename,
'datas': base64.b64encode(body['attachment'].read()),
'store_fname': body['attachment'].filename,
'res_model': 'hr.holidays',
'res_id': holidays.id,
'att_holiday_ids': holidays.id,
})
holidays.attach_ids = [(4,attach.id)]
data = self.get_return_data(holidays, approvel)
return http_helper.response(message=_("Leave Updated Successfully"), data={'leaves': [data]})
else:
return http_helper.response(code=400,
message=_(
"You Have issue in your employee profile. please check with one of your team admins"),
success=False)
with request.env.cr.savepoint():
holidays = http.request.env['hr.holidays'].search([('id', '=', int(id))])
if holidays:
days = holidays._get_number_of_days(body['start_date'], body['end_date'], employee)
vals = {
'date_from': body['start_date'], 'date_to': body['end_date'],
'name': body['description'] if body.get('description') else '',
'holiday_status_id': int(body['type_id']),
'number_of_days_temp': days, 'delegate_acc': json.loads(body['delegated_permission']),
}
if approvel and 'replacement_id' in body:
vals.update({
'replace_by': int(body['replacement_id'])
})
if 'ticket' in body and body['ticket']:
vals.update({'issuing_clearance_form': body['issuing_clearance_form'],
'issuing_deliver_custdy': body[
'issuing_deliver_custdy'] if 'issuing_deliver_custdy' in body else False,
'permission_request_for': body[
'permission_request_for'] if 'permission_request_for' in body else False,
'exit_return_duration': body[
'exit_return_duration'] if 'exit_return_duration' in body else False,
'ticket_cash_request_type': body[
'ticket_cash_request_type'] if 'ticket_cash_request_type' in body else False,
'ticket_cash_request_for': body[
'ticket_cash_request_for'] if 'ticket_cash_request_for' in body else False,
'issuing_ticket': body['issuing_ticket'] if 'issuing_ticket' in body else False, })
holidays.write(vals)
if 'attachment' in body and body['attachment']:
attach = http.request.env['ir.attachment'].sudo().create({
'name': body['attachment'].filename,
'datas': base64.b64encode(body['attachment'].read()),
'store_fname': body['attachment'].filename,
'res_model': 'hr.holidays',
'res_id': holidays.id,
'att_holiday_ids': holidays.id,
})
holidays.attach_ids = [(4,attach.id)]
data = self.get_return_data(holidays, approvel)
return http_helper.response(message=_("Leave Updated Successfully"), data={'leaves': [data]})
else:
return http_helper.response(code=400,
message=_(
"You Have issue in your employee profile. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -354,7 +374,12 @@ class LeaveController(http.Controller):
message=_(
"You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -387,6 +412,10 @@ class LeaveController(http.Controller):
li.append(value)
data = {'system_leaves': li, }
return http_helper.response(message="Data Found", data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))

View File

@ -2,7 +2,7 @@
import werkzeug
from odoo import http,tools
from odoo.http import request, Response
from odoo.exceptions import UserError
from odoo.exceptions import UserError , AccessError, ValidationError
import base64
from ...validator import validator
from ...http_helper import http_helper
@ -78,7 +78,12 @@ class LoanController(http.Controller):
'results':{'loan_types': types, 'employee_loans': li }}
return http_helper.response(message="Data Found",
data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -114,41 +119,46 @@ class LoanController(http.Controller):
if not body.get('is_old'):
return http_helper.response(code=400,message=_("Enter is old"), success=False)
try:
loans = http.request.env['hr.loan.salary.advance'].sudo().create({
'employee_id':employee.id,
'request_type':int(body['request_type']),
'date':body['date'],
'emp_expect_amount':body['expect_amount'],
'finance_propos_amount':body['expect_amount'],
'gm_propos_amount':body['expect_amount'],
'is_old':body['is_old'],
'months':body['months'],
})
if loans:
value = {
"id": loans.id,
"code": loans.code,
"expect_amount": loans.emp_expect_amount,
"date": str(loans.date),
"state_name": loans.state,
"installment_amount": loans.installment_amount,
"state": validator.get_state_name(loans, loans.state),
"months": loans.months,
"request_type_id": loans.request_type.id,
"request_type_name": loans.request_type.name,
}
lines = []
if loans.deduction_lines:
for l in loans.deduction_lines:
vals = {
'installment_date': str(l.installment_date),
'installment_amount': l.installment_amount,
'paid': l.paid
}
lines.append(vals)
value['lines'] = lines
return http_helper.response(message=_("Record create Successfully"),
data={'employee_loans': [value], })
with request.env.cr.savepoint():
loans = http.request.env['hr.loan.salary.advance'].sudo().create({
'employee_id':employee.id,
'request_type':int(body['request_type']),
'date':body['date'],
'emp_expect_amount':body['expect_amount'],
'finance_propos_amount':body['expect_amount'],
'gm_propos_amount':body['expect_amount'],
'is_old':body['is_old'],
'months':body['months'],
})
if loans:
value = {
"id": loans.id,
"code": loans.code,
"expect_amount": loans.emp_expect_amount,
"date": str(loans.date),
"state_name": loans.state,
"installment_amount": loans.installment_amount,
"state": validator.get_state_name(loans, loans.state),
"months": loans.months,
"request_type_id": loans.request_type.id,
"request_type_name": loans.request_type.name,
}
lines = []
if loans.deduction_lines:
for l in loans.deduction_lines:
vals = {
'installment_date': str(l.installment_date),
'installment_amount': l.installment_amount,
'paid': l.paid
}
lines.append(vals)
value['lines'] = lines
return http_helper.response(message=_("Record create Successfully"),
data={'employee_loans': [value], })
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -184,33 +194,39 @@ class LoanController(http.Controller):
if not body.get('is_old'):
return http_helper.response(code=400, message=_("Enter is old"), success=False)
try:
loans = http.request.env['hr.loan.salary.advance'].search([('id','=',id)])
if loans:
loans.write({
'employee_id':loans.employee_id.id,
'request_type':int(body['request_type']),
'date':body['date'],
'emp_expect_amount':body['expect_amount'],
'is_old':body['is_old'],
'months':body['months'],
})
# loans.create_loan()
value = {'id': loans.id, 'code': loans.code, 'expect_amount': loans.emp_expect_amount, 'date': str(loans.date),
'installment_amount': loans.installment_amount, 'state_name':loans.state,'state': validator.get_state_name(loans,loans.state), 'months': loans.months,
'request_type_id': loans.request_type.id, 'request_type_name': loans.request_type.name}
lines = []
if loans.deduction_lines:
for l in loans.deduction_lines:
vals = {
'installment_date': str(l.installment_date),
'installment_amount': l.installment_amount,
'paid': l.paid
}
lines.append(vals)
value['lines'] = lines
return http_helper.response(message=_("Loan Updated successfully"),
data={'employee_loans': [value], })
with request.env.cr.savepoint():
loans = http.request.env['hr.loan.salary.advance'].search([('id','=',id)])
if loans:
loans.write({
'employee_id':loans.employee_id.id,
'request_type':int(body['request_type']),
'date':body['date'],
'emp_expect_amount':body['expect_amount'],
'is_old':body['is_old'],
'months':body['months'],
})
# loans.create_loan()
value = {'id': loans.id, 'code': loans.code, 'expect_amount': loans.emp_expect_amount, 'date': str(loans.date),
'installment_amount': loans.installment_amount, 'state_name':loans.state,'state': validator.get_state_name(loans,loans.state), 'months': loans.months,
'request_type_id': loans.request_type.id, 'request_type_name': loans.request_type.name}
lines = []
if loans.deduction_lines:
for l in loans.deduction_lines:
vals = {
'installment_date': str(l.installment_date),
'installment_amount': l.installment_amount,
'paid': l.paid
}
lines.append(vals)
value['lines'] = lines
return http_helper.response(message=_("Loan Updated successfully"),
data={'employee_loans': [value], })
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -240,7 +256,12 @@ class LoanController(http.Controller):
return http_helper.response(code=400,
message=_("You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -276,7 +297,12 @@ class LoanController(http.Controller):
lines.append(vals)
value['lines'] = lines
return http_helper.response(message=_("Get Loan successfully"),data={'loan': value})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)

View File

@ -45,10 +45,12 @@ class OverTimeController(http.Controller):
else:
return http_helper.response(message=_("Data Not Found"),
data=data)
except (UserError, AccessError, ValidationError, Warning) as e:
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -140,10 +142,12 @@ class OverTimeController(http.Controller):
return http_helper.response(message="Data Found",
data=data)
except (UserError, AccessError, ValidationError, Warning) as e:
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -153,12 +157,10 @@ class OverTimeController(http.Controller):
@http.route(['/rest_api/v2/overtimes'], type='http', auth='none', csrf=False, methods=['POST'])
def create_overtime(self, **kw):
s = None
try:
data = kw.get('lines', {})
if data:
data = json.loads(data)
# data = json.loads(data["lines"])
http_method, body, headers, token = http_helper.parse_request()
result = validator.verify_token(token)
if not result['status']:
@ -193,71 +195,70 @@ class OverTimeController(http.Controller):
success=False)
if not data:
return http_helper.response(code=400, message=_("Enter Lines for Overtime"), success=False)
s = http.request.env["employee.overtime.request"].sudo().create(
{
"transfer_type": body["transfer_type"],
"request_date": body["request_date"],
"date_from": body["date_from"],
"date_to": body["date_to"],
"reason": body["reason"],
"overtime_plase": body["overtime_plase"],
"line_ids_over_time": [(0,0,
{
"employee_id": employee.id,
"over_time_workdays_hours": l[ "over_time_workdays_hours"],
"over_time_vacation_hours": l["over_time_vacation_hours"],
},
)
for l in data
],
}
)
s.line_ids_over_time.get_max_remain_hours()
if s:
value = {
"id": s.id,
"transfer_type": s.transfer_type,
"request_date": str(s.request_date),
"date_from": str(s.date_from),
"date_to": str(s.date_to),
"state_name": s.state,
"state": validator.get_state_name(s, s.state),
"reason": s.reason,
"overtime_plase":s.overtime_plase,# http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),#
# "benefits_discounts_list":s.benefits_discounts.read(['name']),
'account': s.sudo().account_id.id if s.sudo().account_id else False,
'account_id': s.sudo().account_id.name if s.sudo().account_id else False,
'journal': s.sudo().journal_id.name if s.sudo().journal_id else False,
'journal_id': s.sudo().journal_id.id if s.sudo().journal_id else False,
'benefits_discounts': s.sudo().benefits_discounts.name if s.sudo().benefits_discounts else False,
'benefits_discounts_id': s.sudo().benefits_discounts.id if s.sudo().benefits_discounts else False,
}
li = []
if s.line_ids_over_time:
for r in s.line_ids_over_time:
rec = {
'id': r.id,
'over_time_workdays_hours': r.over_time_workdays_hours,
'over_time_vacation_hours': r.over_time_vacation_hours,
'price_hour': r.price_hour,
'daily_hourly_rate': r.daily_hourly_rate,
'holiday_hourly_rate': r.holiday_hourly_rate,
with request.env.cr.savepoint():
s = http.request.env["employee.overtime.request"].sudo().create(
{
"transfer_type": body["transfer_type"],
"request_date": body["request_date"],
"date_from": body["date_from"],
"date_to": body["date_to"],
"reason": body["reason"],
"overtime_plase": body["overtime_plase"],
"line_ids_over_time": [(0,0,
{
"employee_id": employee.id,
"over_time_workdays_hours": l[ "over_time_workdays_hours"],
"over_time_vacation_hours": l["over_time_vacation_hours"],
},
)
for l in data
],
}
li.append(rec)
value['lines'] = li
)
s.line_ids_over_time.get_max_remain_hours()
if s:
value = {
"id": s.id,
"transfer_type": s.transfer_type,
"request_date": str(s.request_date),
"date_from": str(s.date_from),
"date_to": str(s.date_to),
"state_name": s.state,
"state": validator.get_state_name(s, s.state),
"reason": s.reason,
"overtime_plase":s.overtime_plase,# http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),#
# "benefits_discounts_list":s.benefits_discounts.read(['name']),
'account': s.sudo().account_id.id if s.sudo().account_id else False,
'account_id': s.sudo().account_id.name if s.sudo().account_id else False,
'journal': s.sudo().journal_id.name if s.sudo().journal_id else False,
'journal_id': s.sudo().journal_id.id if s.sudo().journal_id else False,
'benefits_discounts': s.sudo().benefits_discounts.name if s.sudo().benefits_discounts else False,
'benefits_discounts_id': s.sudo().benefits_discounts.id if s.sudo().benefits_discounts else False,
}
li = []
if s.line_ids_over_time:
for r in s.line_ids_over_time:
rec = {
'id': r.id,
'over_time_workdays_hours': r.over_time_workdays_hours,
'over_time_vacation_hours': r.over_time_vacation_hours,
'price_hour': r.price_hour,
'daily_hourly_rate': r.daily_hourly_rate,
'holiday_hourly_rate': r.holiday_hourly_rate,
}
li.append(rec)
value['lines'] = li
return http_helper.response(message=_("Overtime created successfully"),
data={'overtimes': [value],})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
if s:
s.unlink()
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
if s:
s.unlink()
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -304,85 +305,86 @@ class OverTimeController(http.Controller):
# if not data:
# return http_helper.response(code=400, message=_("Enter Lines for Overtime"), success=False)
try:
with request.env.cr.savepoint():
s = http.request.env['employee.overtime.request'].search([('id', '=', id)])
if s:
vals = {
"transfer_type": body["transfer_type"],
"request_date": body["request_date"],
"date_from": body["date_from"],
"date_to": body["date_to"],
"reason": body["reason"],
"overtime_plase":s.overtime_plase,# http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),#
}
# if approvel:
s.write(vals)
s.line_ids_over_time.get_max_remain_hours()
if s.transfer_type == 'accounting' and body.get("account") and body.get("journal"):
vals.update({
'account_id':int( body['account']),
'journal_id': int(body['journal']),
})
s.benefits_discounts = False
elif s.transfer_type == 'payroll' and body.get("rule") :
vals.update({
'benefits_discounts':int( body['rule']),
})
s.account_id = False
s.journal_id = False
s.write(vals)
if s.state == 'financial_manager':
s.onchange_transfer_type()
# s.get_account_ids()
if data:
for t in data:
self.get_overtime_line(s.employee_id, s, t)
value = {
"id": s.id,
"transfer_type": s.transfer_type,
"request_date": str(s.request_date),
"date_from": str(s.date_from),
"overtime_plase":s.overtime_plase, #http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),# s.overtime_plase,
"date_to": str(s.date_to),
"state_name": s.state,
"state": validator.get_state_name(s, s.state),
"reason": s.reason,
# "benefits_discounts":s.benefits_discounts.read(['name']),
}
# if approvel:
value.update({
'account': s.sudo().account_id.id if s.sudo().account_id else False,
'account_id': s.sudo().account_id.name if s.sudo().account_id else False,
'journal': s.sudo().journal_id.name if s.sudo().journal_id else False,
'journal_id': s.sudo().journal_id.id if s.sudo().journal_id else False,
'benefits_discounts': s.sudo().benefits_discounts.name if s.sudo().benefits_discounts else False,
'benefits_discounts_id': s.sudo().benefits_discounts.id if s.sudo().benefits_discounts else False,
s = http.request.env['employee.overtime.request'].search([('id', '=', id)])
if s:
vals = {
"transfer_type": body["transfer_type"],
"request_date": body["request_date"],
"date_from": body["date_from"],
"date_to": body["date_to"],
"reason": body["reason"],
"overtime_plase":s.overtime_plase,# http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),#
}
# if approvel:
s.write(vals)
s.line_ids_over_time.get_max_remain_hours()
if s.transfer_type == 'accounting' and body.get("account") and body.get("journal"):
vals.update({
'account_id':int( body['account']),
'journal_id': int(body['journal']),
})
s.benefits_discounts = False
elif s.transfer_type == 'payroll' and body.get("rule") :
vals.update({
'benefits_discounts':int( body['rule']),
})
s.account_id = False
s.journal_id = False
s.write(vals)
if s.state == 'financial_manager':
# s.get_account_ids()
s.onchange_transfer_type()
# s.get_account_ids()
if data:
for t in data:
self.get_overtime_line(s.employee_id, s, t)
value = {
"id": s.id,
"transfer_type": s.transfer_type,
"request_date": str(s.request_date),
"date_from": str(s.date_from),
"overtime_plase":s.overtime_plase, #http_helper.get_lable_selection(s,'overtime_plase',s.overtime_plase),# s.overtime_plase,
"date_to": str(s.date_to),
"state_name": s.state,
"state": validator.get_state_name(s, s.state),
"reason": s.reason,
# "benefits_discounts":s.benefits_discounts.read(['name']),
}
# if approvel:
value.update({
'account': s.sudo().account_id.id if s.sudo().account_id else False,
'account_id': s.sudo().account_id.name if s.sudo().account_id else False,
'journal': s.sudo().journal_id.name if s.sudo().journal_id else False,
'journal_id': s.sudo().journal_id.id if s.sudo().journal_id else False,
'benefits_discounts': s.sudo().benefits_discounts.name if s.sudo().benefits_discounts else False,
'benefits_discounts_id': s.sudo().benefits_discounts.id if s.sudo().benefits_discounts else False,
li = []
if s.line_ids_over_time:
for r in s.line_ids_over_time:
rec = {
'id': r.id,
'over_time_workdays_hours': r.over_time_workdays_hours,
'over_time_vacation_hours': r.over_time_vacation_hours,
'price_hour': r.price_hour,
'daily_hourly_rate': r.daily_hourly_rate,
'holiday_hourly_rate': r.holiday_hourly_rate,
}
li.append(rec)
value['lines'] = li
})
li = []
if s.line_ids_over_time:
for r in s.line_ids_over_time:
rec = {
'id': r.id,
'over_time_workdays_hours': r.over_time_workdays_hours,
'over_time_vacation_hours': r.over_time_vacation_hours,
'price_hour': r.price_hour,
'daily_hourly_rate': r.daily_hourly_rate,
'holiday_hourly_rate': r.holiday_hourly_rate,
}
li.append(rec)
value['lines'] = li
return http_helper.response(message=_("Overtime Update successfully"),
data={'overtimes': [value], })
else:
return http_helper.response(code=400, message="Overtime Update Not Fount", success=False)
except (UserError, AccessError, ValidationError, Warning) as e:
return http_helper.response(message=_("Overtime Update successfully"),
data={'overtimes': [value], })
else:
return http_helper.response(code=400, message="Overtime Update Not Fount", success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -429,10 +431,12 @@ class OverTimeController(http.Controller):
return http_helper.response(code=400,
message=_("You are can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Warning) as e:
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -463,10 +467,12 @@ class OverTimeController(http.Controller):
return http_helper.response(code=400,
message=_("You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Warning) as e:
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -535,10 +541,12 @@ class OverTimeController(http.Controller):
return http_helper.response(message=_("Get Overtime successfully"),
data={'overtimes': value,})
except (UserError, AccessError, ValidationError, Warning) as e:
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)

View File

@ -73,7 +73,12 @@ class PermissionController(http.Controller):
data = {'links': {'prev': prev_url, 'next': url, }, 'count': count,
'results': {'permissions': emp, 'groups': ['group_division_manager', 'group_hr_user']}}
return http_helper.response(message="Data Found", data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -147,9 +152,11 @@ class PermissionController(http.Controller):
}
return http_helper.response(message="Permission Created Successfully", data={'permission': [data]})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -222,9 +229,11 @@ class PermissionController(http.Controller):
message=_("You are not found this permission by id"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -271,6 +280,10 @@ class PermissionController(http.Controller):
else:
return http_helper.response(code=400, success=False, message="Get Permission Not Fount",
data={'permission': data})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -306,7 +319,12 @@ class PermissionController(http.Controller):
message=_(
"You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -353,7 +371,12 @@ class PermissionController(http.Controller):
return http_helper.response(message="Data Found", data={'balance': balance,
'permission_limit': employee.contract_id.working_hours.permission_hours})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)

View File

@ -167,19 +167,20 @@ class PettiesController(http.Controller):
if not body['type']:
return http_helper.response(code=400,message="Please enter Type",success=False)
try:
petty = http.request.env['petty.cash.payment'].create({
'employee_id':employee.id,
'amount':body['amount'],
'date':body['date'],
'name':body['name'],
'type':body['type'],
})
if petty:
li = []
value = {'id': petty.id, 'name': petty.name,'date':petty.date,'amount':petty.amount,'state':validator.get_state_name(petty,petty.state),
'reconciliation_amount':petty.reconciliation_amount,'type':petty.type.name,'type_id':petty.type.id }
li.append(value)
return http_helper.response(message="Petty Created Successfully", data={'petties': li})
with request.env.cr.savepoint():
petty = http.request.env['petty.cash.payment'].create({
'employee_id':employee.id,
'amount':body['amount'],
'date':body['date'],
'name':body['name'],
'type':body['type'],
})
if petty:
li = []
value = {'id': petty.id, 'name': petty.name,'date':petty.date,'amount':petty.amount,'state':validator.get_state_name(petty,petty.state),
'reconciliation_amount':petty.reconciliation_amount,'type':petty.type.name,'type_id':petty.type.id }
li.append(value)
return http_helper.response(message="Petty Created Successfully", data={'petties': li})
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -213,20 +214,21 @@ class PettiesController(http.Controller):
if not body['type']:
return http_helper.response(code=400,message="Please enter Type",success=False)
try:
petty = http.request.env['petty.cash.payment'].search([('id','=',id)])
if petty:
petty.write({
'employee_id':employee.id,
'amount':body['amount'],
'date':body['date'],
'name':body['name'],
'type':body['type'],
})
li = []
value = {'id': petty.id, 'name': petty.name,'date':petty.date,'amount':petty.amount,'state':validator.get_state_name(petty,petty.state),
'reconciliation_amount':petty.reconciliation_amount,'type':petty.type.name,'type_id':petty.type.id }
li.append(value)
return http_helper.response(message="Petty Updated Successfully", data={'petties': li})
with request.env.cr.savepoint():
petty = http.request.env['petty.cash.payment'].search([('id','=',id)])
if petty:
petty.write({
'employee_id':employee.id,
'amount':body['amount'],
'date':body['date'],
'name':body['name'],
'type':body['type'],
})
li = []
value = {'id': petty.id, 'name': petty.name,'date':petty.date,'amount':petty.amount,'state':validator.get_state_name(petty,petty.state),
'reconciliation_amount':petty.reconciliation_amount,'type':petty.type.name,'type_id':petty.type.id }
li.append(value)
return http_helper.response(message="Petty Updated Successfully", data={'petties': li})
except Exception as e:
_logger.error(str(e))
message = validator.get_server_error(e, user)

View File

@ -4,7 +4,7 @@ from odoo import http,tools
from datetime import datetime
from odoo.http import request, Response
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.exceptions import UserError
from odoo.exceptions import UserError ,AccessError, ValidationError
import base64
from ...validator import validator
from ...http_helper import http_helper
@ -38,7 +38,12 @@ class ProjectController(http.Controller):
value = {'id':pro.id,'name':pro.name,}
li.append(value)
return http_helper.response(message="Data Found", data={'projects':li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -60,7 +65,12 @@ class ProjectController(http.Controller):
return http_helper.response(message="Data Found", data={'projects':value})
else:
return http_helper.response(success=False , code =400 ,message="Data Not Found", data={'projects':value})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -83,7 +93,12 @@ class ProjectController(http.Controller):
value = {'id':t.id,'name':t.name,'state':t.stage_id.name}
li.append(value)
return http_helper.response(message="Data Found", data={'tasks':li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -105,7 +120,12 @@ class ProjectController(http.Controller):
message = _("Data Found")
value = {'id':task.id,'name':task.name,'state':task.stage_id.name}
return http_helper.response(message=message, data={'tasks':value})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -158,7 +178,12 @@ class ProjectController(http.Controller):
url = "/rest_api/v2/timesheets?approvel=%s&page=%s" % (approvel, next) if next else False
data = {'links': {'prev': perv_page, 'next': url, }, 'count': count, 'results': {'timesheets':li,'groups':['group_timesheet_manager']}}
return http_helper.response(message="Data Found", data=data)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -204,6 +229,10 @@ class ProjectController(http.Controller):
else:
return http_helper.response(message=_("Get Not Fount"), data={'timesheets': value})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -232,44 +261,49 @@ class ProjectController(http.Controller):
if not employee:
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)
try:
timesheet = http.request.env['hr_timesheet.sheet'].sudo().create({
'employee_id':employee.id,
'date_start': body['start_date'] ,
'date_end':body['end_date'],
'timesheet_ids':[ (0, 0, {
'date':l['date'],
with request.env.cr.savepoint():
timesheet = http.request.env['hr_timesheet.sheet'].sudo().create({
'employee_id':employee.id,
'project_id':l['project_id'],
'task_id':l['task_id'] if 'task_id' in l else False,
'name':l['description'],
'unit_amount':l['time'] if 'time' in l else 0,
}) for l in data]
})
if timesheet:
li = []
value = {'id': timesheet.id, 'state': validator.get_state_name(timesheet,timesheet.state),
'state_name':timesheet.state,'period': timesheet.display_name,
'start_date': str(timesheet.date_start), 'end_date': str(timesheet.date_end),
'total_hours':timesheet.total_time}
lines = []
value['lines'] = False
'date_start': body['start_date'] ,
'date_end':body['end_date'],
'timesheet_ids':[ (0, 0, {
'date':l['date'],
'employee_id':employee.id,
'project_id':l['project_id'],
'task_id':l['task_id'] if 'task_id' in l else False,
'name':l['description'],
'unit_amount':l['time'] if 'time' in l else 0,
}) for l in data]
})
if timesheet:
li = []
value = {'id': timesheet.id, 'state': validator.get_state_name(timesheet,timesheet.state),
'state_name':timesheet.state,'period': timesheet.display_name,
'start_date': str(timesheet.date_start), 'end_date': str(timesheet.date_end),
'total_hours':timesheet.total_time}
lines = []
value['lines'] = False
if timesheet.timesheet_ids:
for line in timesheet.timesheet_ids:
data = {
'id': line.id,
'date': str(line.date),
'time': line.unit_amount,
'project_id': line.project_id.id,
'project_name': line.project_id.name,
'task_name': line.task_id.name,
'task_id': line.task_id.id,
'description': line.name,
}
lines.append(data)
value['lines'] = lines
li.append(value)
return http_helper.response(message=_("Created successfully"), data={'timesheets': li})
if timesheet.timesheet_ids:
for line in timesheet.timesheet_ids:
data = {
'id': line.id,
'date': str(line.date),
'time': line.unit_amount,
'project_id': line.project_id.id,
'project_name': line.project_id.name,
'task_name': line.task_id.name,
'task_id': line.task_id.id,
'description': line.name,
}
lines.append(data)
value['lines'] = lines
li.append(value)
return http_helper.response(message=_("Created successfully"), data={'timesheets': li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
@ -298,60 +332,67 @@ class ProjectController(http.Controller):
if not employee:
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)
try:
timesheet = http.request.env['hr_timesheet.sheet'].search([('id','=',id)],limit=1)
if timesheet:
timesheet.write({
'employee_id':timesheet.employee_id.id,
'date_start': body['start_date'],
'date_end': body['end_date'],
})
if data:
for l in data:
self.get_timesheet_line(timesheet,l)
li=[]
value = {'id': timesheet.id, 'state': validator.get_state_name(timesheet,timesheet.state),
'state_name':timesheet.state,'period': timesheet.display_name,
'start_date': str(timesheet.date_start), 'end_date': str(timesheet.date_end),
'total_hours':timesheet.total_time}
lines = []
value['lines'] = False
if timesheet.timesheet_ids:
for line in timesheet.timesheet_ids:
data = {
'id': line.id,
'date': str(line.date),
'time': line.unit_amount,
'project_id': line.project_id.id,
'project_name': line.project_id.name,
'task_name': line.task_id.name,
'task_id': line.task_id.id,
'description': line.name,
}
lines.append(data)
value['lines'] = lines
li.append(value)
return http_helper.response(message="Updated successfully", data={'timesheets': li})
with request.env.cr.savepoint():
timesheet = http.request.env['hr_timesheet.sheet'].search([('id','=',id)],limit=1)
if timesheet:
timesheet.write({
'employee_id':timesheet.employee_id.id,
'date_start': body['start_date'],
'date_end': body['end_date'],
})
if data:
for l in data:
self.get_timesheet_line(timesheet,l)
li=[]
value = {'id': timesheet.id, 'state': validator.get_state_name(timesheet,timesheet.state),
'state_name':timesheet.state,'period': timesheet.display_name,
'start_date': str(timesheet.date_start), 'end_date': str(timesheet.date_end),
'total_hours':timesheet.total_time}
lines = []
value['lines'] = False
if timesheet.timesheet_ids:
for line in timesheet.timesheet_ids:
data = {
'id': line.id,
'date': str(line.date),
'time': line.unit_amount,
'project_id': line.project_id.id,
'project_name': line.project_id.name,
'task_name': line.task_id.name,
'task_id': line.task_id.id,
'description': line.name,
}
lines.append(data)
value['lines'] = lines
li.append(value)
return http_helper.response(message="Updated successfully", data={'timesheets': li})
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
def get_timesheet_line(self,sheet,line):
vals = {
'date': line['date'],
'employee_id': sheet.employee_id.id,
'project_id': line['project_id'],
'task_id':line['task_id'] if 'task_id' in line else False,
'name':line['description'] if 'description' in line else False,
'unit_amount':line['time'] if 'time' in line else 0,
}
if 'line_id' in line:
record = http.request.env['account.analytic.line'].search([('id','=',line['line_id'])],limit=1)
if record:
record.write(vals)
else:
vals.update({'sheet_id':sheet.id,})
record = http.request.env['account.analytic.line'].sudo().create(vals)
with request.env.cr.savepoint():
vals = {
'date': line['date'],
'employee_id': sheet.employee_id.id,
'project_id': line['project_id'],
'task_id':line['task_id'] if 'task_id' in line else False,
'name':line['description'] if 'description' in line else False,
'unit_amount':line['time'] if 'time' in line else 0,
}
if 'line_id' in line:
record = http.request.env['account.analytic.line'].search([('id','=',line['line_id'])],limit=1)
if record:
record.write(vals)
else:
vals.update({'sheet_id':sheet.id,})
record = http.request.env['account.analytic.line'].sudo().create(vals)
@http.route(['/rest_api/v2/timesheets/<string:timesheetId>/lines/<string:lineId>'], type='http', auth='none', csrf=False, methods=['DELETE'])
def delete_timesheet_line(self,timesheetId,lineId, **kw):
@ -373,7 +414,12 @@ class ProjectController(http.Controller):
else:
return http_helper.response(code=400,message=_("You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)
@ -398,7 +444,12 @@ class ProjectController(http.Controller):
else:
return http_helper.response(code=400,message=_("You can not perform this operation. please check with one of your team admins"),
success=False)
except (UserError, AccessError, ValidationError, Exception, Warning) as e:
http.request._cr.rollback()
error = str(e)
return http_helper.response(code=400, message=str(error), success=False)
except Exception as e:
http.request._cr.rollback()
_logger.error(str(e))
message = validator.get_server_error(e, user)
return http_helper.errcode(code=403, message=message)