odoo18/custom_addons/customer_orders/controllers/main.py

86 lines
3.2 KiB
Python

from odoo import http
from odoo.http import request
import json
from datetime import datetime, timedelta
class CustomerOrdersDashboard(http.Controller):
@http.route('/customer_orders/dashboard_data', type='json', auth='user')
def dashboard_data(self, **kwargs):
env = request.env
# Get all orders
orders = env['customer.order'].search([])
# Basic statistics
total_orders = len(orders)
total_quantity = sum(orders.mapped('quantity'))
delivered_quantity = sum(orders.mapped('delivered_qty'))
pending_quantity = total_quantity - delivered_quantity
# Orders by state
orders_by_state = {}
for state_key, state_label in dict(env['customer.order']._fields['state'].selection).items():
state_count = env['customer.orders'].search_count([('state', '=', state_key)])
orders_by_state[state_key] = state_count
# Monthly orders for last 6 months
monthly_orders = []
# for i in range(5, -1, -1):
month_date = datetime.now() - timedelta(days=30)
month_start = month_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_end = (month_start + timedelta(days=32)).replace(day=1) - timedelta(days=1)
month_orders = env['customer.orders'].search([
('from_date', '>=', month_start),
('from_date', '<=', month_end)
])
monthly_orders.append({
'month': month_start.strftime('%b %Y'),
'count': len(month_orders),
'quantity': sum(month_orders.mapped('quantity'))
})
# Top customers
top_customers = []
customer_orders = env['customer.orders'].read_group(
[('customer_id', '!=', False)],
['customer_id:count'],
['customer_id']
)
for customer in sorted(customer_orders, key=lambda x: x['customer_id_count'], reverse=True)[:10]:
customer_record = env['res.partner'].browse(customer['customer_id'] if customer['customer_id'] else 1)
top_customers.append({
'id': customer_record.id,
'name': customer_record.name,
'order_count': customer['customer_id_count']
})
# Top products
top_products = []
product_orders = env['customer.orders'].read_group(
[('product_id', '!=', False)],
['product_id', 'quantity:sum'],
['product_id']
)
for product in sorted(product_orders, key=lambda x: x['quantity'], reverse=True)[:10]:
product_record = env['product.product'].browse(product['product_id'][0])
top_products.append({
'name': product_record.name,
'total_quantity': product['quantity']
})
return {
'totalOrders': total_orders,
'totalQuantity': total_quantity,
'deliveredQuantity': delivered_quantity,
'pendingQuantity': pending_quantity,
'ordersByState': orders_by_state,
'monthlyOrders': monthly_orders,
'topCustomers': top_customers,
'topProducts': top_products,
}