#!/usr/bin/env python3
"""
Batch script to import remaining active employees from CSV into Odoo
"""
import csv
import sys
import os
import time
from datetime import datetime
# Add the src directory to Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from odoo_mcp.odoo_client import get_odoo_client
def get_existing_employee_names(client):
"""Get list of existing employee names in Odoo"""
print("Fetching existing employees...")
employees = client.search_read('hr.employee', [], ['name'], limit=1000)
existing_names = set(emp['name'] for emp in employees)
print(f"Found {len(existing_names)} existing employees")
return existing_names
def parse_date(date_str):
"""Parse date string in M/D/YYYY format to Odoo format YYYY-MM-DD"""
if not date_str or date_str.strip() == '':
return None
try:
# Handle M/D/YYYY format
dt = datetime.strptime(date_str.strip(), '%m/%d/%Y')
return dt.strftime('%Y-%m-%d')
except ValueError:
try:
# Handle MM/DD/YYYY format
dt = datetime.strptime(date_str.strip(), '%m/%d/%Y')
return dt.strftime('%Y-%m-%d')
except ValueError:
print(f"Warning: Could not parse date '{date_str}'")
return None
def clean_phone(phone):
"""Clean phone number format"""
if not phone:
return None
# Remove any spaces and ensure it starts with +966
phone = phone.strip().replace(' ', '')
if phone.startswith('966'):
phone = '+' + phone
return phone
def create_employee_from_csv_row(client, row):
"""Create an employee record from CSV row data"""
try:
# Map CSV fields to Odoo employee fields
employee_data = {
'name': row['Name'].strip() if row['Name'] else 'Unknown',
'work_phone': clean_phone(row['mobile_number']),
}
# Create work email from name
if row['Name']:
name_parts = row['Name'].strip().lower().split()
if len(name_parts) > 1:
email = f"{name_parts[0]}.{name_parts[-1]}@barqapp.com"
else:
email = f"{name_parts[0]}@barqapp.com"
employee_data['work_email'] = email
# Add optional fields if available
if row['id_number']:
employee_data['identification_id'] = row['id_number'].strip()
if row['Date Of Birth']:
dob = parse_date(row['Date Of Birth'])
if dob:
employee_data['birthday'] = dob
if row['Joining Date']:
joining_date = parse_date(row['Joining Date'])
if joining_date:
employee_data['first_contract_date'] = joining_date
result = client.create_record('hr.employee', employee_data)
if isinstance(result, list) and len(result) > 0:
employee_id = result[0]
return employee_id
else:
print(f"Failed to create employee '{employee_data['name']}': {result}")
return None
except Exception as e:
print(f"Error creating employee '{row.get('Name', 'Unknown')}': {str(e)}")
return None
def import_remaining_employees(batch_size=50):
"""Import remaining active employees from CSV in batches"""
csv_file = '/Users/ramizmohamed/Downloads/Asset Managment - COURIER MASTER SHEET (1).csv'
try:
# Initialize Odoo client
print("Connecting to Odoo...")
client = get_odoo_client()
print("Connected successfully!")
# Get existing employees to avoid duplicates
existing_names = get_existing_employee_names(client)
# Read CSV file
print(f"Reading CSV file: {csv_file}")
created_count = 0
failed_count = 0
skipped_count = 0
batch_count = 0
with open(csv_file, 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row_num, row in enumerate(reader, start=2): # Start from 2 since row 1 is headers
# Only process active employees
if row['Status'].strip().lower() == 'active':
employee_name = row['Name'].strip()
# Skip if employee already exists
if employee_name in existing_names:
print(f"Skipping row {row_num}: {employee_name} (already exists)")
skipped_count += 1
continue
print(f"Processing row {row_num}: {employee_name}")
employee_id = create_employee_from_csv_row(client, row)
if employee_id:
created_count += 1
print(f"✓ Created employee '{employee_name}' with ID: {employee_id}")
existing_names.add(employee_name) # Add to avoid duplicates in this run
else:
failed_count += 1
print(f"✗ Failed to create employee '{employee_name}'")
# Process in batches to avoid timeouts
if (created_count + failed_count) % batch_size == 0:
batch_count += 1
print(f"\n=== Batch {batch_count} Complete ===")
print(f"Created: {created_count}, Failed: {failed_count}, Skipped: {skipped_count}")
print("Pausing for 2 seconds...")
time.sleep(2)
print(f"\n=== Final Import Summary ===")
print(f"Successfully created: {created_count} employees")
print(f"Failed to create: {failed_count} employees")
print(f"Skipped (already exist): {skipped_count} employees")
print(f"Total processed: {created_count + failed_count + skipped_count} active employees")
except Exception as e:
print(f"Error during import: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == '__main__':
import_remaining_employees()