
    "i	7                        d dl Z d dlZd dlZ ej                  ej                  j
                         e j                  j                  d ej                  j                  e	             d dl
mZ d dlmZ  edd      Zej                         d0dedefd	       Zej                         d1d
edefd       Zej                         d2dededefd       Zej                         d3dedededefd       Zej                         d0dedefd       Zej                         	 	 	 	 	 	 d4dededededededefd       Zej                         d5dededefd       Zej                         dedefd       Zej                         d6dedefd       Zej                         dedededefd       Zej                         defd       Zej                         dedefd       Zej                         d2ded edefd!       Zej                         d0dedefd"       Z ej                         d7d#edefd$       Z!ej                         d8d#ededefd%       Z"ej                         d9d#edededefd&       Z#ej                         d8d#ededefd'       Z$ej                         d8d#ededefd(       Z%ej                         d9d#edededefd)       Z&ejO                  d*      defd+       Z(ejS                         defd,       Z*ejS                         dedefd-       Z+ejS                         dedefd.       Z,e-d/k(  rej]                          yy):    N)FastMCPgetzIDEAL OMS AnalyticszEReal-time analytics and operational tools for the IDEAL textbook OMS.)nameinstructionsaccount_year_idreturnc                     t        dd| i      S )z
    High-level KPIs for the current (or specified) season.
    Returns: total orders, order value, dispatched count, pending dispatch,
    collections received, overdue amount, open credit note requests, stock alert count.
    zseason-summaryr   r   r   s    9D:\Projects\php\service-ideal0324-oms\pyapi\mcp_server.pyget_season_summaryr      s     "3_!EFF    days_remainingc                     t        dd| i      S )z
    Products that will run out of stock within `days_remaining` days at the current
    order rate. Returns product name, current stock, avg daily orders, days remaining.
    zstock-alertsr   r   )r   s    r   get_stock_alertsr      s     ~ 0.ABBr   zone_idc                      t        d| |d      S )z
    Order quantity vs. target by district with attainment percentage.
    Optionally filter by zone_id or account_year_id.
    zdistrict-performancer   r   r   r   s     r   get_district_performancer   (   s     %7'_``r   limit	from_dateto_datec                 "    t        d| ||d      S )zr
    Top products ranked by total quantity ordered.
    Dates are ISO format YYYY-MM-DD. Default limit is 10.
    ztop-productsr   r   r   r   r   s      r   get_top_productsr   1   s     ~YSZ[\\r   c                     t        dd| i      S )zg
    Products where total orders exceed available stock.
    Critical for purchase order planning.
    zshortfall-productsr   r   r   s    r   get_shortfall_productsr   :   s     #&7%IJJr   	client_iddistrict_idstatusc           
      (    t        d| |||||d      S )z
    Search orders with flexible filters.
    Status values: placed, approved, dispatched, invoiced, cancelled.
    Dates are ISO format YYYY-MM-DD.
    ordersr   r   r    r   r   r   r   r#   s         r   search_ordersr$   C   s*     x "   r   min_days_overduec                      t        d| |d      S )z
    Clients with overdue payments sorted by amount descending.
    `min_days_overdue` filters to only collections overdue by at least that many days.
    zoverdue-collectionsr%   r   r   r'   s     r   get_overdue_collectionsr(   ]   s     $;KV[&\]]r   c                     t        d|        S )u   
    ML-generated payment delay probability (0.0–1.0) for a specific client,
    plus a risk_level label: LOW, MEDIUM, or HIGH.
    zcollection-risk/r   r   s    r   score_collection_riskr+   f   s     !)-..r   c                     t        dd| i      S )z
    Credit note requests flagged as anomalous.
    Returns anomaly score, risk level, and the trigger reason for each record.
    zcn-anomaliesr   r   )r   s    r   get_cn_anomaliesr-   o   s     ~/00r   
product_idnext_season_startc                 "    t        d| ||d      S )u   
    Prophet model demand forecast for a product × district combination.
    `next_season_start` must be an ISO date string e.g. "2026-04-01".
    Returns predicted_qty with lower and upper confidence bounds.
    zdemand-forecastr.   r   r/   r   r1   s      r   forecast_demandr2   x   s"      )*0#  r   c                      t        d      S )zw
    Count and list of items awaiting admin action:
    credit note requests, purchase orders, and orders on hold.
    zpending-approvalsr    r   r   get_pending_approvalsr5      s     "##r   c                      t        d|  d      S )z
    Full analytical profile for a client: lifetime orders, lifetime value,
    current outstanding balance, YTD credit note count, AI segment, collection risk level.
    zclients/z/profiler   r*   s    r   get_client_profiler7      s     )H-..r   sales_user_idc                      t        d| |d      S )zo
    Season attainment percentage per sales user.
    Shows orders placed, target, attainment %, and rank.
    zsales-performancer   r8   r   r:   s     r   get_sales_performancer;      s     "*(%  r   c                     t        dd| i      S )z
    Approved orders ready for dispatch, optionally filtered by district.
    Grouped by geographic cluster with suggested batching.
    zdispatch-queuer   r   r   s    r   get_dispatch_queuer>      s     -!=>>r   queryc                     t        dd| i      S )a-  
    Resolve a human-readable year reference to an account year record with its id.
    Accepted formats:
    - Short range:   '25-26', '2025-26'
    - Full range:    '2025-2026'
    - Single year:   '2025'
    - Relative:      'current', 'active', 'this year',
                     'last year', 'past year', 'previous year',
                     'last 2 years', 'last 3 years', 'past 2 years'
    Returns id, title, from_period, to_period, status, status_label.
    Call BEFORE any tool that accepts account_year_id when the user gives a year by name.
    zlookup/account-yearqr   )r?   s    r   lookup_account_yearrB      s     $sEl33r   c                      t        d| |d      S )z
    Search products by name or code. Returns id, name, code, product_head, stock.
    Call BEFORE forecast_demand or get_shortfall_products when you only have a product name.
    zlookup/productsrA   r   r   r?   r   s     r   lookup_productrF      s      ">??r   c                 "    t        d| ||d      S )z
    Search districts by name or code. Returns id, district_name, zone_id, zone_name.
    Call BEFORE forecast_demand, get_district_performance, get_dispatch_queue,
    or search_orders when you only have a district name.
    zlookup/districts)rA   r   r   r   )r?   r   r   s      r   lookup_districtrH      s     !7U#STTr   c                      t        d| |d      S )z
    Search zones by name or code. Returns id, zone_code, zone_name.
    Call BEFORE get_district_performance when filtering by zone name.
    zlookup/zonesrD   r   rE   s     r   lookup_zonerJ      s     ~UU;<<r   c                      t        d| |d      S )z
    Search sales users by name or username. Returns id, full_name, username, role.
    Call BEFORE get_sales_performance when filtering by a sales user's name.
    zlookup/sales-usersrD   r   rE   s     r   lookup_sales_userrL      s     #55%ABBr   c                 "    t        d| ||d      S )z
    Search clients/dealers by name or client code. Returns id, client_code, client_name, district, zone.
    Call BEFORE score_collection_risk, get_client_profile, or search_orders
    when you only have a client name.
    zlookup/clients)rA   r   r   r   )r?   r   r   s      r   lookup_clientrN      s     u[SX!YZZr   zoms://schema/overviewc                       y)z
    A plain-English description of the IDEAL OMS database schema,
    key table relationships, and business terminology.
    Used by the AI to interpret query results correctly.
    u"	  
    IDEAL OMS Database Overview
    ===========================
    The system manages textbook distribution in Gujarat, India.

    Key Tables:
    - account_years: Each row is one academic season (April–March). Filter all seasonal data by this.
    - admin: Sales reps, back office staff, management teams, etc. users
    - products: Product catalog with stock, price, and category data.
    - boards: Exam boards (Maharashtra, Gujarat, CBSE, etc.)
    - mediums: Languages of instruction (Hindi, Marathi, English, Semi-English)
    - mas_segment: Standard Junior Kg, Senior Kg, 1–12
    - mas_product_head: Product head groups product by their category.
    - mas_series - Series is a collection of books following a common theme.
    - product_balance - Year wise opening and closing stock of products.
    - product_stock - Maintains the running stock of products for each accounting year.
    - clients: Dealers/bookshops who place orders.
    - sales_structure - The sales structure is a hierarchical structure that defines the sales organization.
    - sales_users_relationship - The mapping of users in sales hierarchy.
    - districts / talukas: Geographic hierarchy. Zone → District → Taluka.
    - orders: Main order table with status, dates, and financial info.
    - order_products: Line items showing which products are in which order.
    - purchase_orders: Orders placed to vendors to replenish stock.
    - credit_note: CN generated from the sales returned by clients.
    - credit_note_products: Line items showing which products are in which credit note.
    - transaction_sales: Sales transactions.
    - transaction_sales_products: Line items showing which products are in which sales transaction.
    - transaction_cn: Credit note transactions.
    - transaction_cn_products: Line items showing which products are in which credit note transaction.


    Key Metrics:
    - Total Orders: Count of orders in different statuses.
    - Total Sales: Revenue from sold items.
    - Stock Balance: Current inventory levels.
    - Supply Pending: Orders waiting for stock.
    - Purchase Orders: Pending vendor orders.

    Business Terms:
    - Challan: Physical delivery challan.
    - Stock Balance: Available stock.
    - Supply Pending: Orders awaiting stock.
    - Purchase Order: Vendor purchase order.
    r4   r4   r   r   schema_overviewrP      s    +r   c                       y)z3Generate a daily operations briefing for the admin.u2  
    You are an analytics assistant for IDEAL, a textbook distribution company.

    Please provide a concise daily operations briefing by calling these tools in order:
    1. get_season_summary() — overall health
    2. get_stock_alerts(days_remaining=14) — critical stock issues only
    3. get_overdue_collections(min_days_overdue=30) — urgent payment risks
    4. get_pending_approvals() — what needs action today
    5. get_cn_anomalies(limit=5) — top anomalous credit note requests

    Format the briefing as:
    - A 3-sentence executive summary
    - A bulleted "Action Required" list (items needing immediate attention)
    - A bulleted "Watch List" (items that may need attention in 3–5 days)

    Keep the tone factual and direct. Use ₹ for currency. Flag anything with > ₹1L exposure.
    r4   r4   r   r   daily_ops_briefingrR   %  s    r   c           	           d|  d|  d|  d|  d	S )z&Deep-dive review of a specific client.z!
    You are reviewing client ID z3 for a sales manager.

    Call get_client_profile(zA) to retrieve their profile.
    Then call score_collection_risk(z:) for payment risk.
    Then call search_orders(client_id=a4  , limit=10) for recent orders.

    Provide:
    1. A 2-sentence summary of who this client is and their value to IDEAL.
    2. Their payment behaviour and current risk level.
    3. Any red flags (high CN rate, overdue balance, dropping order frequency).
    4. A recommended action for the sales team.
    r4   r*   s    r   client_reviewrT   :  s9    !!* ,&K (%%.K 0''0k 2 r   c                     d|  d|  d|  dS )z9Demand forecast and stock planning report for a district.z=
    Generate a season stock planning report for district ID z.

    Steps:
    1. Call get_stock_alerts() and filter for this district.
    2. Call get_shortfall_products() to identify gaps.
    3. Call get_district_performance() with district_id=zm for target context.
    4. For the top 3 shortfall products, call forecast_demand(product_id=X, district_id=z,
       next_season_start="2026-04-01") to get next season estimates.

    Output a markdown table: Product | Current Stock | Projected Need | Gap | Suggested PO Qty
    Then write a 2-sentence purchasing recommendation.
    r4   r=   s    r   season_forecast_reportrV   L  s7    ==HM J9
 :E FYYdXe f r   __main__)N)   )NN)
   NN)NNNNN   )rX      )r[   )current)   )Nr]   )/sysosurllib3disable_warnings
exceptionsInsecureRequestWarningpathinsertdirname__file__mcp.server.fastmcpr   laravel_clientr   mcptoolintdictr   r   r   strr   r   r$   r(   r+   r-   r2   r5   r7   r;   r>   rB   rF   rH   rJ   rL   rN   resourcerP   promptrR   rT   rV   __name__runr4   r   r   <module>rs      s   
 	    ++BB C 277??8, - & 	X G Gt G G CS C$ C C ac a3 aRV a a ]C ] ]c ]UY ] ] KC K4 K K   	
   
 2 ^c ^s ^D ^ ^ /S /T / / 1C 1 1 1 
 
# 
# 
RV 
 
 $t $ $ /# /$ / / 3 c UY   ?C ?4 ? ? 4s 44 4 4" @# @c @4 @ @ U3 U UC U U U =s =3 = = = CS C Cd C C [ [3 [c [4 [ [ %&1 1 '1f C  ( S S  "    $ zGGI r   