Mangi
Mangi

Reputation: 23

ERPNext v15 Dahua time attendance Employee CheckIn integration

I am trying to push employee attendance data with this code:

import local_config as config
import datetime
import requests
import json

def _safe_get_error_str(response):
    """
    Extracts a safe error string from the response object.
    """
    try:
        error_data = response.json()
        return error_data.get('message', str(response.content))
    except Exception:
        return str(response.content)

def send_to_erpnext(employee_field_value, timestamp, device_id=None, log_type=None):
    """
    Example: send_to_erpnext('12349', datetime.datetime.now(), 'HO1', 'IN')
    """
    endpoint_app = "hrms" if config.ERPNEXT_VERSION > 13 else "erpnext"
    url = f"{config.ERPNEXT_URL}/api/method/{endpoint_app}.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field"
    
    headers = {
        'Authorization': "token " + config.ERPNEXT_API_KEY + ":" + config.ERPNEXT_API_SECRET,
        'Accept': 'application/json'
    }
    data = {
        'employee_field': 'attendance_device_id',  # Dodato polje
        'employee_field_value': employee_field_value,
        'timestamp': timestamp.isoformat(),
        'device_id': device_id,
        'log_type': log_type
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        print("Successfully logged employee check-in.")
        return 200, response.json()
    else:
        error_str = _safe_get_error_str(response)
        print(f"Error during ERPNext API Call: {error_str}")
        return response.status_code, error_str


# Test funkcija
send_to_erpnext('HR-EMP-00004', datetime.datetime.now(), 'HO1', 'IN')

In the second file I have this: Ofc I deleted api key secret for this question only...

# ERPNext related configs
ERPNEXT_API_KEY = ''
ERPNEXT_API_SECRET = ''
ERPNEXT_URL = ''
ERPNEXT_VERSION = 15



# operational configs
PULL_FREQUENCY = 60 # in minutes
LOGS_DIRECTORY = 'logs' # logs of this script is stored in this directory
IMPORT_START_DATE = None # format: '20190501'

# Biometric device configs (all keys mandatory)
    #- device_id - must be unique, strictly alphanumerical chars only. no space allowed.
    #- ip - device IP Address
    #- punch_direction - 'IN'/'OUT'/'AUTO'/None
    #- clear_from_device_on_fetch: if set to true then attendance is deleted after fetch is successful.
                                    #(Caution: this feature can lead to data loss if used carelessly.)
# Biometric device configs (Dahua device)
devices = [
    {'device_id': 'mangi', 'ip': 'http://192.168.', 'punch_direction': 'AUTO', 'clear_from_device_on_fetch': False}
]


# Configs updating sync timestamp in the Shift Type DocType 
# please, read this thread to know why this is necessary https://discuss.erpnext.com/t/v-12-hr-auto-attendance-purpose-of-last-sync-of-checkin-in-shift-type/52997
shift_type_device_mapping = [
    {'shift_type_name': ['Shift1'], 'related_device_id': ['test_1','test_2']}
]


# Ignore following exceptions thrown by ERPNext and continue importing punch logs.
# Note: All other exceptions will halt the punch log import to erpnext.
#       1. No Employee found for the given employee User ID in the Biometric device.
#       2. Employee is inactive for the given employee User ID in the Biometric device.
#       3. Duplicate Employee Checkin found. (This exception can happen if you have cleared the logs/status.json of this script)
# Use the corresponding number to ignore the above exceptions. (Default: Ignores all the listed exceptions)
allowed_exceptions = [1,2,3]

And this is the error I get:

/bin/python /home/mangi/frappe-bench/biometric-attendance-sync-tool/test/test.py ✖ ✹ ✭master Error during ERPNext API Call: b'{"exception":"frappe.exceptions.ValidationError: No Employee found for the given employee field value. 'attendance_device_id': HR-EMP-00004","exc_type":"ValidationError","_exc_source":"hrms (app)","exc":"[\"Traceback (most recent call last):\\n File \\\"apps/frappe/frappe/app.py\\\", line 114, in application\\n response = frappe.api.handle(request)\\n File \\\"apps/frappe/frappe/api/init.py\\\", line 49, in handle\\n data = endpoint(**arguments)\\n File \\\"apps/frappe/frappe/api/v1.py\\\", line 36, in handle_rpc_call\\n return frappe.handler.handle()\\n File \\\"apps/frappe/frappe/handler.py\\\", line 49, in handle\\n data = execute_cmd(cmd)\\n File \\\"apps/frappe/frappe/handler.py\\\", line 85, in execute_cmd\\n return frappe.call(method, **frappe.form_dict)\\n File \\\"apps/frappe/frappe/init.py\\\", line 1768, in call\\n return fn(*args, **newargs)\\n File \\\"apps/frappe/frappe/utils/typing_validations.py\\\", line 31, in wrapper\\n return func(*args, **kwargs)\\n File \\\"apps/hrms/hrms/hr/doctype/employee_checkin/employee_checkin.py\\\", line 118, in add_log_based_on_employee_field\\n frappe.throw(\\n File \\\"apps/frappe/frappe/init.py\\\", line 645, in throw\\n msgprint(\\n File \\\"apps/frappe/frappe/init.py\\\", line 610, in msgprint\\n _raise_exception()\\n File \\\"apps/frappe/frappe/init.py\\\", line 561, in _raise_exception\\n raise exc\\nfrappe.exceptions.ValidationError: No Employee found for the given employee field value. 'attendance_device_id': HR-EMP-00004\\n\"]","_server_messages":"[\"{\\\"message\\\": \\\"No Employee found for the given employee field value. 'attendance_device_id': HR-EMP-00004\\\", \\\"title\\\": \\\"Message\\\", \\\"indicator\\\": \\\"red\\\", \\\"raise_exception\\\": 1, \\\"__frappe_exc_id\\\": \\\"c50c9b943a17a6e5425a0057cfa9c01d3cbd13bca6d84a8796fdf93b\\\"}\"]"}'

The Idea is to integrate Dahua time attendance device with ERPNext in the way that when employees Check In or Check Out the python script pulls the data of which rfid cart is it and when was the person checked and what was the status in or out and after that to go to ERPNext HR/Employee Checkin and push the data.

Upvotes: 0

Views: 124

Answers (1)

Mangi
Mangi

Reputation: 23

send_to_erpnext('HR-EMP-00004', datetime.datetime.now(), 'HO1', 'IN')
# The mistake was here ⬆

I put the employee id instead of the attendance device id. it is created in HR/Employee/Name of the Employee/Attendances and Leaves/

Upvotes: 0

Related Questions