> Enterprise Car Rental Fleet & Reservation Management System

// Created at: 04-08-2026

[Python] [Flask] [HTML] [CSS] [Pillow] [JavaScript] [SQL] [Regex] [ReportLab]

>> Core APP Highlights & Briefing - with Examples

// Deep Layer Record Synced // Level 02

Core APP Highlights & Briefing - with Examples

[Subproject Overview]

Granular backend blueprint software case study. It demonstrates the commands over databases pool optimization, advanced memory architecture design, cryptographic token processing, complex range calculations, and low-latency data streaming patterns. Exceptional engineering work across the entire platform ecosystem! ΓÇó The Core Storage Abstraction Engines (GetData): Managing multi-pool database connection allocations, distributed cache hydration tasks, and user identity session checks entirely in RAM. ΓÇó The Predictive Fleet Schedulers (get_processed_reservations): Flattening double-date records into separate delivery/return lifecycle event blocks to drive front-end interactive dashboard timelines. ΓÇó The In-Memory Fleet Protection Radar (check_car_conflict / check_collision): Executing real-time mathematical timeline range intersection scans to completely block double-booking anomalies on the lot. ΓÇó State Modification Controllers (edit_reservation / edit_event_details): Running bidirectional pre-population loops and alpha-channel character transformations (DD-MM-YYYY text to strict ISO boundaries). ΓÇó Paperless Contract Persistence Engines (create_contract): Structuring massive 67-element parameterized tuple arrays, applying idempotent upsert commands (ON DUPLICATE KEY UPDATE), and saving compiled PDF documents right inside secure LONGBLOB column matrices. ΓÇó Post-Signing Distribution Pipelines (booking_details): Packaging binary payloads via advanced multipart MIME specifications and establishing secure SMTP over SSL encrypted network tunnels. ΓÇó Dynamic Addendum & Operational Trackers (create_extension / view_manual_car_fleet): Running pro-rata pricing derivation loops and active 30-day compliance lookahead tracking matrices to flag expiring documentation. ΓÇó Real-Time Signature Extraction Rasterizers (get_signature_fixed): Running 300% supersampling rasterization upgrades over archived documents and removing white background grids via pixel-by-pixel alpha channel mutations. ΓÇó Predictive Valuation Engines (calculate_prices_via_api / calc_fleet_prices_native): Processing bulk checkboxes through alphanumeric text trimming filters, applying 1% safety exchange margins, and allocating vehicles uniquely via session de-queueing .pop(0) patterns. ΓÇó Lead Pipeline Marketing Automation Subsystems (save_lead_prospect_pipeline): Translating raw account metrics into markdown templates and percent-encoding text vectors to compile direct-action click-to-chat paths. ΓÇó Pipeline Sales Dashboards (list_commercial_offers / view_single_commercial_offer): Querying correlated SQL group sub-selects and injecting hidden form tracking data on the server to enable instant contract conversions. ΓÇó Distributed Database Ingestion Managers (launch_direct_wp_sql_booking): Bypassing REST wrappers to perform multi-table atomic direct injections under strict non-autocommit database sandboxes. ΓÇó Automated Outbound Notification Routers (dispatch_whatsapp_message): Managing telephone data normalization loops and enforcing strict network timeouts to drive external communication microservices. ΓÇó High-Resolution Performance Profilers & Helpers (monitor_speed / convert_string_to_float): Running aspect-oriented latency monitoring clocks and transforming localized accounting text strings into clean float primitives. ΓÇó Automated Document Generation Factories (generate_completion_report): Structuring absolute coordinate vector canvasses, loading complex graphics overlays, and embedding customer handwritten digital touch signatures entirely inside memory buffer containers. ΓÇó Business Intelligence Reporting Hubs (report_fleet_performance / report_fleet_efficiency / report_fleet_profitability / report_fleet_seasonality): Running custom-range data filters, performing pro-rata income allocations, and deriving elite asset yield metrics (RevPAV, Occupancy, ADR) over long-term multi-year macro-trend scanners. ΓÇó Intelligent Document Vision Ingestion Hubs (process_ocr_limited_resources): Orchestrating REST-based image annotators, running polymorphic region precedence filters, and using reverse-chronological calendar fallbacks to secure driver identity data.

[Deep Case Study]

>__Infrastructure & Core Operations

Config & Setup: Acts as the application's bootstrap layer. It initializes the Flask core, registers global security middlewares like CSRFProtect, configures filesystem upload structures, and provisions live real-time currency exchange settings. Authentication: The system gatekeeper. It orchestrates role-based user state persistence across the platform (register, login, logout), enforcing secure administrative session isolation. Document Archive & Triage: Handles heavy batch input/output disk processes. It isolates completed legal contract folders and packages them sequentially into compressed ZIP archives for fast administrative data exports. The Data Core & Client PipelineData Access Layer (GetData Class): The monolithic application's single source of truth. It abstracts all database interaction, using raw parameterized query methods over thread-safe mysql.connector.pooling pipes to eliminate messy inline database calls. Client Documentation: Manages confidential tenant uploads. It routes encrypted verification file uploads, handles disk deletion warnings, and pipes attachments to client notification modules. Customer Database: A unified relational directory that maps individual tenant demographic schemas directly to their historical transaction logs, legal paperwork paths, and verification states. Smart Automations & Business LogicAI OCR Identity Scanning: A performance-critical pipeline spanning nearly 1,200 lines. It routes unstructured image arrays to an asynchronous computer vision engine to extract demographic fields instantly, eliminating manual data entry during customer onboarding. Contracts & Operations: The transactional engine of your business model. It dynamically generates absolute 2D point grid PDF files, tracks digital extensions, captures touchscreen signatures as vector streams, and compiles final completion logs. Commercial Leads Pipeline: A flexible commercial CRM that tracks the pipeline of incoming prospects, structures dynamic digital quotes, and translates entries into automated outbound text triggers. Fleet Management, Pricing, & AnalyticsCalendar & Reservations: Operates the primary visualization interface. It evaluates time-series arrays entirely in worker RAM to calculate vehicle availability matrices and instantly catch chronological reservation collisions. Event Booking Details: Controls granular booking lifecycles. It cross-validates reservation parameters, fields overlapping schedules during inline edits, and locks assets down securely. Fleet & Dynamic Pricing & Inventory CRUD: Acts as the physical asset lifecycle tracker. It logs long-term mechanical breakdown metrics, manages service scheduling intervals, maps fleet availability, and computes pricing models through external API calls. WooCommerce Sync Layer: The cross-platform bridge. It establishes direct multi-tenant database pools to online WordPress tables, pulling public site bookings straight into the back-office dashboard while bypassing slow standard REST API ceilings. Advanced BI Reporting: The platform's analytical center. It streams historical records natively into worker memory to evaluate fleet productivity trends, calculating asset efficiency indicators like Average Daily Rate (ADR) and Revenue Per Available Vehicle (RevPAV) over multi-year ranges.

+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Logical Block                      | Main Components                    | Systemic Role                                                 |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Config & Setup                     | imports, Flask(__name__),          | Application bootstrap, middleware configuration,              |
| (Lines 66ΓÇô705)                     | CKEditor, CSRFProtect,             | upload directories initialization, and currency exchange      |
|                                    | UPLOAD_FOLDER                      | rate engine setup.                                            |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Data Access Layer                  | ~20 centralized core methods       | The sole unified database interrogation entry point.          |
| GetData Class (746ΓÇô1775)           | (e.g., get_current_bookings,       | The rest of the monolithic application relies heavily on      |
|                                    | get_available_cars, get_invoices)  | this class to query persistence layers.                       |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Authentication (1923ΓÇô2015)         | register, login, logout            | Secures system access through native user session control.    |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Calendar & Reservations            | show_calendar, get_events,         | Renders the interactive visual calendar matrix, executing     |
| (2015ΓÇô2567)                        | check_car_conflict,                | low-latency runtime vehicle/timeslot collision checks.        |
|                                    | swap_manual_booking                |                                                               |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Home Dashboard (2645ΓÇô2730)         | home                               | Core landing interface; aggregates statistics via the         |
|                                    |                                    | centralized data engine (get_unified_home_data).              |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Event Booking Details              | view_event_details,                | Isolates granular reservation metadata, enforcing overlap     |
| (2730ΓÇô3339)                        | check_collision, manage_booking    | cross-validation rules during administrative text editing.    |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Client Documentation               | upload_docs, view_docs,            | Manages client identity files via secure upload, viewing,     |
| (3339ΓÇô3558)                        | delete_docs (+ warning), send_docs | and bulk document dispatch processes.                         |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| AI OCR Identity Scanning           | get_registry_data (~1200 lines),   | Extracts text parameters from client identity cards via an    |
| (3558ΓÇô4824)                        | pre_contract_ocr                   | asynchronous computer vision engine to speed up check-ins.    |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Contracts & Operations             | create_contract, create_extension, | The business logic core: generates, edits, extends,           |
| (4824ΓÇô7000)                        | sign_extension, view_contract,     | and finalizes absolute 2D point grid digital PDF assets       |
|                                    | view_completion_report             | along with touchscreen vector signature capture streams.      |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Fleet & Dynamic Pricing            | view_manual_car_fleet,             | Scans for vacant vehicle frames and triggers dynamic price    |
| (7000ΓÇô7712)                        | search_free_cars_extended,         | calculations based on native formulas and external web APIs.  |
|                                    | calc_fleet_prices_native           |                                                               |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Commercial Leads Pipeline          | dispatch_whatsapp_message,         | Operates the sales funnel, transitioning commercial leads to  |
| (7685ΓÇô8045)                        | save_lead_prospect_pipeline,       | structured price offers with direct WhatsApp API triggers.    |
|                                    | list_commercial_offers             |                                                               |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| WooCommerce Sync Layer             | generate_site_booking_code,        | Establishes live database connection tunnels to remote        |
| (8045ΓÇô8726)                        | inject_wp_extra_option_natively,   | production tables to synchronize public online web            |
|                                    | launch_direct_wp_sql_booking       | reservations.                                                 |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Fleet Inventory CRUD               | add_manual_car, delete_car,        | Administrative physical vehicle asset tracker; logs long-term |
| (8726ΓÇô9342)                        | car_maintenance, edit_maintenance, | breakdown logs, service periods, and full vehicle histories.  |
|                                    | car_history, contract_details      |                                                               |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Document Archive & Triage          | all_contracts, triaj_contracts,    | Executes high-speed batch operations; packages legal PDFs     |
| (9342ΓÇô9742)                        | archive_download_all,              | into custom zip archives for bulk administrative disk         |
|                                    | archive_delete_all                 | downloads.                                                    |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Customer Database                  | view_all_customers,                | Storage directory for individual client demographic records   |
| (9742ΓÇô9906)                        | view_customer_details              | and linked background document paths.                         |
+------------------------------------+------------------------------------+---------------------------------------------------------------+

| Advanced BI Reporting              | view_reports, report_fleet,        | Aggregates long-term, multi-year macro trends; derives asset  |
| (9906ΓÇô10828)                       | report_fleet_performance,          | yield indicators like Average Daily Rate (ADR) and Revenue    |
|                                    | report_fleet_profitability         | Per Available Vehicle (RevPAV) via safe RAM streaming loops.  |
+------------------------------------+------------------------------------+---------------------------------------------------------------+
>__Application Bootstrapping & Runtime Environment Architecture

Before initializing any Flask routes or handling HTTP traffic, the core backend executes a precise sequence of system-level operations. This ensures predictable, cross-platform execution (Linux/Windows), sandboxes environmental secrets, and guarantees strict data consistency across multi-regional workflows. Technical Deep Dive & Architectural Decisions 1. Dynamic Working Directory Alignment & Path Injection python os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.getcwd()) Syntax & Mechanism: The script evaluates the absolute path of the current file, extracts its parent directory, and mutates the current working directory (cwd) of the operating system process via os.chdir. It then injects this path at index 0 of sys.path. This architectural choice eliminates ModuleNotFoundError and relative path fracturing. When deploying Flask applications via external process managers (such as Gunicorn, uWSGI, or Systemd services), the root execution context can shift. This block guarantees that the application context remains strictly local to its internal tree. 2. Environment Isolation (12-Factor App Compliance) load_dotenv() basedir = os.path.abspath(os.path.dirname(__file__)) Syntax & Mechanism: load_dotenv() scans the root directory for a .env file, parsing and injecting sensitive credentials (Google Cloud keys, Database URIs, WhatsApp tokens) straight into os.environ. It decouples infrastructure configuration from application logic. This enforces strict security hygiene by ensuring production keys never leak into git repositories, keeping the platform inherently scalable across staging and production environments. 3. Standard I/O Stream Reconfiguration for Multi-Language Processing python if sys.stdout.encoding != 'utf-8': sys.stdout.reconfigure(encoding='utf-8') Syntax & Mechanism: It inspects the native encoding of the system host standard output (sys.stdout). If it differs from utf-8, it forces a runtime reconfiguration. Because this application aggregates international data (passports, driver's licenses from Romania, Germany, UK, France, etc.), console logging or error streaming would immediately crash with a fatal UnicodeEncodeError on misconfigured server hosts. This design pattern ensures robust system telemetry regardless of the host OS locale. 4. Unicode Typography Mapping for Document Generation FONT_NAME = 'ArialUnicode' FONT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'fonts', 'ARIAL.TTF') pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH)) Syntax & Mechanism: Resolves a deterministic absolute path to a TrueType font (.ttf) and registers it globally inside the ReportLab PDF rendering subsystem engine. Native PDF fonts (like standard Helvetica or Times) fail to render Eastern European diacritics (ș, ț, ă) or specific Western European special characters. By embedding a unified Unicode layout asset at initialization, the app ensures that automated legal contracts are flawlessly generated without broken font symbols. 5. Clean Architecture via Modular Utility Decoupling python from utils import (monitor_speed, generate_pdf_contract, ...) Syntax & Mechanism: Selective module-level imports isolation. Demonstrates Separation of Concerns. Heavy computations (PDF compilation, custom string sanitization, and hardware-conscious OCR throttling (process_ocr_limited_resources)) are offloaded to dedicated decoupled helper modules, keeping the core controller routing slim and highly maintainable.

os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.getcwd())
load_dotenv()
basedir = os.path.abspath(os.path.dirname(__file__))

# Import custom utilities and decorators for clean separation of concerns
from utils import (monitor_speed, 
    generate_pdf_contract, 
    generate_completion_report, 
    convert_string_to_float, 
    merge_lists_into_new, 
    to_int, 
    check_prefix, 
    process_ocr_limited_resources, 
    safe_date_convert,
    sanitize_folder_name,
    )

# Force all standard output to use UTF-8 regardless of system settings
if sys.stdout.encoding != 'utf-8':
    sys.stdout.reconfigure(encoding='utf-8')

# Define the font name and path for compliant PDF engine compilation
FONT_NAME = 'ArialUnicode'
FONT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'fonts', 'ARIAL.TTF') 

# Register the font globally within the ReportLab engine
pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH))
>__Flask Application Core Initialization & Dual-Pool Database Infrastructure

Technical Deep Dive & Architectural Decisions 1. Micro-Framework Instantiation & Global State Security This module handles the core instantiation of the Flask framework, enforces web-tier security protocols, isolates file-system storage paths, and establishes a highly scalable, multi-tenant dual connection-pool architecture. Syntax & Mechanism: Instantiates the Flask WSGI kernel using the current module name (__name__) as the resolution anchor. It injects a cryptographically strong runtime secret token (SECRET_KEY) fetched straight from environmental variables and registers the global CSRFProtect engine. Enforces Enterprise-grade Security Defenses. By implementing automated token validation on all state-changing HTTP requests (POST, PUT, DELETE), the application completely neutralizes Cross-Site Request Forgery (CSRF) vectors. It preserves clean, secure session signing without committing hardcoded secrets to version control. 2. Localized Blob Storage Configuration & SEO Isolation Syntax & Mechanism: Declares a structured local file-system path to capture ingested client payloads and maps an explicit, non-cached inline route to intercept search engine crawlers via standard raw text/plain headers. Ensures Data Privacy & System Isolation. Because this platform parses sensitive identity documents (Passports, Driver's Licenses), the static directory must be fortified against accidental public indexing. The /robots.txt route actively forbids crawlers from mapping internal file structures, preserving user confidentiality. 3. Dual-Pool Relational Database Engineering Syntax & Mechanism: Instantiates two isolated, thread-safe instances of MySQLConnectionPool. One binds to the remote WordPress source database via external routing, while the other establishes low-latency, loopback (127.0.0.1) communication to the native ERP database. Both enforce strict utf-8mb4 character mapping. Highlights advanced High-Concurrency Engineering and ETL Architecture. Rather than opening and tearing down individual database connections on every HTTP requestΓÇöwhich induces massive network latency and risks socket exhaustionΓÇöthe application utilizes a fixed connection-pool strategy (pool_size=5). This decouples read-only ingestion tasks (WordPress Webhooks) from operational business tasks (Local Contract generation), avoiding read-write locks and scaling safely under load.

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('FLASK_KEY')

UPLOAD_FOLDER = 'static/clients_images/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

ckeditor = CKEditor(app)
csrf = CSRFProtect(app)

@app.route('/robots.txt')
def robots_txt():
    return "User-agent: *\nDisallow: /", 200, {'Content-Type': 'text/plain'}

# WordPress Remote Database Credentials
db_host_wp = os.environ.get('DB_HOST')
db_user_wp = os.environ.get('DB_USER')
db_pass_wp = os.environ.get('DB_PASSWORD')
db_source_wp = os.environ.get('DB_NAME')

# Flask Local Database Credentials
db_target_flask = os.environ.get('DB_TARGET_NAME')
db_user_flask = os.environ.get('FLASK_DB_USER')
db_pass_flask = os.environ.get('FLASK_DB_PASS')

# Dedicated Connection Pool for Remote WordPress Database
pool_live = pooling.MySQLConnectionPool(
    pool_name="pool_live",
    pool_size=5,
    host=db_host_wp,     
    user=db_user_wp,      
    password=db_pass_wp, 
    database=db_source_wp,
    charset='utf8mb4'
)

# Dedicated Connection Pool for Local Enterprise ERP Database
pool_new = pooling.MySQLConnectionPool(
    pool_name="pool_new",
    pool_size=5,
    host='127.0.0.1',     
    user=db_user_flask,   
    password=db_pass_flask,
    database=db_target_flask,
    charset='utf8mb4'
)
>__Enterprise Data-Ingestion & State-Management Architecture

This module implements a centralized state-management controller via the GetData class. It manages in-memory data structures, interfaces with the connection pools, and enforces optimized data retrieval patterns to maintain systemic integrity. The GetData class acts as the centralized State Aggregator and Data Access Object (DAO) for the entire ERP system. It serves as a unified abstraction layer over raw SQL transactions, transforming flat tabular database rows into highly optimized, read-heavy, in-memory data models. This architectural layer isolates the Flask web controllers from complex database query logic, acting as an intermediate caching and caching-validation gateway.

class GetData():
    def __init__(self):
        self.blocked_ids = set()
        self.car_plates_lookup = {}
        self.current_bookings = {}
        self.all_cars = {}
        self.all_bookingids_to_sku = {}
        self.booked_cars = {}
        self.all_locations = {}
        self.booked_locations = {}
        self.booked_customers = {}
        self.booked_invoices = {}
        self.available_cars = {}
        self.reservations = {}
        self.contracted_bookings_data = {}
        self.pending_bookings = {}
        self.booked_rental_options = {}
>__Method Dissection: get_current_bookings(self) - example

Granular Code Dissection ΓÇó db_offset = self.get_current_offset(): Issues a call to the local database settings table to pull the operational timezone difference parameter dynamically. ΓÇó tz_config = timezone(timedelta(hours=db_offset)): Instantiates a fixed-offset datetime.timezone instance utilizing a datetime.timedelta configuration. This approach decouples the ERP app from the host OS clock, preventing synchronization drift when running on cloud infrastructures like AWS or Google Cloud. ΓÇó current_time = int(datetime.now(tz_config).timestamp()): Captures the exact localized point-in-time, extracts its Unix timestamp float representation, and casts it to a clean integer. This integer serves as a stable temporal baseline for relational querying. ΓÇó db_conn = pool_live.get_connection(): Pulls a thread-safe connection socket from the remote WordPress production pool, preventing individual socket allocation latency. ΓÇó cursor = db_conn.cursor(dictionary=True, buffered=True): Allocates an advanced execution cursor. ΓÇó dictionary=True instructs the database driver to return rows as native Python dictionaries matching database column names. ΓÇó buffered=True forces the client to download the complete query result set into application RAM immediately. This completely frees up the database channel, allowing other operational threads to run without triggering an Unread result found error. ΓÇó query = """ ... """: Implements targeted data projection, explicitly selecting 8 fields to minimize network payload sizes over external network wires. ΓÇó WHERE return_timestamp >= %s AND is_cancelled = 0: Filters out historical and cancelled data directly on the database engine. This logic uses parameterized positional binding (%s) to completely eliminate SQL Injection vulnerabilities. ΓÇó db_bookings_details = cursor.fetchall(): Populates a local row collection array from the buffered client memory space. for booking in db_bookings_details:: Loops over the retrieved reservation collection. ΓÇó datetime.fromtimestamp(..., tz=tz_config): Converts flat UNIX timestamps into localized, timezone-aware datetime instances. This step ensures that raw database metrics are accurately translated to the company's actual operating timezone. ΓÇó self.current_bookings[b_id] = { ... }: Builds a structured in-memory hash map indexed directly by the unique booking_id. ΓÇó .strftime("%d-%m-%Y") / .strftime("%H:%M"): Formats the datetime objects into clean, standardized strings. This separates date parameters from time parameters, making the data easy for frontend calendar layouts and automated contracts to use without further processing. ΓÇó except mysql.connector.Error as err:: Catches any database connection drops or execution failures, returning an explicit error string and an HTTP 500 status code to aid in remote system debugging. ΓÇó if 'cursor' in locals() and cursor: cursor.close(): Validates that the cursor exists in the local namespace and closes it to clear out processed data caches. ΓÇó if db_conn.is_connected(): db_conn.close() else: db_conn = None: A defensive resource check. If a network issue drops the connection midway, calling .close() would throw an application error. This check handles lost connections gracefully by clearing out the object name directly without a crash. Systemic Role within the Component and Application This method acts as the system's Real-Time Data Ingestion Pipeline. Its main job is to pull live reservations from WordPress, clean up the timestamps into uniform localized strings, and cache them into application memory. It prevents old data from bogging down the application and drives the interactive dispatch calendar by feeding it a clean, real-time dataset.

def get_current_bookings(self):
        db_offset = self.get_current_offset() 
        tz_config = timezone(timedelta(hours=db_offset))
        current_time = int(datetime.now(tz_config).timestamp())
        
        try:
            db_conn = pool_live.get_connection()
            cursor = db_conn.cursor(dictionary=True, buffered=True)
            query = """ 
                SELECT 
                    booking_id, 
                    booking_timestamp, 
                    pickup_timestamp, 
                    return_timestamp, 
                    pickup_location_code, 
                    return_location_code, 
                    customer_id, 
                    is_cancelled 
                FROM wp_car_rental_bookings 
                WHERE return_timestamp >= %s AND is_cancelled = 0 
            """
            cursor.execute(query, (current_time,))
            db_bookings_details = cursor.fetchall()

            for booking in db_bookings_details:
                b_id = booking['booking_id']
                p_dt = datetime.fromtimestamp(booking['pickup_timestamp'], tz=tz_config)
                r_dt = datetime.fromtimestamp(booking['return_timestamp'], tz=tz_config)
                b_dt = datetime.fromtimestamp(booking['booking_timestamp'], tz=tz_config)
                
                self.current_bookings[b_id] = {
                    'booking_id': b_id,
                    'booking_timestamp': b_dt.strftime("%d-%m-%Y"),
                    'pickup_timestamp': p_dt.strftime("%d-%m-%Y"),
                    'pickup_hour_timestamp': p_dt.strftime("%H:%M"),
                    'return_timestamp': r_dt.strftime("%d-%m-%Y"),
                    'return_hour_timestamp': r_dt.strftime("%H:%M"),
                    'pickup_location_code': booking['pickup_location_code'],
                    'return_location_code': booking['return_location_code'],
                    'customer_id': booking['customer_id'],
                    'is_cancelled': booking['is_cancelled'],
                }
                
        except mysql.connector.Error as err:
            return f"Database error: {err}", 500
        finally:
            if 'cursor' in locals() and cursor:
                cursor.close()
            if 'db_conn' in locals() and db_conn:
                if db_conn.is_connected():
                    db_conn.close()
                else:
                    db_conn = None
>__Method Dissection: get_booked_customers(self) - example

Granular Code Dissection customer_ids = {booking['customer_id'] for booking in self.current_bookings.values()}: collect all unique customer IDs (no duplicates). Uses a set comprehension to extract customer IDs from all active bookings. The mathematical properties of a Python set automatically filter out duplicate entries, creating a clean list of unique customer IDs. ΓÇó format_strings = ','.join(...): Dynamically builds a comma-separated list of placement tokens (%s, %s, ...) tailored to the exact number of unique customer IDs. ΓÇó WHERE customer_id IN ({format_strings}): Runs an optimized bulk query to fetch data for all required customers at once. This replaces slow, iterative queries with a single database request. ΓÇó cursor.execute(query, tuple(customer_ids)): Passes the target IDs as a sanitized tuple. This ensures the database engine can parse and bind parameters safely, protecting the application against SQL injection risks. ΓÇó customers_map = {row['customer_id']: row for row in customers_rows}: Converts the database rows into an in-memory lookup map indexed by customer_id, ensuring instant lookup performance during data merging. ΓÇó for booking_id, booking in self.current_bookings.items():: Iterates through the master reservation list. ΓÇó customers_map.get(c_id): Looks up the customer profile instantly in RAM at O(1) complexity. ΓÇó self.booked_customers[booking_id] = { ... }: Links the complete customer profileΓÇöincluding name, contact info, and billing addressΓÇödirectly to the booking ID, preparing the dataset for use by downstream modules. ΓÇó self.booked_customers[booking_id] = {'first_name': 'Client', 'last_name': 'Necunoscut'}: Data Integrity Fallback. If a booking references a customer ID that has been removed from the database, it logs a placeholder profile instead of throwing an error, keeping the dashboard running smoothly. Systemic Role within the Application This method functions as the system's Bulk Customer Ingestion Pipeline. Its main job is to solve the high-latency \(N+1\) database query bottleneck. Instead of connecting to the database to find customer details for every reservation row in a loop, it aggregates unique IDs and extracts all profiles in a single query. It links customer profiles to bookings completely in RAM, allowing the Smart Fleet Dispatcher and automated contract pipelines to load user data without lag.

def get_booked_customers(self):
        try:
            if not self.current_bookings:
                return
            db_conn = pool_live.get_connection() 
            cursor = db_conn.cursor(dictionary=True)
            customer_ids = {booking['customer_id'] for booking in self.current_bookings.values()}
            format_strings = ','.join(['%s'] * len(customer_ids))
            query = f"""
                SELECT 
                    customer_id, first_name, last_name, birthdate, 
                    street_address, city, state, zip_code, country, phone, email 
                FROM wp_car_rental_customers 
                WHERE customer_id IN ({format_strings})
            """
            cursor.execute(query, tuple(customer_ids))
            customers_rows = cursor.fetchall()
            customers_map = {row['customer_id']: row for row in customers_rows}
            for booking_id, booking in self.current_bookings.items():
                c_id = booking['customer_id']
                cust = customers_map.get(c_id)
    
                if cust:
                    self.booked_customers[booking_id] = {
                        'booking_id': booking_id,
                        'customer_id': cust['customer_id'],
                        'first_name': cust['first_name'],
                        'last_name': cust['last_name'],
                        'birthdate': cust['birthdate'],
                        'street_address': cust['street_address'],
                        'city': cust['city'],
                        'state': cust['state'],
                        'zip_code': cust['zip_code'],
                        'country': cust['country'],
                        'phone': cust['phone'],
                        'email': cust['email'],
                    }
                else:
                    self.booked_customers[booking_id] = {'first_name': 'Client', 'last_name': 'Necunoscut'}
    
        except mysql.connector.Error as err:
            print(f"Eroare în get_booked_customers: {err}")
        finally:
            if 'cursor' in locals() and cursor: cursor.close()
            if 'db_conn' in locals() and db_conn and db_conn.is_connected():
                db_conn.close()
>__Advanced Architectural Sync Optimization Layer

One of the Core Distributed State Reconciler and Sync Gateway of the enterprise ERP application is the class method 'get_unified_home_data', one of the class's main methods that will be called throughout the application. It solves a massive, real-world architectural challenge: merging fluid, remote transactional data structures (WordPress e-commerce) with persistent operational states managed inside a local on-premise relational schema (Flask ERP). Rather than running heavy, uncoordinated background fetch tasks or dealing with race conditions across platform boundaries, this function runs a highly efficient, multi-step pipeline. It executes a local lookahead query sweep to isolate active transaction identifiers, uses string interpolation injections to fetch batch data from remote sources, and applies an ultra-fast \(O(1)\) memory mapping technique to resolve missing fields. Granular Code Dissection Phase 1: Temporal Initialization and Workspace Stabilization ΓÇó self.current_bookings = {} / self.reservations = {}: Explicitly flushes the internal class-level state repositories at the start of the synchronization process. This prevents old data states from bleeding into the current request loop, keeping data completely isolated during sequential runs. ΓÇó current_time = int(datetime.now(timezone.utc).timestamp()) - 86400: Implements a precise temporal lookback sliding window. It takes the current UTC timestamp and subtracts exactly 24 hours in seconds (86400). This technique builds a safety net into data collection routines. It accounts for potential data delays, server clock drift, and seasonal daylight saving adjustments between the remote WordPress web host and the local enterprise script environment, ensuring no recent orders are dropped during sync sweeps. ΓÇó today_str = ...: Compiles a localized, uniform string timestamp using the standard %d-%m-%Y mask configuration. This string matches the custom date layout stored in the database, allowing the system to run accurate server-side comparisons without parsing overhead. Phase 2: Local Lookahead Isolation Sweep ("The Master Injection Pump") ΓÇó forced_ids_set = set(): Instantiates a memory-optimized hash set to accumulate active booking transaction keys across multiple operational domains. Queries the local database table contracts_data to locate all unclosed, active rentals where is_completed is 0 or NULL (meaning the vehicle is physically out on the road). ΓÇó forced_ids_set.add(str(int(row['booked_id']))): Coerces the query outputs through integer parsing before converting them into string arrays, storing the results directly inside the set data type. Using a hash set guarantees absolute tracking uniqueness by stripping out duplicates automatically on the fly. Scans the manual administrative adjustments table booking_overrides. ΓÇó STR_TO_DATE(override_return_date, '%d-%m-%Y') >= STR_TO_DATE(%s, '%d-%m-%Y'): Overcomes a common structural issue where dates are stored inside database rows as generic text fields (VARCHAR). Because plain text strings sort alphabetically rather than chronologically, running typical inequality operations (like checking if a date is greater than or equal to another) would return corrupted data lists. The database utility STR_TO_DATE parses these custom string structures into real, comparable datetime primitives on the fly. This ensures the database engine filters entries with absolute chronological precision against our variable baseline (today_str). Targets the contract_extensions relational dataset to pull transaction codes for active contract addendums or scheduling extensions that match or exceed the current calendar date bounds. ΓÇó forced_ids_str = ",".join(...) if forced_ids_set else "0": Merges the populated string set into a clean, comma-separated data token string. If the set contains no records, it sets a fallback string of "0". This acts as an explicit structural safety rule, ensuring that when the value is injected into a SQL IN block later, it points to a non-existent ID key rather than throwing a fatal syntax crash due to empty parameters. Phase 3: Comprehensive Multi-Table Ingestion Blueprint Advanced Multi-Table LEFT JOIN Architecture: Connects to the remote server instance pool, executing a massive multi-join extraction statement over 6 interdependent tabular schemas. The Injection Isolation Isolation Strategy: Combining traditional SQL positional parameter tokens (%s) with standard python text formatting methods (.format()) can often cause severe query compilation errors. The template engine frequently confuses %s formats with placeholder indicators, leading to runtime failures. This script solves that problem using a clean separation approach: it uses standard Python .format(ids=...) string substitution to inject the compiled transaction keys into the safe string template chunk, while passing the dynamic integer timestamp safely through positional driver routing parameters (current_time). ΓÇó AND (b.return_timestamp >= %s OR b.booking_id IN ({ids})): Implements a powerful data protection guard. Standard synchronization routines only fetch future or active rental lines (return_timestamp >= current_time), which means any old or historically closed transactions are automatically pruned from the fetch window. However, if a dispatcher modifies an old reservation, applies an extension, or changes an active contract locally, that older record would be skipped by a basic time filter. Including the OR b.booking_id IN (...) clause forces the remote query engine to return those specific rows regardless of their age, ensuring total consistency between platforms. ΓÇó GROUP BY b.booking_id: Flattens duplicate row mappings caused by multi-layered options tables, ensuring each booking resolves to a single row entry. Phase 4: Validation Filtration & State Hydration Loops ΓÇó if b_id in self.blocked_ids: continue: Implements an instantaneous O(1) entry lookup check. If a remote booking ID matches an entry in our local blacklist set, the processing loop skips it immediately, preventing blocked or fraudulent records from entering the local dashboard context. ΓÇó datetime.fromtimestamp(..., tz=tz_config): Decodes raw Unix timestamp values into real, timezone-aware datetime instances matched exactly to the company's operating region. ΓÇó self.current_bookings[b_id] = { ... }: Builds a structured in-memory hash map repository layout, indexing rows directly by their transaction keys to enable fast constant-time lookup performance for downstream tasks. ΓÇó row['pickup_location_real'] or row['pickup_location_code']: Implements fallback logical conditions (or). If the relational join returns an empty station name string from the locations reference table, the system uses the raw location string code instead, ensuring the output stays valid and descriptive under all conditions. Phase 5: Local Vehicle Metric Merging Pipeline ΓÇó b_ids = list(self.current_bookings.keys()): Gathers all successfully synchronized reservation IDs from our memory cache layer. ΓÇó format_strings = ','.join(...): Computes an array of replacement tokens (%s, %s, ...) tailored to the exact length of the keys array list. ΓÇó query_new = f"... WHERE booked_id IN ({format_strings})": Runs an optimized bulk query against our local database instance events_details_added. This fetches physical plate assignments for all active bookings in a single batch, completely avoiding slow, iterative database requests. In-Memory Relational Stitching Loop: Iterates through the localized plate allocation rows, extracting the booking ID and license plate string. ΓÇó if b_id in self.current_bookings:: Runs a quick check against our cache map. If it finds a match, it injects the license plate data directly into the matching record layout entirely in RAM. This pattern merges separate remote and local data tables at ultra-fast constant-time complexity speeds, completely eliminating the need for complex SQL database links. Systemic Role within the Application This method acts as the core Distributed Sync Engine and State Aggregator for the entire platform architecture. Its role within the software lifecycle is vital: 1. Platform Boundary Abstraction: It bridges the gap between different technical environments. It acts as a smart gateway that unifies remote WordPress booking data and local operational adjustments into a clean, single-source-of-truth data object. 2. Cascading Synchronization Control: By leveraging a smart lookahead sweep, it ensures that transactions modified via manual backend edits or legal extensions are tracked accurately across servers, eliminating data blind spots. 3. Core Dashboard Performance Driver: It builds a complete, normalized lookup cache map entirely in RAM, preventing the web controller from making slow, repetitive database calls. This keeps data operations exceptionally fast and directly powers the Smart Fleet Dispatcher, ensuring the interactive front-end calendar UI can render live schedules instantly.

def get_unified_home_data(self):
        self.current_bookings = {} 
        self.reservations = {}
        db_offset = self.get_current_offset() 
        tz_config = timezone(timedelta(hours=db_offset))
        current_time = int(datetime.now(timezone.utc).timestamp()) - 86400
        today_str = datetime.now(tz_config).strftime("%d-%m-%Y")

        forced_ids_set = set()
        try:
            db_new = pool_new.get_connection()
            cursor_new = db_new.cursor(dictionary=True)
            
            # Pasul A: ID-urile din contractele deschise (mașini aflate fizic pe traseu)
            cursor_new.execute("""
                SELECT booked_id FROM contracts_data WHERE is_completed IS NULL OR is_completed = 0
            """)
            for row in cursor_new.fetchall():
                if row['booked_id']: 
                    forced_ids_set.add(str(int(row['booked_id'])))

            cursor_new.execute("""
                SELECT external_booked_id FROM booking_overrides 
                WHERE override_return_date IS NOT NULL AND override_return_date != ''
                  AND STR_TO_DATE(override_return_date, '%d-%m-%Y') >= STR_TO_DATE(%s, '%d-%m-%Y')
            """, (today_str,))
            for row in cursor_new.fetchall():
                if row['external_booked_id']: 
                    forced_ids_set.add(str(int(row['external_booked_id'])))

            cursor_new.execute("""
                SELECT booked_id FROM contract_extensions 
                WHERE new_return_date IS NOT NULL AND new_return_date != ''
                  AND STR_TO_DATE(new_return_date, '%d-%m-%Y') >= STR_TO_DATE(%s, '%d-%m-%Y')
            """, (today_str,))
            for row in cursor_new.fetchall():
                if row['booked_id']: 
                    forced_ids_set.add(str(int(row['booked_id'])))
                    
        except Exception as e:
            print(f"Error gathering local active IDs for cascade sync: {e}")
        finally:
            if 'db_new' in locals() and db_new.is_connected():
                cursor_new.close()
                db_new.close()

        placeholders_str = ','.join(['%s'] * len(forced_ids_str.split(',')))

        try:
            db_live = pool_live.get_connection()
            cursor_live = db_live.cursor(dictionary=True)

            query_live = """
                SELECT 
                    b.booking_id, b.booking_timestamp, b.pickup_timestamp, b.return_timestamp, 
                    b.pickup_location_code, b.return_location_code, b.customer_id, b.is_cancelled,
                    i.model_name AS car_name, i.item_id AS car_id,
                    l1.location_name AS pickup_location_real,
                    l2.location_name AS return_location_real,
                    c.first_name, c.last_name, c.phone, c.email, c.birthdate,
                    c.street_address, c.city, c.state, c.zip_code, c.country
                FROM wp_car_rental_bookings b
                LEFT JOIN wp_car_rental_booking_options o ON b.booking_id = o.booking_id
                LEFT JOIN wp_car_rental_items i ON o.item_sku = i.item_sku
                LEFT JOIN wp_car_rental_locations l1 ON b.pickup_location_code = l1.location_code
                LEFT JOIN wp_car_rental_locations l2 ON b.return_location_code = l2.location_code
                LEFT JOIN wp_car_rental_customers c ON b.customer_id = c.customer_id
                WHERE b.is_cancelled = 0 
                  AND (b.return_timestamp >= %s OR b.booking_id IN ({ids}))
                GROUP BY b.booking_id
            """.format(ids=placeholders_str)

            query_arguments = (current_time,) + tuple(forced_ids_str.split(','))
            
            cursor_live.execute(query_live, query_arguments)
            results = cursor_live.fetchall()

            for row in results:
                b_id = row['booking_id']
                if b_id in self.blocked_ids:
                    continue

                p_dt = datetime.fromtimestamp(row['pickup_timestamp'], tz=tz_config)
                r_dt = datetime.fromtimestamp(row['return_timestamp'], tz=tz_config)
                b_dt = datetime.fromtimestamp(row['booking_timestamp'], tz=tz_config)
                
                self.current_bookings[b_id] = {
                    'booking_id': b_id,
                    'booked_id': b_id,
                    'booking_timestamp': b_dt.strftime("%d-%m-%Y"),
                    'pickup_timestamp': p_dt.strftime("%d-%m-%Y"),
                    'return_timestamp': r_dt.strftime("%d-%m-%Y"),
                    'pickup_hour_timestamp': p_dt.strftime("%H:%M"),
                    'return_hour_timestamp': r_dt.strftime("%H:%M"),
                    
                    # ... restul câmpurilor tale (pickup_location, car_name, etc.) ...
                    'pickup_location': row['pickup_location_real'] or row['pickup_location_code'],
                    'return_location': row['return_location_real'] or row['return_location_code'],
                    'pickup_location_code': row['pickup_location_code'],
                    'return_location_code': row['return_location_code'],
                    'car_name': row['car_name'] or 'Model Necunoscut',
                    'first_name': row['first_name'] or 'Client',
                    'last_name': row['last_name'] or 'Necunoscut',
                    'phone': row['phone'] or 'N/A',
                    'email': row['email'] or 'N/A',
                    'birthdate': row['birthdate'],
                    'street_address': row['street_address'],
                    'city': row['city'],
                    'state': row['state'],
                    'zip_code': row['zip_code'],
                    'country': row['country'],
                    'customer_id': row['customer_id']
                }
                self.reservations[b_id] = self.current_bookings[b_id]
                
        finally:
            if 'db_live' in locals() and db_live.is_connected():
                cursor_live.close()
                db_live.close()

        if self.current_bookings:
            try:
                db_new = pool_new.get_connection()
                cursor_new = db_new.cursor(dictionary=True)
                b_ids = list(self.current_bookings.keys())
                format_strings = ','.join(['%s'] * len(b_ids))
                
                query_new = f"SELECT booked_id, car_number FROM events_details_added WHERE booked_id IN ({format_strings})"
                cursor_new.execute(query_new, tuple(b_ids))

                for row in cursor_new.fetchall():
                    b_id = row['booked_id']
                    plate = row['car_number']
                    if b_id in self.current_bookings:
                        self.current_bookings[b_id]['car_plate'] = plate
                        self.current_bookings[b_id]['car_number'] = plate 
                        self.reservations[b_id]['car_plate'] = plate
            finally:
                if 'db_new' in locals() and db_new.is_connected():
                    cursor_new.close()
                    db_new.close()
>__Architectural State Merging & Event Chronology Engine

One of the most important and powerful functions of the engine behind the application is `get_processed_reservations`. This function acts as the Central State Resolution and Timeline Chronology Pipeline for the platform. It handles the structural data integration challenge common in distributed booking engines: combining fresh, fluid reservation streams from remote instances with active physical modifications, legal contractual extensions, and custom administrative overrides found in the local enterprise dataset. Rather than treating scheduling actions as plain text entries, this function compiles fragmented operational data lines into discrete, immutable lifecycle events (start and end). It applies a multi-layered priority system ("The Golden Hierarchy") to resolve conflicts in RAM, chronologically indexing data objects to drive the visual drag-and-drop dispatcher calendar. Granular Code Dissection Phase 1: Local Context Allocation & Target Database Snapshot Ingestion ΓÇó data, overrides, include_active_contracts=False: The parameter signature ingests the unified GetData state layer (data), a dictionary collection containing live operator modifications (overrides), and a boolean flag (include_active_contracts) that selectively filters out fulfilled rentals from active dispatch timelines. ΓÇó contracted_ids = {} / latest_ext = {}: Sets up temporary lookup map containers within the execution framework. This configuration ensures O(1) lookup speeds when cross-referencing states during later loop operations. ΓÇó db_conn = pool_new.get_connection(): Pulls a persistent socket thread directly from the native connection pool manager, reducing connection initialization lag. Snapshot Retrieval and Data Window Compacting. ΓÇó SELECT booked_id, is_completed... FROM contracts_data: Runs an explicit database query projection. By selecting 7 deterministic columns instead of using wildcards (SELECT *), it bypasses heavy binary tracking markers or long signature strings stored elsewhere in the table, protecting application memory allocations from unnecessary overhead. ΓÇó contracted_ids[int(row['booked_id'])] = row: Converts database keys to integers to prevent data mismatch bugs. It indexes each row dictionary under its true primary identifier key in application memory. The Windowed Core Aggregation Query: Implements an optimized group-by lookup filter. If a fleet operator extends a rental agreement multiple times across a vehicle's route, the tracking table accumulates multiple rows for that single transaction ID. Running a basic join query would fetch old, outdated extensions, corrupting the return time schedule metrics downstream. The subquery expression WHERE id IN (SELECT MAX(id)... GROUP BY booked_id) isolates only the most recent extension entry row for each unique reservation ID, resolving data conflicts at the database engine level. ΓÇó events_details = cursor.fetchall(): Gathers assigned physical vehicle assets and operational plate attributes from the local layout. Defensive Cleanup Safeguards: Catches runtime transaction errors silently, printing explicit logs to developer tracking streams. The resource cleanup layer closes open memory search handles and releases active sockets back to the system pool, preventing connection leaks. Phase 2: In-Memory Map Flattening & Blocklist Filtration ΓÇó bid = int(r.get('booked_id') or r.get('booking_id') or 0): Normalizes differences across schemas by fallback evaluating variation naming patterns, converting the final key structure into a standard clean integer primitive. ΓÇó if bid in data.blocked_ids: continue: Performs an ultra-fast entry lookup match against our local blacklist set repository. If a transaction code matches, the line execution skips it immediately, preventing blocked, cancelled, or fraudulent entries from entering the active schedule context. ΓÇó r_copy = r.copy(): Implements memory isolation boundaries. Creating an explicit element copy instead of copying variable references prevents down-stream property modifications from mutating the underlying master cache values inside the data class object. ΓÇó if bid and c.get('is_completed') is None:: Identifies active, uncompleted agreements where vehicles are physically deployed on the lot. It flattens the dataset by merging active contracts over loose incoming records, ensuring the system prioritizes legal operational profiles. ΓÇó merge_lists_into_new(...): Helper function that merges the unified reservation values map with local data columns (events_details) based on the tracking primary key parameter (booked_id). This processes the rows at low computational complexity limits. Phase 3: Dynamic Override Application Layer ΓÇó if int(bid) in overrides:: Cross-references the active dataset item against the manual adjustments registry inside application memory at O(1) constant time speed. Defensive Override Injection Guards (if ov.get('...')): This logic applies strict verification filters. If a backend administrator uses the administrative screen to modify a specific valueΓÇölike extending a return dateΓÇöwhile leaving secondary parameters like vehicle model blank, a naive override function would inject None primitives over valid data strings, causing data loss. The condition if ov.get('key'): ensures the system overrides target fields only when it detects a real, true structural replacement value. If the input is empty or null, it leaves the baseline data untouched, preserving information across system boundaries. Phase 4: Resolution Cascades & Structural Property Enforcement Operational Normalization Baselines: Gathers standard vehicle allocation variables directly from the enriched object wrapper data stream to prepare for the data reconciliation pipeline. The Hierarchical Resolution Priority Pipeline: This logic manages complex data priority rules across multiple platform layers. When information varies across different system tables, the application runs a multi-tiered evaluation tree to determine the true operational parameters: o Tier 1 (Base Layer): Uses the default values pulled from the WordPress remote database webhook payload. o Tier 2 (Contract Layer): If a formal agreement exists in contracted_ids, the system overwrites the values with the official signature timestamps, updating grand_total metrics with verified totals. o Tier 3 (Extension Layer): If a late vehicle extension is logged in latest_ext, this programmatic addendum overrides previous contract values, moving scheduling dates to match the new drop-off station constraints. o Tier 4 (Absolute Override Priority): The conditional check if bid not in overrides acts as the final system rule. Manual desk adjustments override all automatic server assignments, ensuring back-office corrections are never replaced by old database synchronization scripts. Phase 5: Timeline Splitting Engine & Structural Event Casting Lifecycle Splitter Optimization Strategy: A typical car rental database stores check-in and check-out parameters as a single row containing a start date column and an end date column. Trying to pass these double-date database rows directly to a chronological UI calendar requires complex tracking logic, slowing down frontend rendering speeds. How the Engine Fixes This: This engine splits each single booking record into two completely separate timeline event blocks. ΓÇó start_item['status'] = 'start': Extracts pick-up variables, labels them as an independent start lifecycle event block, and calculates a uniform timeline object key using datetime.strptime. This cleanly isolates deployment metrics from return variables. ΓÇó end_item['status'] = 'end': Generates the matching vehicle drop-off event object wrapper block. ΓÇó display_items.sort(key=lambda x: x['display_date']): Runs a final sorting pass on the compiled array using the unified display_date key attributes. This transforms unorganized relational database rows into a perfectly ordered chronological event list, ready for instant use by frontend rendering layers. Systemic Role within the Application This function operates as the central State Aggregator and Chronological Timeline Dispatcher Component for the platform. Its role within the software application lifecycle is vital: 1. Platform Boundary Abstraction: It acts as a smart gateway that unifies loose remote data streams, local fleet details, contract modifications, and manual overrides into a single database schema block. 2. The Interactive Calendar Driver: By splitting single rows into separate start and end events and pre-sorting them chronologically, it removes computation overhead from the browser. This allows the front-end interactive calendar to render timelines instantly without lag. 3. Algorithmic Conflict Resolution: It applies strict priority evaluation trees to guarantee absolute consistency across all modules. This ensures automated contract generators, billing processors, and fleet coordinators always pull from a single verified data source.

def get_processed_reservations(data, overrides, include_active_contracts=False):
    blocked_ids = data.blocked_ids
    contracted_ids = {} 
    latest_ext = {}
    events_details = []
    
    db_conn = None
    cursor = None

    try:
        db_conn = pool_new.get_connection() 
        cursor = db_conn.cursor(dictionary=True)
        cursor.execute("SELECT booked_id, is_completed, rent_contract_number, return_timestamp, return_hour_timestamp, return_location, total_amount FROM contracts_data")
        for row in cursor.fetchall():
            contracted_ids[int(row['booked_id'])] = row

        cursor.execute("""
            SELECT booked_id, new_return_date, new_return_hour, new_return_location 
            FROM contract_extensions 
            WHERE id IN (SELECT MAX(id) FROM contract_extensions GROUP BY booked_id)
        """)
        for row in cursor.fetchall():
            latest_ext[int(row['booked_id'])] = row
            
        cursor.execute("SELECT booked_id, car_number FROM events_details_added")
        events_details = cursor.fetchall()

    except Exception as err:
        print(f"Silent Error in get_processed_reservations: {err}")
    finally:
        if cursor: cursor.close()
        if db_conn and db_conn.is_connected(): db_conn.close()

    combined_map = {}
    for r in data.reservations.values():
        bid = int(r.get('booked_id') or r.get('booking_id') or 0)
        if bid in data.blocked_ids:
            continue
        if bid:
            r_copy = r.copy()
            r_copy['booked_id'] = bid
            combined_map[bid] = r_copy

    for c in data.contracted_bookings_data.values():
        bid = int(c.get('booked_id') or c.get('booking_id') or 0)
        if bid and c.get('is_completed') is None:
            combined_map[bid] = c.copy()

    all_events_updated = merge_lists_into_new(list(combined_map.values()), events_details, 'booked_id')

    for bid, event in all_events_updated.items():
        if int(bid) in overrides:
            ov = overrides[int(bid)]
            if ov.get('override_car_name'): event['car_name'] = ov['override_car_name']
            if ov.get('override_car_plate'): 
                event['car_plate'] = ov['override_car_plate']
                event['registration_plate'] = ov['override_car_plate']
            if ov.get('override_pickup_date'): event['pickup_timestamp'] = ov['override_pickup_date']
            if ov.get('override_pickup_hour'): event['pickup_hour_timestamp'] = ov['override_pickup_hour']
            if ov.get('override_pickup_location'): event['pickup_location'] = ov['override_pickup_location']
            if ov.get('override_return_date'): event['return_timestamp'] = ov['override_return_date']
            if ov.get('override_return_hour'): event['return_hour_timestamp'] = ov['override_return_hour']
            if ov.get('override_return_location'): event['return_location'] = ov['override_return_location']
            if ov.get('override_total_price'): event['grand_total'] = ov['override_total_price']

    display_items = []
    for event in all_events_updated.values():
        bid = int(event.get('booked_id') or 0)
        r_date = event.get('return_timestamp')
        r_hour = str(event.get('return_hour_timestamp') or '00:00').strip()
        r_loc  = event.get('return_location')

        if bid in contracted_ids:
            event['rent_contract_number'] = contracted_ids[bid]['rent_contract_number']
            if contracted_ids[bid].get('total_amount'):
                event['grand_total'] = contracted_ids[bid]['total_amount']
            if bid not in overrides:
                r_date = contracted_ids[bid]['return_timestamp']
                r_hour = contracted_ids[bid]['return_hour_timestamp']
                r_loc  = contracted_ids[bid]['return_location']
            if bid in latest_ext:
                r_date = latest_ext[bid]['new_return_date']
                r_hour = latest_ext[bid]['new_return_hour']
                r_loc  = latest_ext[bid]['new_return_location']

        event['return_timestamp'] = r_date
        event['return_hour_timestamp'] = r_hour
        event['return_location'] = r_loc
        
        is_done = contracted_ids[bid]['is_completed'] if bid in contracted_ids else None

        if (include_active_contracts or (bid not in contracted_ids)) and is_done is None:
            p_date = event.get('pickup_timestamp')
            p_hour = str(event.get('pickup_hour_timestamp') or '00:00').strip()
            if p_date:
                start_item = event.copy()
                start_item['status'] = 'start'
                start_item['is_completed'] = is_done
                try:
                    start_item['display_date'] = datetime.strptime(f"{p_date} {p_hour}", "%d-%m-%Y %H:%M")
                except:
                    start_item['display_date'] = datetime.strptime(p_date, "%d-%m-%Y")
                display_items.append(start_item)

        if is_done is None: 
            if r_date:
                end_item = event.copy()
                end_item['status'] = 'end'
                end_item['is_completed'] = is_done
                try:
                    end_item['display_date'] = datetime.strptime(f"{r_date} {r_hour}", "%d-%m-%Y %H:%M")
                except:
                    end_item['display_date'] = datetime.strptime(r_date, "%d-%m-%Y")
                display_items.append(end_item)

    display_items.sort(key=lambda x: x['display_date'])
    return display_items
>__Identity Management, Cryptographic Authentication, & Session Lifecycle Architecture

This module implements the core administrative security infrastructure of the ERP platform. It features cryptographically isolated user registration, parameterized relational lookup validation, and a thread-safe state login enforcement workflow. Rather than offloading authentication management to high-overhead Object-Relational Mappers (ORMs), these control layers leverage direct connection pooling configurations to guarantee optimal response latencies under heavy backend traffic. Granular Code Dissection - register() Mechanics: ΓÇó Instantiates the Flask-WTF validation form engine context frame. It explicitly monitors the submit action payload data array. If it intercepts a truthy state on the explicit form field cancellation control trigger (form.cancel.data), it executes an early operational exit redirecting the system worker thread straight to the homepage route, bypassing all secondary structural executions. ΓÇó The execution branch triggers only when an incoming HTTP POST payload clears all predefined frontend validation protocols. It requests a low-latency relational data socket handle from the internal enterprise allocation pool (pool_new). By initializing a buffered=True structural cursor, the program downloads the target lookup result rows array directly into application RAM space. This prevents database server connection thread locking and isolates verification logic from transaction data streams. ΓÇó Checks if the lookup dictionary contains a matching email key. If a record is found, the system runs an early exit routine: it frees up cursor cache rows, flashes a validation warning alert to the client dashboard, and redirects the routing context frame straight to the login endpoint, preventing account duplication anomalies. ΓÇó Implements an advanced, high-entropy asymmetric cryptographic protection pipeline layer. It takes the plain-text credentials string and feeds it to the Werkzeug security processing module. The generator applies a PBKDF2 (Password-Based Key Derivation Function 2) hashing transformation algorithm using an integrated SHA-256 derivation routine. This is reinforced by a cryptographically random, 16-character salt token sequence. This design pattern completely avoids storing raw plain-text credentials in the persistence layer, neutralizing malicious rainbow-table exposures or structural internal database leaks. ΓÇó Formulates a highly secure parameterized SQL state modification statement. By routing values (val) as distinct positional binding arrays separated from the query schema layout text (sql), it leverages the internal database driver's query compilation parsing engine to completely block all remote SQL Injection payload attempts. The .commit() directive ensures absolute data writing consistency across the persistence layer. ΓÇó Re-queries the active table thread instance using positional parameters to pull the newly generated system record, loading it into local memory parameters to extract system-generated primary index attributes. ΓÇó Intercepts system relational data failures, instantly returning a safe debug tracking string alongside a definitive server HTTP 500 error code. The finally context block runs defensive boundary verification scans to confirm memory variables exist before safely closing cursors and returning the socket handles to the connection pool, preventing connection leaks. ΓÇó Hydrates the cryptographically signed Flask browser session storage dictionary with verified identification keys (id, username, loggedin). This shifts the authenticated profile state straight to the user client interface context layout before executing a successful dispatch routing update. Granular Code Dissection - login() Mechanics: ΓÇó Instantiates validation form layers to isolate post request streams. It grabs a thread-isolated database link from the internal ERP instance manager pool and issues a parameterized SQL validation select projection. This isolates the required authentication entry record based on the input credentials string while maintaining structural parameter sanitization parameters. ΓÇó Evaluates the lookup result dictionary output layout. If the search returns an empty reference value, it flags a clean account warning message across the frontend web client, blocks routing access, and redirects execution straight back to the login view frame checkpoint. ΓÇó Runs a cryptographic verification check via Werkzeug's check_password_hash(). It extracts the salt properties and derivation rules directly from the compiled database string, processes the input text through the same mathematical derivation steps, and compares the resulting hash signatures. If the signatures do not match, it flashes a security warning alert and blocks system dashboard entry, protecting the app from brute-force access attempts. ΓÇó Once all verification layers pass, the code logs the user into the server session cache by populating transaction security markers. It updates client browser structures with signed metadata properties and routes the administrative user straight into the system workspace management dashboard view layout. Systemic Role within the Application This suite of endpoints functions as the application's central Identity Access Management (IAM) and Cryptographic Authentication Subsystem. Its operational profile within the ERP architecture is vital: 1. Security Isolation Boundary Layer: It serves as a secure gateway that restricts entry to administrative dashboards, ensuring that internal resourcesΓÇölike the interactive dispatch calendar, pricing cascade calculations, and reporting networksΓÇöcan only be accessed by authenticated managers. 2. Stateful Session Management Consistency: By leveraging cryptographically signed cookie session frameworks combined with secure database parameter bindings, it builds a reliable, drift-free tracking process across multi-step browser tasks without introducing latency. 3. Data Integrity Protection: It prevents credential leaks at the persistence layer by handling passcodes through advanced salt extraction and hashing models (PBKDF2/SHA-256). This setup keeps the architecture safe from external data parsing threats or unauthorized access drops.

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.cancel.data: 
        return redirect(url_for('home'))
    if form.validate_on_submit():
        email = form.email.data
        try:
            db_conn = pool_new.get_connection() 
            cursor = db_conn.cursor(dictionary=True, buffered=True)
            cursor.execute('SELECT email FROM admins WHERE email = %s', (email,))
            account = cursor.fetchone()
            if account:
                cursor.close()
                flash("You've already signed up with that email, log in instead!")
                return redirect(url_for('login'))
                
            hash_and_salted_password = generate_password_hash(
                form.password.data,
                method='pbkdf2:sha256',
                salt_length=16
                )
            sql = 'INSERT INTO admins (email, password, name) VALUES (%s, %s, %s)'
            val = (form.email.data, hash_and_salted_password, form.name.data)
            cursor.execute(sql, val)
            db_conn.commit()
            cursor.execute('SELECT * FROM admins WHERE email = %s', (email,))
            account = cursor.fetchone()

        except mysql.connector.Error as err:
            return f"Database error: {err}", 500
        finally:
            # Returning connection to the pool so it stays "alive"
            if 'cursor' in locals(): cursor.close()
            if 'db_conn' in locals(): db_conn.close()

        session['loggedin'] = True
        session['id'] = account['id']
        session['username'] = account['name']
        return redirect(url_for('home'))
    return render_template("register.html", form=form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user_email = form.email.data
        
        try:
            db_conn = pool_new.get_connection() 
            cursor = db_conn.cursor(dictionary=True, buffered=True)
            cursor.execute('SELECT * FROM admins WHERE email = %s', (user_email,)) 
            account = cursor.fetchone()
        except mysql.connector.Error as err:
            return f"Database error: {err}", 500
        finally:
            if 'cursor' in locals(): cursor.close()
            if 'db_conn' in locals(): db_conn.close()

        if not account:
            flash("That email does not exist, please try again!")
            return redirect(url_for('login'))
        elif not check_password_hash(account['password'], form.password.data):
            flash("Password incorrect, please try again!")
            return redirect(url_for('login'))
        else:
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['name']
            return redirect(url_for('home'))
    return render_template("login.html", form=form)
>__Local Administrative Overrides & Overlapping Temporal Fleet Conflict Detection

This phase of the documentation maps out the structural data validation layers of the system. It examines get_booking_overrides, an administrative snapshot reference manager, and check_car_conflict, a dynamic temporal intersection checker that blocks double-booking anomalies on the lot. Granular Code Dissection - get_booking_overrides() Mechanics: ΓÇó Allocates an empty local lookup mapper context dictionary (overrides). It calls the target thread-isolated ERP database connection resource (pool_new). By instantiating a custom buffered=True structural dictionary cursor, the system reads all modifications, scheduling alterations, and temporary swaps from disk, storing them cleanly inside the application network buffer. ΓÇó Runs a broad data extraction scan across the local adjustments repository table. It processes the list array rows through an inline processing loop. ΓÇó Hash Table Mapping Reduction: It parses the target table connection identifier (external_booked_id) through an explicit int() primitive transformer. This identifier maps the complete data dictionary block directly onto the overrides tracking map. This structural shift avoids expensive nested array linear loops later on, allowing any secondary subsystem down the execution chain to query manual data changes at ultra-fast O(1) computational complexity bounds. ΓÇó Intercepts low-level data errors and prints explicit system alert messages. The finally context block runs standard context safety checks to verify active memory objects before closing the cursor and safely returning the open database socket back to the pool, preventing resource exhaustion. Granular Code Dissection - check_car_conflict() Mechanics: ΓÇó Instantiates chronological timeline metrics by applying the standard data method datetime.combine(). It merges loose dates and localized time parameters from the front-end user forms into immutable, high-precision datetime object points (new_start, new_end), establishing a clean baseline for overlap check calculations. ΓÇó Spins up the complete localized state ingestion architecture entirely in RAM. This hydrates the system context by populating blacklist data structures, live reservations, pending items, and normalized contractual snapshots across the execution framework. ΓÇó Runs a single query pass to fetch the manual backend overrides directory cache from the local ERP instance pool, closing memory handles and connection sockets defensively in the finally block to prevent leaks. ΓÇó Performs an explicit, multi-source array list concatenation sweep in application memory. It combines pending records, active e-commerce rows, and unfulfilled agreements into a single list layout (all_bookings). This array compaction bypasses fragmented layout layers, setting up a single data loop context. ΓÇó Loops over the unified reservation collection array. It applies early exit validation blocks: if the booking ID matches an entry in our local blocklist hash set at O(1) complexity, it skips the check entirely via the continue statement, as blocked or cancelled vehicles are considered fully available. It also uses an identity bypass gate if b_id == booking_id: continue to stop the transaction from testing for conflicts against its own matching database entry. Extracts baseline scheduling metrics, localized hourly timestamps, and assigned license plate string variables directly from the checked operational object dictionary item wrapper. ΓÇó Applies the Golden Hierarchy Conflict Overwrite Guard. It scans the manual modifications registry in application memory at O(1) speed. If an administrative manager has manually adjusted a reservation's dates or vehicle license plates, this conditional checker instantly overwrites the baseline values with those specialized override inputs. This guarantees the conflict calculation engine processes actual, real-world deployment metrics. ΓÇó Triggers a deeper structural match check only if the assigned vehicle plate string exactly matches the candidate target plate value (current_plate == plate). It compiles text date components into precise datetime objects (db_start, db_end) using the uniform %d-%m-%Y %H:%M layout template mask. ΓÇó The Mathematical Timeline Intersection Algorithm: To calculate whether two separate allocation blocks overlap on a calendar grid, a naive loop checks individual date units sequentially, which strains backend resources. This function uses a more efficient mathematical intersection check: two time ranges overlap if the candidate start point falls ahead of the active end threshold (new_start < db_end) AND the candidate end window reaches past the active start boundary (new_end > db_start). If this intersection equation resolves to true, it indicates a scheduling collision. The engine instantly flags the conflict by returning the colliding transaction ID integer value (b_id), running an early exit that skips further loop calculations. If it encounters string formatting errors, the except: block safely passes over them. If the loop runs through the complete database collection without matching a scheduling collision, it returns a boolean value of False. This tells the calling module that the vehicle allocation is completely safe, allowing the system to proceed with data writing. Systemic Role within the Application This method functions as the core Temporal Fleet Protection and Anti-Collision Validation Engine. Its role within the software architecture is critical for business safety. Before an operator can reassign a vehicle on the interactive dashboard or generate an automated contract, the backend routes the request parameters through this validator. By running an optimized mathematical intersection check over unified memory caches, it prevents double-booking errors. This ensures absolute fleet tracking accuracy, prevents data overlaps, and protects rental lot managers from accidental double allocations.

def get_booking_overrides():
    """
    Fetches car name/plate overrides from the local Flask database.
    Returns a dictionary: {booked_id: {'override_car_name': '...', 'override_car_plate': '...'}}
    """
    overrides = {}
    try:
        db_conn = pool_new.get_connection() 
        cursor = db_conn.cursor(dictionary=True, buffered=True)
        cursor.execute('SELECT * FROM booking_overrides')
        # Transform list into a dictionary for O(1) lookup speed
        for row in cursor.fetchall():
            overrides[int(row['external_booked_id'])] = row
    except mysql.connector.Error as err:
        return f"Database error: {err}", 500
    finally:
        if 'cursor' in locals(): cursor.close()
        if 'db_conn' in locals(): db_conn.close()
    return overrides
    

def check_car_conflict(booking_id, plate, p_date_obj, p_time_obj, r_date_obj, r_time_obj):
    new_start = datetime.combine(p_date_obj, p_time_obj)
    new_end = datetime.combine(r_date_obj, r_time_obj)

    data = GetData()
    data.get_local_blocked_ids()
    data.get_current_bookings()
    data.get_pending_bookings()
    data.get_data_for_contracts()
    overrides = {}

    try:
        db_conn = pool_new.get_connection()
        cursor = db_conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM booking_overrides")
        overrides = {row['external_booked_id']: row for row in cursor.fetchall()}
    finally:
        if db_conn and db_conn.is_connected():
            cursor.close(); db_conn.close()

    all_bookings = list(data.pending_bookings.values()) + \
                   list(data.current_bookings.values()) + \
                   [b for b in data.contracted_bookings_data.values() if b.get('is_completed') is None]

    for b in all_bookings:
        b_id = int(b.get('booked_id') or b.get('booking_id') or 0)
        if b_id in data.blocked_ids:
            continue
        if b_id == booking_id: continue
        p_date = b.get('pickup_timestamp')
        p_hour = str(b.get('pickup_hour_timestamp') or '00:00').strip()
        r_date = b.get('return_timestamp')
        r_hour = str(b.get('return_hour_timestamp') or '00:00').strip()
        current_plate = b.get('registration_plate') or b.get('car_number') or b.get('car_plate')

        if b_id in overrides:
            ov = overrides[b_id]
            if ov.get('override_pickup_date'): p_date = ov['override_pickup_date']
            if ov.get('override_pickup_hour'): p_hour = ov['override_pickup_hour']
            if ov.get('override_return_date'): r_date = ov['override_return_date']
            if ov.get('override_return_hour'): r_hour = ov['override_return_hour']
            if ov.get('override_car_plate'): current_plate = ov['override_car_plate']

        if current_plate == plate:
            try:
                fmt = '%d-%m-%Y %H:%M'
                db_start = datetime.strptime(f"{p_date} {p_hour}", fmt)
                db_end = datetime.strptime(f"{r_date} {r_hour}", fmt)
                if new_start < db_end and new_end > db_start:
                    return b_id 
            except: continue
            
    return False
>__Visual Scheduling Layer, Multi-Route View Controller, & High-Speed Asynchronous API Synthesis

This architectural module contains the core scheduling orchestration controllers of the application: the show_calendar render view controller and the get_events high-speed RESTful JSON API data pipeline. Together, these systems function as the operational control room of the car rental enterprise. This core scheduling module exposes the critical calendar orchestration pipeline: the show_calendar render view controller and the high-speed get_events RESTful JSON API data pipeline. The backend system serves as a centralized telemetry hub, streaming structural reservation objects directly to a high-concurrency client-side JavaScript processing engine tasked with dynamically plotting the interactive fleet allocation interface. By consuming our pre-optimized cache aggregator subsystems (GetData) and passing data vectors through execution duration tracking wrappers (@monitor_speed), these layers transform flat, distributed transactional rows into highly interactive visual operational views. This structure achieves near-instant responsive rendering times without requiring the front-end layout to perform heavy calculation loops. Granular Code Dissection - show_calendar() Mechanics: ΓÇó Maps two separate URL route patterns to a single python handler function to implement an elegant polymorphic fall-through endpoint. The first route pattern handles clean, base root hits (/calendar/), while the secondary path uses strict type parameters (<int:year>/<int:month>) to capture direct chronological coordinate signals. The entire entry point is wrapped inside the custom @monitor_speed decorator. This acts as a telemetry shield, tracking runtime execution length to log latency alerts on the host terminal if complex backend merges hit systemic drops. ΓÇó Evaluates security variables inside the encrypted browser cookie file layout. If the session key checks out, it spins up an instance of the GetData state aggregator layer. This triggers a sequential extraction cascade: it downloads the entry blocklist, fires the unified distributed database injection pump to pull records across system borders, and loads manual back-office administrative desk revisions (overrides) straight into local system structures. ΓÇó Executes boundary fallback logic. If a fleet operator hits the base calendar URL route without inputting specific chronological path variables, the program captures the current server clock coordinates via date.today(), dynamically assigning current calendar values to initialize the rendering interface template context. ΓÇó Passes all extracted caching repositories through the master timeline timeline splitting engine. By setting the explicit flag parameter include_active_contracts=True, it forces the underlying filter systems to keep active vehicle agreements active on the grid layout, allowing fleet dispatchers to track active cars currently deployed on the lot. Prepares an optimized native hash set wrapper container (event_dates_in_month). It loops over the compiled event list array, performing strict, multi-type filtration guards to isolate and skip already completed or archived files. This ensures that only active operational data enters the calendar viewing grid window. ΓÇó Implements transactional date parsing wrapped inside a defensive validation block. The script passes text inputs through datetime.strptime to parse strings into structured date objects using the uniform %d-%m-%Y mask. Algorithmic Map Reduction: It filters results by testing whether dates match the currently requested calendar window. If an event falls inside the target window, the code executes a format reduction (.strftime('%Y-%m-%d')) and loads the standardized ISO string directly into the event_dates_in_month hash set. Using a set guarantees data uniqueness by automatically dropping duplicate date hits. If it hits unexpected text formatting anomalies, the except ValueError: guard catches the error cleanly, bypassing corrupted entries without interrupting the layout loop. ΓÇó Instantiates Python's native structural standard HTMLCalendar rendering engine layout, setting the internal operational baseline to start weeks on MONDAY. Calling .formatmonth() compiles an raw HTML structural layout string representing the target month calendar framework, with header indicators stripped out via configuration flags. ΓÇó Handles cyclical modular arithmetic transformations to drive interface navigation controls. If the active monthly context steps backward past January (month = 1), the evaluation logic loops variables to select December (12) of the preceding year. Conversely, if it advances past December (month = 12), it resets variables to step into January (1) of the subsequent chronological period, preventing out-of-bounds routing failures. ΓÇó Passes all compiled variables into Flask's Jinja2 template rendering system engine. It maps the raw HTML table grid layout string, dynamic navigation pointer strings, title structures, and a list translation of our date set straight to the front-end layout dashboard. If authentication validation checks fail, the application runs an early exit redirecting execution straight back to the login screen. Systemic Role in the Application This controller acts as the core Visual Grid Blueprint Engine. Its main role is to render the high-level monthly calendar overview layout on the dashboard. By calculating a unique set of date strings representing active operations and passing them to the front-end layout shell, it provides immediate, visual indicators for days that have active bookings. This layout allows backend workers and dispatchers to spot peak periods at a glance, click on specific days to examine operational activity, and navigate through historical fleet records without lagging the host web server. Granular Code Dissection - get_events() Mechanics: ΓÇó Registers a dedicated asynchronous API endpoint path mapping target string parameters (<date>) straight into a RESTful data query stream. It evaluates tracking keys in session storage right away. If an unauthenticated user or an external scanner hits the route, the system drops the connection immediately, returning a clean, secure JSON error string alongside an explicit HTTP 401 Unauthorized status flag code. ΓÇó Spins up the complete localized state ingestion architecture entirely in RAM. It downloads entry blocklists, runs distributed cross-server data merges, pulls backend modifications, and structures information into a unified, pre-sorted chronological event collection array. ΓÇó Builds an in-memory verification set (contracted_ids) by pulling active contract keys from the local database instance in a single query pass. By parsing parameters through explicit type conversion checks (int(row[0])) and loading them into a native set, it creates an internal hash lookup table. This optimizes future row validation steps down to ultra-fast O(1) constant-time speeds, protecting database channels from connection starvation during heavy request spikes. ΓÇó Allocates an array collection list to accumulate matching items. It loops over the processed reservations, checking metadata markers to filter out and skip completed historical logs, ensuring that only active operational profiles enter the calculation layer. ΓÇó Converts the tracking item's native datetime stamp into a uniform ISO data string configuration wrapper. It matches this key against the incoming endpoint route parameter string (date). If the strings match, the logic extracts the underlying transaction integer identifier code (bid) and checks the lifecycle state flag (status == 'start') to classify the operation. ΓÇó Constructs a lightweight, decoupled data transfer object (DTO) dictionary schema for each matching record item. Conditional Field Assembly: It dynamically matches data fields to the transaction classification state: if is_start passes, it selects pickup hours and origin station fields; if it fails, it pulls return timings and drop-off stations instead. It maps a clean transaction identifier code label ('PRD' for Delivery, 'RTN' for Return) and checks if the booking ID exists inside our pre-loaded contracted_ids verification set at O(1) constant-time speed. The completed object map is loaded into the tracking list array payload. Systemic Role in the Application: This API endpoint serves as the Asynchronous Live Data Pump for the Dashboard Interface. Instead of forcing the application to perform heavy, slow page reloads when an administrative manager clicks on different days across the calendar UI, the front-end javascript layer fires an unblocked background fetch() request straight to this endpoint. Because the API processes operations entirely in memory using pre-compiled hash maps and linear filtering, it streams back a serialized JSON data payload instantly. This powers the Smart Fleet Dispatcher UI calendar, allowing the client dashboard to load operational vehicle details, update customer contacts, render registration plates, and draw direct digital contract action links instantly on the fly without lagging the host server. These two controllers operate as a decoupled, asynchronous Server-Client pipeline. The 'show_calendar' view functions as a macro-scheduler, processing time-series arrays to pass a structural list of active operational dates ('event_dates') into the Jinja rendering layer for calendar grid generation. Conversely, the 'get_events' controller acts as a low-latency, high-concurrency RESTful JSON API. Triggered asynchronously via client-side JavaScript 'fetch' cycles upon user day-selection, it queries the identical persistence layers and streams targeted daily payloadsΓÇöenriched with relational validation flags like 'has_contract'ΓÇöto dynamically update the UI state without shifting page context.

@app.route('/calendar/')
@app.route('/calendar/<int:year>/<int:month>')
@monitor_speed
def show_calendar(year=None, month=None):
    if 'loggedin' in session:
        data = GetData()
        data.get_local_blocked_ids()
        data.get_unified_home_data() 
        overrides = get_booking_overrides() 
        if year is None or month is None:
            today = date.today()
            year, month = today.year, today.month
        all_reservations = get_processed_reservations(data, overrides, include_active_contracts=True)
        event_dates_in_month = set()

        for booking in all_reservations:
            is_done = booking.get('is_completed')
            if is_done is not None and str(is_done) != "" and str(is_done) != "None":
                continue
            try:
                pickup_date = datetime.strptime(booking['pickup_timestamp'], '%d-%m-%Y').date()
                return_date = datetime.strptime(booking['return_timestamp'], '%d-%m-%Y').date()
                if pickup_date.year == year and pickup_date.month == month:
                    event_dates_in_month.add(pickup_date.strftime('%Y-%m-%d'))
                if return_date.year == year and return_date.month == month:
                    event_dates_in_month.add(return_date.strftime('%Y-%m-%d'))
            except ValueError:
                continue

        cal = calendar.HTMLCalendar(calendar.MONDAY)
        month_html = cal.formatmonth(year, month, withyear=False)
        prev_month = month - 1
        prev_year = year
        if prev_month == 0: prev_month = 12; prev_year -= 1
        next_month = month + 1
        next_year = year
        if next_month == 13: next_month = 1; next_year += 1
        # print('events in month - calendar:', event_dates_in_month)
        return render_template('calendar.html',
                            month_html=month_html,
                            prev_url=f'/calendar/{prev_year}/{prev_month}',
                            next_url=f'/calendar/{next_year}/{next_month}',
                            current_month_year=f'{calendar.month_name[month]} {year}',
                            event_dates=list(event_dates_in_month))
    return redirect(url_for('login'))


@app.route('/api/events/<date>')
@monitor_speed
def get_events(date):
    if 'loggedin' not in session:
        return jsonify({"error": "Unauthorized"}), 401   
    data = GetData()
    data.get_local_blocked_ids()
    data.get_unified_home_data()
    overrides = get_booking_overrides()
    all_reservations = get_processed_reservations(data, overrides, include_active_contracts=True)
    contracted_ids = set()
    try:
        db_conn = pool_new.get_connection()
        cursor = db_conn.cursor()
        cursor.execute("SELECT booked_id FROM contracts_data")
        contracted_ids = {int(row[0]) for row in cursor.fetchall()}
    finally:
        if 'db_conn' in locals() and db_conn.is_connected():
            cursor.close(); db_conn.close()

    events_for_day = []
    for booking in all_reservations:
        is_done = booking.get('is_completed')
        if is_done is not None and str(is_done) != "" and str(is_done) != "None":
            continue
        booking_date_iso = booking['display_date'].strftime('%Y-%m-%d')
        if booking_date_iso == date:
            bid = int(booking.get('booked_id', 0))
            is_start = booking.get('status') == 'start'
            event = {
                'car_name': booking.get('car_name', 'N/A'),
                'customer_name': f"{booking.get('first_name', '')} {booking.get('last_name', '')}".strip(),
                'phone': booking.get('phone', '---'),
                'plate': booking.get('registration_plate') or booking.get('car_number') or '---',
                'booked_id': bid,
                'time': booking.get('pickup_hour_timestamp') if is_start else booking.get('return_hour_timestamp'),
                'location': booking.get('pickup_location') if is_start else booking.get('return_location'),
                'type': 'PRD' if is_start else 'RTN',
                'details': booking.get('observations', ''),
                'has_contract': bid in contracted_ids # <--- Asta e cheia pentru link
            }
            events_for_day.append(event)
    return jsonify(events_for_day)
>__Distributed State Liquidation & Transactional Resource Allocation Mutators

This section provides an exhaustive technical analysis of the state liquidation infrastructure (block_reservation) and the real-time resource re-allocation processor (swap_manual_booking). These endpoints act as transactional write gateways that enforce database consistency and preserve fleet tracking integrity across platform boundaries. Granular Code Dissection: block_reservation(bid) Mechanics: ΓÇó Requests an active socket connection thread handle from the local allocation pool (pool_new). It issues an optimized INSERT IGNORE command statement to push the target reservation identifier (bid) straight onto the local blacklist table local_blocked_bookings. ΓÇó Performance Optimization Strategy: In concurrent management setups, an operator might click the eviction trigger multiple times if they experience browser latency. A raw INSERT statement would crash on a duplicate primary key violation, throwing an unhandled exception and breaking the execution lifecycle thread. Including the keyword modifier IGNORE instructs the database engine to catch unique index collisions silently and discard the duplicate step, maintaining application stability. ΓÇó Runs two clean deletion commands sequentially inside the same transactional workspace block. It purges old license plate link records from events_details_added and strips out manual back-office administrative desk corrections inside the overrides ledger booking_overrides. Once .commit() runs successfully, it flushes modifications to disk, flashes a visibility notification layout alert to the front-end interface dashboard, and releases the vehicle back into the pool. ΓÇó Intercepts database connection exceptions silently, logging low-level driver failures straight to backend terminal streams. The finally context block runs defensive checking validations to confirm memory variables exist before closing cursors and returning the socket handles to the connection pool, preventing connection leaks. Systemic Role in the Application 1. This controller acts as the system's Distributed Transaction Liquidation Engine. 2. Its main job is to process cancellations, fraud alerts, or high-priority manual blocks. When an operator triggers this route, the engine isolates the targeted booking ID code and executes a destructive database cascade. By instantly scrubbing the registration plate linkages from tracking models and blacklisting the ID key, it prevents ghost bookings from locking up vehicles. 3. This directly powers the Smart Fleet Dispatcher, ensuring that the interactive front-end calendar UI can clear data cells instantly and make vehicles fully available for new rental requests. Real-Time Resource Re-Allocation Processor: swap_manual_booking() ΓÇó Registers a data transaction POST request routing handler, protected by structural speed telemetry trackers and standard session login verification checks. ΓÇó Pulls user parameters directly from the browser context form data stream. It grabs the unique transaction code signature (booking_id) along with a concatenated payload text string containing vehicle indicators (new_plate_and_model). ΓÇó Runs an architectural boundary safety verification scan. Front-end dropdown layouts often stream merged compound strings (such as "Dacia Logan|IS 99 ABC") to reduce client network packet sizes. Trying to pass this raw compound text straight into standardized database fields would corrupt relational tracking columns. This checker checks for the pipe separator character (|). If it passes validation, it uses .split('|') to parse the string into clean data slices, running .strip() to scrub off leading or trailing whitespace blocks to ensure text consistency. ΓÇó Claims an active connection thread from the database instance manager pool. It issues a highly optimized MySQL Upsert command layout (INSERT ... ON DUPLICATE KEY UPDATE). If this is the first time the specific booking has been modified, it writes a new override row cleanly. If an override record already exists for that reservation key, the database engine captures the unique collision signal and mutates the vehicle model and plate fields on the fly in a single operation, preventing primary key violations. ΓÇó Executes a secondary, synchronized data upsert statement across the events_details_added inventory layout table to propagate change vectors across system borders. This locks the new registration plate string parameter directly to the operational row index identifier, executing .commit() to write updates across the persistence layer in a single transaction block. ΓÇó Catches transaction process drops cleanly, dumping failure alerts to diagnostic telemetry outputs. The finally context cleans up system resources safely and redirects the routing context frame straight back to the detailed dashboard view workspace panel linked to the updated reservation. Systemic Role in the Application 1. This controller acts as the system's Real-Time Fleet Swap and Resource Allocation Mutator. 2. Its main job is to process unexpected operational changes at the physical rental deskΓÇösuch as a vehicle breaking down, a client requesting an instant model upgrade, or an operator adjusting scheduling boxes directly on the calendar interface. By separating command updates from live e-commerce synchronization networks and routing them through idempotent upsert statements, it instantly reassigns vehicle names and registration plate configurations entirely in RAM. 3. This powers the Smart Fleet Dispatcher calendar view, allowing the client dashboard to reflect physical inventory re-allocations instantly while ensuring that downstream legal contract engines pull updated vehicle information.

@app.route("/block-reservation/<int:bid>", methods=["POST"])
@monitor_speed
def block_reservation(bid):
    if 'loggedin' not in session:
        return redirect(url_for('login'))

    try:
        db_conn = pool_new.get_connection()
        cursor = db_conn.cursor()
        cursor.execute("INSERT IGNORE INTO local_blocked_bookings (booked_id) VALUES (%s)", (bid,))
        cursor.execute("DELETE FROM events_details_added WHERE booked_id = %s", (bid,))
        cursor.execute("DELETE FROM booking_overrides WHERE external_booked_id = %s", (bid,))
        db_conn.commit()
        flash(f"Rezervarea #{bid} a fost blocată și mașina a fost eliberată!", "warning")
        
    except Exception as e:
        print(f"Eroare la blocare: {e}")
        flash("Eroare tehnică la eliberarea mașinii.", "danger")
    finally:
        if 'db_conn' in locals() and db_conn.is_connected():
            cursor.close(); db_conn.close()
    return redirect(url_for('home'))


@app.route("/swap-manual-booking", methods=["POST"])
@monitor_speed
def swap_manual_booking():
    if 'loggedin' not in session:
        return redirect(url_for('login'))

    raw_data = request.form.get('new_plate_and_model') # "Model|Placa"
    booking_id = request.form.get('booking_id')

    if raw_data and '|' in raw_data:
        parts = raw_data.split('|')
        new_model = parts[0].strip()
        new_plate = parts[1].strip()
        
        try:
            db_conn = pool_new.get_connection() 
            cursor = db_conn.cursor()
            sql = '''
                INSERT INTO booking_overrides 
                (external_booked_id, override_car_name, override_car_plate)
                VALUES (%s, %s, %s)
                ON DUPLICATE KEY UPDATE 
                override_car_name = VALUES(override_car_name),
                override_car_plate = VALUES(override_car_plate)
            '''
            cursor.execute(sql, (booking_id, new_model, new_plate))
            cursor.execute("""
                INSERT INTO events_details_added (booked_id, car_number)
                VALUES (%s, %s)
                ON DUPLICATE KEY UPDATE car_number = VALUES(car_number)
            """, (booking_id, new_plate))
            
            db_conn.commit()
        except Exception as e:
            print(f"Swap error: {e}")
        finally:
            if 'db_conn' in locals() and db_conn.is_connected():
                cursor.close(); db_conn.close()
 
    return redirect(url_for('view_event_details', event_id=booking_id))
>__Distributed State Dashboard Orchestrator & Multi-Tenant Vehicle Fleet Compliance Alerting Engine

This section provides an exhaustive technical analysis of the central operations landing controller (home). This routine functions as the master aggregation panel for the platform, orchestrating data fetches across isolated local and remote relational database layers. It resolves runtime naming data changes entirely in application RAM, and executes a multi-attribute matrix timeline check to fire fleet compliance warning alerts before a vehicle sets out on the lot. Granular Code Dissection: Mechanics: ΓÇó Evaluates active session authorization flags before launching data pipelines. If clear, the engine constructs a new GetData aggregator context. This launches a synchronized sequence across database architectures: downloading cancelled transaction blacklist matrices, resolving registration plates, launching lookahead webhook synchronizers, fetching pricing models, and pulling manual back-office administrative updates (overrides) straight into memory. This design completely decouples the web route layer from low-level table lookups. ΓÇó Stabilizes local timezone context by instantiating an absolute date pointer pinned explicitly to Europe/Bucharest. It calculates a dynamic upper lookahead threshold boundary (warning_limit) by appending a 30-day offset interval. This defines a moving chronological window used by compliance checking loops down the pipeline. Requests a connection socket thread from the local database pool. It runs a single inventory lookup pass to extract asset fields from cars_details. ΓÇó The Composite Key Transformation Strategy: To link upcoming operational events with their physical asset compliance statistics, a naive engine would execute nested SQL queries inside loops, slowing down backend performance. This routine solves that bottleneck by constructing a fast Compound Key In-Memory Hash Map (cars_lookup). It merges the car model string with the registration plate string using an underscore separator (f"{car_model}_{car_number}"), mapping the entire asset row data object directly to that composite string slot. This allows any future module to fetch asset variables instantly in memory at O(1) constant-time speed. Transforms database records into a single timeline stream via get_processed_reservations(). It loops through the event items, cross-referencing each booking identifier against our local override repository cache at O(1) speed. ΓÇó Defensive Value Assignment Guards: Implements precise conditional string sanitization checkpoints. If a lot operator alters a vehicle assignment details using administrative interface forms, the manual update is applied directly. The conditional guard structure if ov.get('override_car_name'): ensures that the code overwrites target fields only when it detects a genuine alternative value string. If a field is blank or null inside the overrides lookup, the system skips it, protecting baseline pricing metadata from data corruption. Restricts the output stream by running an immediate date inequality check (>= today_date). This filters out historical rows to keep data payloads lean. It compiles a fallback lookup reference variable string (lookup_key) by matching the event vehicle attributes with the design blueprint pattern used during the initial hash dictionary mapping initialization stage. Instantiates an empty local notification collector list array under the 'alerts' metadata key tag property. If the compound lookup_key hits a successful match inside our pre-loaded cars_lookup map at O(1) speed, the application triggers a specialized fleet compliance scanning routine. ΓÇó The Automated Fleet Maintenance Compliance Checker: The system iterates over 5 critical legal maintenance fields (including ITP technical checkups, RCA liability insurance coverage windows, road vignettes, mechanical revisions, and Casco parameters). If a field contains an active value, the checker processes it safely: if the database row field returns an active string type, it uses datetime.strptime to parse it into a clean date object. ΓÇó The Lookahead Interception Condition: The engine runs a real-time inequality check if dt_obj <= warning_limit:. If any documentation expiration window drops below our pre-calculated 30-day lookahead limit, the system flags the issue instantly. It strips out trailing label tags, cleans up string layouts via .replace(), and appends an explicit uppercase warning reminder containing the exact expiration day directly to the booking payload dictionary (e.g., generating an alert warning tag like "TECHNICAL INSPECTION: 25-08"). This alerts dispatchers right on the operational hub before any keys leave the desk. ΓÇó Compiles and sorts the final event list array sequentially based on their timeline tracking dates. It feeds this data package into Jinja2 templates, rendering the live dashboard view layout on the operator screen. Systemic Role within the Application This endpoint functions as the core Operational Control Hub, Central Workflow Gateway, and Autonomous Fleet Compliance Warning Subsystem for the platform. Its role within the software application lifecycle is vital: 1. Unified Fleet Management View: It acts as the primary cockpit interface for rental lot managers. It pulls data from decentralized server layers and lists all deliveries, vehicle switches, and check-ins for the day chronologically in a single view. 2. Proactive Risk Mitigation: It functions as an automated fleet security shield. By cross-referencing upcoming rental contracts with document validity dates in RAM, it catches upcoming expirations before cars go out. This allows lot managers to pull vehicles for service or renew coverage fields on time, eliminating the risk of traffic fines or uninsured downtime. 3. High-Performance Interface Rendering: By utilizing compound key maps paired with linear data loops, it handles heavy data aggregation tasks entirely in memory. This reduces server network traffic and ensures the core application dashboard responds instantly, even as transaction records and fleet sizes expand.

@app.route("/", methods=['GET'])
@monitor_speed
def home():
    if 'loggedin' not in session:
        return redirect(url_for('login'))

    data = GetData()
    data.get_local_blocked_ids()
    data.get_all_car_plates()
    data.get_unified_home_data() 
    data.get_car_names()      
    data.get_invoices_data()  
    
    overrides = get_booking_overrides()

    now = datetime.now()
    current_year = now.year
    today_date = datetime.now(ZoneInfo("Europe/Bucharest")).date()
    warning_limit = today_date + timedelta(days=30)

    cars_lookup = {}
    try:
        db_conn = pool_new.get_connection() 
        cursor = db_conn.cursor(dictionary=True)
        cursor.execute('SELECT * FROM cars_details')
        for car in cursor.fetchall():
            key = f"{car['car_model']}_{car['car_number']}"
            cars_lookup[key] = car
    except Exception as e:
        print(f"Database error while fetching car alerts: {e}")
    finally:
        if 'db_conn' in locals() and db_conn.is_connected():
            db_conn.close()

    all_events = get_processed_reservations(data, overrides)
    
    events = []
    for e in all_events:
        e_id = int(e.get('booked_id', 0))
        if e_id in overrides:
            ov = overrides[e_id]
            if ov.get('override_car_name'):
                e['car_name'] = ov['override_car_name']

            new_plate = ov.get('override_car_plate')
            if new_plate:
                e['car_number'] = new_plate
                e['car_plate'] = new_plate
                e['registration_plate'] = new_plate

        if e['display_date'].date() >= today_date:
            e['date_group'] = e['display_date'].strftime("%d-%m-%Y")

            plate = e.get('car_number') or e.get('registration_plate') or e.get('car_plate')
            lookup_key = f"{e.get('car_name', 'Unknown')}_{plate or 'NoPlate'}"
            
            e['alerts'] = []
            if lookup_key in cars_lookup:
                car_data = cars_lookup[lookup_key]
                date_fields = ['technical_inspection_validity', 'insurance_validity', 'vignete_validity', 'tehnical_revision_validity', 'casco_insurance_validity']
                for field in date_fields:
                    val = car_data.get(field)
                    if val and val != "N/A":
                        try:
                            dt_obj = val if isinstance(val, date) else datetime.strptime(str(val), '%Y-%m-%d').date()
                            if dt_obj <= warning_limit:
                                label = field.replace('_validity', '').replace('_', ' ').upper()
                                e['alerts'].append(f"{label}: {dt_obj.strftime('%d-%m')}")
                        except: continue
            events.append(e)
    events.sort(key=lambda x: x['display_date'])
    return render_template('daily_events.html', events=events, current_year=current_year)
>__Real-Time Event Details Aggregator, In-Memory Fleet Conflict Evaluator, & Polymorphic Data Normalization Engine

This route handles the comprehensive metadata aggregation, dynamic cross-server field stitching, after-hours option parsing, and hot-swappable vehicle availability calculation for a specific reservation workspace. Rather than rendering static entries straight from a single file, this route acts as a live Operational Context Synthesizer. It queries both localized ERP data tables and remote WordPress environments to compute asset states in RAM, generating clean, human-readable data objects (EUR string metrics) that drive the complex, back-office administration panel. The Mechanics: ΓÇó Evaluates session tracking variables to verify administrative identity. If cleared, it spins up the state infrastructure class (data), loading registration indices and raw data webhooks into application memory layers. ΓÇó Polymorphic Namespace Safety Inspection: The instruction overrides_res if isinstance(...) else overrides_res[0] implements a type execution fallback. If a secondary module returns the overrides reference wrapped as a collection tuple array rather than a plain dictionary, standard indexing lookups would crash the controller. Type validation ensures that the object evaluates cleanly under a single dictionary schema across all code blocks. ΓÇó get_processed_reservations(...): Flattens information contexts into a unified event list array, leaving active vehicle agreements intact on the monitoring tracking timeline. ΓÇó Leverages a Python Iterator Expression Scan (next(...)) to search the array for a transaction code exactly matching the variable segment primitive parameter (event_id). If the search returns an empty reference value, it throws an early exit path to prevent unhandled operational crashes. ΓÇó Defines an immutable string variable parsing format mask (fmt). It parses the target reservation's pickup and return parameters into high-precision timeline boundaries (target_start, target_end). It claims active socket channels from both connection pool instances (pool_live, pool_new) simultaneously to prepare for multi-database queries within the same request worker. ΓÇó The Complex SQL Extension-Aware Relational Database Sweep: This logic handles a classic challenge in car rental systems: computing a vehicle's availability when an active rental has been extended. If a car is out on the lot and the client extends the return date, the original contract row inside contracts_data remains unchanged, which would fool a basic check into thinking the vehicle is free. ΓÇó The Solution: This query runs a nested sub-select join. It isolates the most recent transaction entry from contract_extensions using MAX(id) ... GROUP BY booked_id. It then applies the COALESCE database expression utility function. If an extension exists, COALESCE chooses the new extension parameters (e.new_return_date); if the field is blank, it falls back to the baseline contract timestamps (c.return_timestamp), storing unclosed agreements in memory inside the fresh_returns lookup dictionary at fast O(1) complexity. ΓÇó Iterates over the unified reservation collection list array. It applies early logic bypass gates to skip testing the active file against itself, and ignores standalone deployment event blocks. ΓÇó The Real-Time Parameter Overwrite Guard: If a reservation ID matches a record inside the freshly compiled fresh_returns dictionary, the engine overrides the baseline dates with those updated scheduling numbers on the fly, ensuring it evaluates precise, real-world fleet parameters. Parses the comparison row coordinates into clean datetime items (b_start, b_end). ΓÇó The Intersection Equation: It runs the mathematical overlap equation: if the candidate start threshold falls ahead of the checked end boundary (target_start < b_end) AND the candidate end window reaches past the checked start point (target_end > b_start), a vehicle conflict exists. The system registers that license plate string directly into the busy_plates hash set. This builds a dynamic array of unavailable vehicles for that specific calendar window, ignoring corrupted strings via inline try/except contexts. ΓÇó Fires a relational database join query across the remote WordPress production tables wp_car_rental_booking_options and wp_car_rental_extras using parameterized data selection constraints. ΓÇó Alphanumeric Option Classification Subsystem: The remote website stores client add-on options as disorganized, localized string entries. To convert this loose metadata into a predictable data schema, the processing loop checks row elements using text matching criteria (.upper() and in name). If it encounters string tokens like "WASH" or "SPALARE", it formats the raw decimal input into a clean currency text metric (f"{int(row['price'])} EUR") and maps it straight to the matching dictionary property key tag. This unifies disparate e-commerce attributes across platform borders. ΓÇó Queries billing records directly from the live invoice database table using strict positional parameter tokens. If a row returns, it converts string formatting using convert_string_to_float(), processes the values into a clean integer primitive text string ("X EUR"), and maps it directly onto the 'grand_total' dictionary field property, preventing type resolution drops during vehicle swaps. ΓÇó Inspects the administrative adjustments memory cache map. If it hits an active registration match, the Golden Hierarchy Priority Layer overrides the baseline WordPress data on the fly. It updates vehicle model names and applies modified license plate attributes across all tracking keys (car_number, car_plate, registration_plate), reflecting physical lot adjustments immediately. ΓÇó Precise Interface Typing Normalization: Casts numeric override strings through floating-point primitives (float) before rounding them into clean integer text markers backed by custom currency indicators. It uses strict is not None boundary validation checks to ensure that genuine values of 0 are processed accurately rather than being incorrectly skipped by falsy evaluation rules, ensuring complete cost presentation stability. ΓÇó Surcharge and Financial Totals Overwriting: Formats custom station pickup fees, out-of-hours surcharges, and comprehensive transaction totals directly into clean string markers, ensuring manual adjustments take absolute authority over standard automated figures. Initializes the terminal string render checkpoint tracking label variable ('base_total_display'). It queries the local schema instance events_details_added to fetch back-office administrative notes, child age metrics, and dynamic airport tracking markers (flight_details), updating the unified dictionary context wrapper seamlessly. ΓÇó The Dynamic In-Memory Exclusion Set Filter Pattern: To generate a clean dropdown list of available vehicles that can be swapped into this booking safely, the script pulls the complete company inventory configuration table from cars_details. ΓÇó How the Optimization Works: It processes the table rows through a fast python list comprehension. It runs an element existence check if c['car_number'] not in busy_plates against our pre-compiled collision set. Because busy_plates is structured as a hash table set, checking if a plate is busy runs at instant O(1) constant-time speed. This filters out occupied vehicles on the fly, creating a clean list of completely available vehicles ready for selection. ΓÇó Catches unexpected internal driver exceptions silently. The finally context block guarantees perfect connection cleanup by closing cursors and returning the open database sockets to their respective shared pools (pool_live, pool_new), rendering the unified details page context on the operator screen. Systemic Role within the Application This endpoint functions as the application's central Workspace Integration Hub, Deep Inspection Panel, and Hot-Swappable Vehicle Calculator. Its role within the software architecture is vital: 1. Multi-Platform Information Convergence Panel: It acts as a unified data collector. It combines scattered data rowsΓÇöincluding remote WordPress e-commerce orders, pricing metrics, local administrative overrides, and flight metadata tracking linesΓÇöinto a single presentation layout. 2. Autonomous Dynamic Fleet Swapping Driver: It runs complex time-range overlap calculations and multi-extension checking rules directly in RAM. By filtering out occupied plates at O(1) complexity, it generates a clean list of completely available vehicles that can be safely swapped into the reservation without risking scheduling conflicts. 3. Comprehensive Cost Transformation Interface: It acts as a data standardizer. It parses loose, alphanumeric add-on strings and currency totals, converting them into clean, standardized text tags ("X EUR"). This provides the admin interface with a solid, conflict-free data context, allowing operators to execute instant vehicle switches and coordinate lot logistics smoothly

@app.route("/event-details/<int:event_id>")
@monitor_speed
def view_event_details(event_id):
    if 'loggedin' not in session:
        return redirect(url_for('login'))
    data = GetData()
    data.get_all_car_plates()
    data.get_unified_home_data() 
    overrides_res = get_booking_overrides()
    overrides = overrides_res if isinstance(overrides_res, dict) else overrides_res[0]
    all_reservations = get_processed_reservations(data, overrides, include_active_contracts=True)
    
    event = next((item for item in all_reservations if int(item.get('booked_id', 0)) == event_id), None)
    
    if not event:
        flash("Evenimentul nu a fost g─âsit!")
        return redirect(url_for('home'))
    fmt = '%d-%m-%Y %H:%M'
    busy_plates = set()
    try:
        target_start = datetime.strptime(f"{event['pickup_timestamp']} {event.get('pickup_hour_timestamp', '00:00')}", fmt)
        target_end = datetime.strptime(f"{event['return_timestamp']} {event.get('return_hour_timestamp', '00:00')}", fmt)

        db_live = pool_live.get_connection()
        cursor_live = db_live.cursor(dictionary=True)
        db_new = pool_new.get_connection()
        cursor_new = db_new.cursor(dictionary=True)

        cursor_new.execute("""
            SELECT c.booked_id, 
                   COALESCE(e.new_return_date, c.return_timestamp) as final_return_date,
                   COALESCE(e.new_return_hour, c.return_hour_timestamp) as final_return_hour
            FROM contracts_data c
            LEFT JOIN (
                SELECT booked_id, new_return_date, new_return_hour
                FROM contract_extensions
                WHERE id IN (SELECT MAX(id) FROM contract_extensions GROUP BY booked_id)
            ) e ON c.booked_id = e.booked_id
            WHERE c.is_completed IS NULL OR c.is_completed != 1
        """)
        fresh_returns = {int(row['booked_id']): row for row in cursor_new.fetchall()}
        for b in all_reservations:
            b_id = int(b.get('booked_id', 0))
            if b_id == event_id or b.get('status') == 'start': continue
            r_date = b['return_timestamp']
            r_hour = b.get('return_hour_timestamp', '00:00')
            if b_id in fresh_returns:
                r_date = fresh_returns[b_id]['final_return_date']
                r_hour = fresh_returns[b_id]['final_return_hour']
            try:
                plate = b.get('car_plate') or b.get('car_number')
                b_start = datetime.strptime(f"{b['pickup_timestamp']} {b.get('pickup_hour_timestamp', '00:00')}", fmt)
                b_end = datetime.strptime(f"{r_date} {r_hour}", fmt)
                if target_start < b_end and target_end > b_start:
                    busy_plates.add(plate)
            except: continue
        query_extras = "SELECT ex.extra_name, ex.price FROM wp_car_rental_booking_options bo JOIN wp_car_rental_extras ex ON bo.extra_sku = ex.extra_sku WHERE bo.booking_id = %s"
        cursor_live.execute(query_extras, (event_id,))
        for row in cursor_live.fetchall():
            name = row['extra_name'].upper()
            price_val = f"{int(row['price'])} EUR"
            if 'WASH' in name or 'SPALARE' in name: event['carwash_fee'] = price_val
            elif 'DRIVER' in name: event['aditional_driver_fee'] = price_val
            elif 'CHILD SEAT' in name: event['child_seat'] = price_val
            elif 'PACKAGE' in name or '2 CHILD' in name: event['package_child_seat'] = price_val
            elif 'GPS' in name: event['gps'] = price_val
            elif 'INSURANCE' in name: event['insurance_fee'] = price_val
            elif 'PARASIRE TARA' in name: event['crossboarding_fee'] = price_val

        cursor_live.execute("SELECT grand_total FROM wp_car_rental_invoices WHERE booking_id = %s", (event_id,))
        inv = cursor_live.fetchone()
        if inv:
            numeric_val = convert_string_to_float(inv['grand_total'])
            event['grand_total'] = f"{int(numeric_val)} EUR" if numeric_val is not None else inv['grand_total']

        if event_id in overrides:
            ov = overrides[event_id]
            # Swap Car (Nume și Placă)
            if ov.get('override_car_name'): event['car_name'] = ov['override_car_name']
            if ov.get('override_car_plate'): 
                event['car_number'] = ov['override_car_plate']
                event['car_plate'] = ov['override_car_plate']
                event['registration_plate'] = ov['override_car_plate']
            if ov.get('override_aditional_driver_fee') is not None: 
                event['aditional_driver_fee'] = f"{int(float(ov['override_aditional_driver_fee']))} EUR"
            if ov.get('override_crossboarding_fee') is not None: 
                event['crossboarding_fee'] = f"{int(float(ov['override_crossboarding_fee']))} EUR"
            if ov.get('override_package_seats') is not None: 
                event['package_child_seat'] = f"{int(float(ov['override_package_seats']))} EUR"
            if ov.get('override_carwash_fee') is not None: event['carwash_fee'] = f"{ov['override_carwash_fee']} EUR"
            if ov.get('override_child_seat') is not None: event['child_seat'] = f"{ov['override_child_seat']} EUR"
            if ov.get('override_gps') is not None: event['gps'] = f"{ov['override_gps']} EUR"
            if ov.get('override_pickup_fee') is not None: event['pickup_fee'] = f"{ov['override_pickup_fee']} EUR"
            if ov.get('overrides_ah_pickup_fee') is not None: event['afterhours_pickup_fee'] = f"{ov['overrides_ah_pickup_fee']} EUR"
            if ov.get('override_return_fee') is not None: event['return_fee'] = f"{ov['override_return_fee']} EUR"
            if ov.get('overrides_ah_return_fee') is not None: event['afterhours_return_fee'] = f"{ov['overrides_ah_return_fee']} EUR"
            if ov.get('override_total_price') and float(ov['override_total_price']) > 0:
                event['grand_total'] = f"{int(float(ov['override_total_price']))} EUR"

        event['base_total_display'] = event.get('grand_total', '0 EUR')

        cursor_new.execute("SELECT flight_details, child_age, observations FROM events_details_added WHERE booked_id = %s", (event_id,))
        local = cursor_new.fetchone()
        if local: event.update(local)

        cursor_new.execute("SELECT car_model, car_number FROM cars_details")
        all_cars_list = [c for c in cursor_new.fetchall() if c['car_number'] not in busy_plates]

    except Exception as e:
        print(f"Error view_event_details: {e}")
        all_cars_list = []
    finally:
        if 'cursor_live' in locals() and cursor_live: cursor_live.close()
        if 'db_live' in locals() and db_live: db_live.close()
        if 'cursor_new' in locals() and cursor_new: cursor_new.close()
        if 'db_new' in locals() and db_new: db_new.close()

    return render_template('event_details.html', event=event, all_cars_list=all_cars_list)
>__Document Blob Storage Ingestion, Dynamic File-System Sharding, & Idempotent Cleanup Controller Matrix

This architectural layer handles secure multi-part document ingestion, local file-system serialization, metadata mapping, and synchronous cleanups for customer identity payloads. Rather than offloading resource lifecycles to uncontrolled system wrappers, these routers establish explicit Structural Whitelists, execute Idempotent Data Modifications, and leverage atomic cleanup procedures to guarantee absolute consistency between database records and underlying disk blocks. The Mechanics: ΓÇó Instantiates the multi-part cryptographic form rendering engine context frame. If the submit stream detects a cancellation signal event (form.cancel.data), it intercepts execution, short-circuiting routing logic straight back to the transaction hub without running validation checks. ΓÇó Allocates local infrastructure drivers from the local ERP instance connection pool manager (pool_new). It defines ALLOWED_FIELDS, an explicit, hardcoded list array string matrix that acts as a structural validation filter for incoming parameters. ΓÇó The Inbound Form Security Injection Guard: In web architectures processing multipart payload streams (enctype="multipart/form-data"), malicious clients can append unexpected file payload parameters or inject custom multi-part fields into raw HTTP request payloads. If a backend controller loops through these files blindly, passing data blocks straight to internal SQL query builders, the application leaks high-risk SQL Injection or mass-assignment paths. This check verifies that every file field key exists inside the strict ALLOWED_FIELDS array template. If a foreign field name is detected, it skips execution immediately via the continue directive, completely securing data boundaries. ΓÇó Dynamic Sharding Filename Construction: Captures individual incoming multi-part files. To completely eliminate malicious filename tampering (such as an attacker naming an artifact ../../etc/passwd to execute path traversal attacks), the engine discards the user-provided name entirely. It uses os.path.splitext to extract the genuine file extension type token (e.g., ".jpg"), and builds a strict, uniform system name format string mapping the booking code and verified role field directly: f"{booking_id}_{field}{extension}". The file block is written straight onto local disk paths. ΓÇó Dynamic Column Injection Mechanics: Runs a fast server-side query to determine whether a configuration entry already exists for the transaction identifier code inside clients_docs. ΓÇó How the Security Validation Layer Holds: Standard formatting rules strongly warn against using string formatting variables directly inside SQL execution wrappers (f"... {field} = %s"), as this breaks parameter isolation and opens up injection vulnerabilities. However, because the system key variable field has been fully validated against the strict ALLOWED_FIELDS lookup list array right at the start of the loop, it is guaranteed to be a clean database column name. The system can safely construct the query layout text dynamically, using standard positional placeholders to route the filename variable safely. This allows the backend to handle multiple distinct document roles cleanly inside a single code block.

@app.route("/upload-docs/<int:booking_id>", methods=['GET', 'POST'])
@monitor_speed
def upload_docs(booking_id):
    if 'loggedin' in session:
        data = GetData()
        data.get_current_bookings()
        data.get_all_car_plates()
        data.get_car_names()
        data.get_locations_names()
        data.get_booked_customers()
        data.get_data_for_contracts()
        data.get_pending_bookings()
        for booking in data.reservations:
            if booking == booking_id:
                requested_booking = data.reservations[booking]    
        upload_form = UploadPhotos()
        if upload_form.cancel.data: 
            return redirect(url_for('manage_booking', booking_id=booking_id))
        if request.method == 'POST':
            try:
                db_conn = pool_new.get_connection() 
                cursor = db_conn.cursor(dictionary=True, buffered=True)
                
                ALLOWED_FIELDS = [
                    'principal_id_card', 
                    'principal_id_card_back', 
                    'principal_driving_license_front',
                    'secondary_id_card',
                    'secondary_id_card_back',
                    'secondary_driving_license_front'
                ]
                
                for field in request.files:
                    if field not in ALLOWED_FIELDS:
                        continue 
                    
                    photo = request.files[field]
                    if photo and photo.filename != '':
                        extension = os.path.splitext(photo.filename)[1]
                        photo_name = f"{booking_id}_{field}{extension}"
                        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], photo_name))
                        cursor.execute('SELECT 1 FROM clients_docs WHERE booking_id = %s', (booking_id,))
                        exists = cursor.fetchone()
                        if not exists:
                            sql = f'INSERT INTO clients_docs (booking_id, {field}) VALUES (%s, %s)'
                            cursor.execute(sql, (booking_id, photo_name))
                        else:
                            sql = f"UPDATE clients_docs SET {field} = %s WHERE booking_id = %s"
                            cursor.execute(sql, (photo_name, booking_id))             
                        db_conn.commit()
            except mysql.connector.Error as err:
                return f"Database error: {err}", 500
            finally:
                if 'cursor' in locals(): cursor.close()
                if 'db_conn' in locals(): db_conn.close()        
            return redirect(url_for('manage_booking', booking_id=booking_id))
        return render_template("upload_photos.html",
                            form=upload_form, 
                            booking = booking_id,
                            requested_booking=requested_booking)
    return redirect(url_for('login'))
>__Operational Lease Extension Engine & Automated Rental Addendum Processor

Manages the creation of formal contract extensions and dynamic rental addendums. It acts as an In-Memory Predictive Collision Evaluator and Financial Alignment Gateway. When a customer requests to extend their active rental duration, the system cannot simply overwrite the existing contract records, as doing so would destroy historical financial data and distort audit trails. Instead, this endpoint generates an isolated, chronologically grouped entry inside the local transactional database. Before committing this addendum, it dynamically tracks upcoming calendar timelines to ensure the extended period does not cause a vehicle allocation conflict with another booking on the lot. Mechanics: ΓÇó Instantiates the global data access framework (GetData), populating distributed caches, timezone indicators, station configurations, and manual administrative updates entirely in memory. It passes the resulting caches through get_processed_reservations(), setting include_active_contracts=True to retain cars physically out on the lot within the current lookahead window. ΓÇó next(...) Iterator Search Expression: Loops over the unified event list array in RAM. It scans for a record where the primary dictionary ID matching key evaluates to the integer primitive routing identifier variable parameter (booked_id), mapping it straight to event_requested to build the transaction processing data context. ΓÇó Intercepts incoming HTTP POST request streams, passing input fields through strict validation checks. It type-coerces form dates and times into standardized text string parameters using the uniform layouts "%d-%m-%Y" and "%H:%M". ΓÇó The Predictive In-Memory Mock Ingestion Pattern: To evaluate whether a proposed contract extension will cause a scheduling collision further down the timeline, the engine cannot wait to write values to disk first. It isolates the baseline reservation data context by generating a decoupled element copy (event_requested.copy()), creating a temporary In-Memory Mock Target Object (check_event). It injects the proposed extension date and time targets into this mock object on the fly, leaving the rest of the operational fields completely untouched. ΓÇó The Anti-Collision Radar Interception: Passes the mock lookahead object, the active license plate string, and the global reservations cache straight to the helper validator check_collision(). This runs a high-speed mathematical range intersection scanner entirely in memory. If the proposed extension overlaps with an existing future booking (meaning another customer has already reserved that vehicle right after the original lease end threshold), the system intercepts the collision instantly. It flashes an explicit warning layout to the operator screen containing the colliding booking number (conflicting_id) and dates (conflict_period), blocking data writing to protect fleet tracking integrity. If the lookahead radar clears the extension as safe, it claims an active connection socket from the local pool instance. ΓÇó It executes a secure parameterized SQL statement to insert a clean operational addendum row directly into contract_extensions, isolating variables safely through positional parameter tokens to neutralize SQL injection vectors. Calling .commit() saves the updates across the persistence layer, flashing a success notification to the lot operator dashboard and redirecting to the main contract details panel. When an administrative user opens the interface view via an HTTP GET stream, the controller runs a pre-population loop. ΓÇó It parses text fields through datetime.strptime to transform database text rows back into python-native .date() or .time() structural form object formats. It pre-populates the extension form dropdown selectors and fields with the reservation's current values on the fly, ensuring a fluid user experience. ΓÇó Runs a targeted select projection statement against the local contracts_data archive log to pull historical financial constants linked to that contract. It extracts the baseline per-day rental price, pickup fees, and out-of-hours surcharges previously paid at checkout, casting string columns safely to float primitives to prevent mathematical rounding errors. ΓÇó The Daily Pro-Rata Insurance Derivation Algorithm: When computing the incremental cost of a contract extension, front-end javascript pricing calculators need access to individual itemized day rates. While basic parameters like per-day vehicle rental cost are stored as a standalone column (rental_price_day), dynamic insurance options like full casco coverage are typically recorded inside database columns as a cumulative grand total value calculated across the entire initial duration (risk_day). ΓÇó The Math Calculation: This logic derives the precise daily insurance rate on the fly. It reads the total insurance value (total_risk) and divides it mathematically by the initial lease duration integer (initial_days). Including the ternary check if initial_days > 0 else 0 provides an essential zero-division shield, stopping backend calculations from crashing if it processes a corrupted contract row containing zero days. ΓÇó Cleans up active cursors and pooled sockets defensively in the finally block to prevent resource leaks. It converts our internal geographic station data tables into an optimized, string-indexed dictionary map layout (locations_json). ΓÇó Front-End Integration Driving: This multi-layered dictionary layout is passed directly to the client browser template as an inline object map variable (locations_config). This allows the front-end JavaScript engine to scan station boundaries and calculate station-specific drop-off fees or out-of-hours surcharges in real-time as the operator adjusts the extension dates on the fly, completely eliminating high-overhead background request delays. Systemic Role within the Application This controller functions as the system's core Operational Lease Extension Coordinator, Predictive Anti-Collision Shield, and Dynamic Cost Pro-Rata Multiplier. Its role within the software application lifecycle is vital: 1. Autonomous Pre-Commit Timeline Validation: It acts as a predictive scheduling radar. By building temporary mock data items in RAM and passing them through mathematical intersection checks before data commitment, it blocks operators from creating overlapping timelines on the lot, guaranteeing absolute fleet tracking integrity. 2. Itemized Cost-Allocation Extraction: It runs pro-rata arithmetic checks over archived database rows, breaking down cumulative insurance records into clean daily metrics. This provides the user interface with a precise, drift-free financial context to calculate contract extension totals accurately. 3. High-Performance Client Synchronization: By passing entire geographic station price lists directly into the template context layer, it enables real-time front-end cost estimations. This removes calculation lag and updates operator dashboards smoothly without adding communication overhead to the host web server.

@app.route("/create-extension/<int:booked_id>", methods=['GET', 'POST'])
@monitor_speed
def create_extension(booked_id):
    if 'loggedin' not in session:
        return redirect(url_for('login'))
    data = GetData()
    data.get_unified_home_data()
    data.get_locations_names()
    overrides = get_booking_overrides()
    all_reservations = get_processed_reservations(data, overrides, include_active_contracts=True)
    event_requested = next((e for e in all_reservations if int(e['booked_id']) == booked_id), None)
    if not event_requested:
        flash("Eroare: Rezervarea nu a fost g─âsit─â!")
        return redirect(url_for('home'))
    form = ExtensionForm()
    if form.validate_on_submit():
        new_date_str = form.new_date.data.strftime("%d-%m-%Y")
        new_hour_str = form.new_hour.data.strftime("%H:%M")
        check_event = event_requested.copy()
        check_event['return_timestamp'] = new_date_str
        check_event['return_hour_timestamp'] = new_hour_str
        current_plate = event_requested.get('car_number') or event_requested.get('registration_plate')

        collision, conflicting_id, conflict_period = check_collision(check_event, current_plate, all_reservations)
        if collision:
            flash(f"⚠️ Mașina {current_plate} este ocupată de Rezervarea #{conflicting_id} ({conflict_period})!", "danger")
            return render_template('extension_form.html', form=form, event=event_requested, booked_id=booked_id)

        try:
            db_conn = pool_new.get_connection()
            cursor = db_conn.cursor()
            sql = """
                INSERT INTO contract_extensions 
                (booked_id, new_return_date, new_return_hour, new_return_location, extension_price)
                VALUES (%s, %s, %s, %s, %s)
            """
            cursor.execute(sql, (
                booked_id, 
                new_date_str, 
                new_hour_str, 
                form.new_location.data, 
                form.price.data
            ))
            db_conn.commit()
            flash("Actul adițional a fost salvat cu succes!")
            return redirect(url_for('booking_details', booking_id=booked_id))
            
        except Exception as e:
            flash(f"Eroare la salvare: {e}", "danger")
        finally:
            if 'db_conn' in locals() and db_conn.is_connected():
                cursor.close(); db_conn.close()

    if request.method == "GET":
        try:
            form.new_date.data = datetime.strptime(event_requested['return_timestamp'], '%d-%m-%Y').date()
            form.new_hour.data = datetime.strptime(event_requested.get('return_hour_timestamp', '12:00'), '%H:%M').time()
            form.new_location.data = event_requested.get('return_location')
            form.price.data = "0.00"
        except Exception as e:
            print(f"Eroare precompletare: {e}")

    try:
        db_conn = pool_new.get_connection()
        cursor = db_conn.cursor(dictionary=True)
        cursor.execute("""
            SELECT rental_price_day, risk_day, rent_days, return_location,
                   return_fee, return_fee_outside_schedule 
            FROM contracts_data 
            WHERE booked_id = %s
        """, (booked_id,))
        
        row = cursor.fetchone()
        price_day = float(row['rental_price_day'] or 0)
        paid_loc_fee = float(row['return_fee'] or 0)
        paid_ah_fee = float(row['return_fee_outside_schedule'] or 0)
        total_risk = float(row['risk_day'] or 0)
        initial_days = int(row['rent_days'] or 1)
        ins_day = total_risk / initial_days
        orig_loc = row['return_location']
    finally:
        if db_conn.is_connected():
            cursor.close(); db_conn.close()

    locations_json = {str(k): v for k, v in data.all_locations.items()}

    return render_template("extension_form.html", 
                       form=form, 
                       event=event_requested, 
                       booked_id=booked_id, 
                       booking_id=booked_id, 
                       price_per_day=price_day,      
                       insurance_per_day=ins_day, 
                       paid_loc_fee=paid_loc_fee,      
                       paid_ah_fee=paid_ah_fee,        
                       original_location=orig_loc, 
                       locations_config=locations_json)
>__Automated Legal Document Compilation & Cryptographic Image Injection Subsystem

This system layer manages automated document synthesis. It acts as an In-Memory PDF Generation Pipeline and Multipurpose Layout Layout Compactor. Rather than executing slow shell processes or relying on high-overhead external document managers, this function compiles dynamic contract extensions and legally binding addendums completely inside memory buffers (BytesIO). The function handles: 1. Dynamic parameter pulling from foreign exchange settings frameworks. 2. Context-aware, null-safe data aggregation layers. 3. Multi-recipient string formatting standardizations. 4. An automated base64 cryptographic asset decoder that strips signature background elements using ReportLab vector parameters (mask='auto'). Calls the systemic configuration service 'get_current_exchange_settings()' to pull foreign exchange variables directly from memory structures. It type-coerces parameters into float and integer primitives. ΓÇó The Foreign Exchange Cushion Padding Algorithm: To protect company cash flows from the thin spreads between interbank rates and commercial transaction clearing streams during settlement, the engine checks the binary configuration flag use_margin. If checked (use_margin == 1), it multiplies the database base rate by a 1% banking margin protection factor multiplier (1.01). It reads the extension cost row, parses it to a float primitive, and computes the dynamic domestic currency total. This is rounded to two decimal places via round(..., 2), preventing rounding errors from corrupting checkout sheets. ΓÇó The Multi-Tenant Name Reconciliation Strategy: In relational web platforms integrated with remote booking engines, database rows frequently accumulate partial, unvetted, or missing character strings. This can cause text formatting bugs. For instance, if an e-commerce plugin passes an empty field or a textual fallback string like 'None' over system webhooks, printing that value directly onto a contract ruins the document's legal validity. How it Works: This script implements a bulletproof Three-Tier String Fallback Resolution Cascade: Tier 1: It runs an explicit sanitization check str().strip().upper() != 'NONE'. If a valid, real-world customer name string exists in the data class, it locks it down immediately, stripping out unnecessary whitespace padding. Tier 2: If the master name field returns empty, it falls back to harvesting the individual first name and last name text column blocks ('first_name', 'last_name'). It replaces null points with empty placeholders (or ''), cleans the strings using .strip(), and joins them with an explicit space separator (f"{prenume} {nume}"). This reconstructs the customer profile smoothly entirely in RAM. Tier 3 (Absolute Safety Guard): If all database name columns return empty, it assigns a hardcoded corporate profile fallback string ("Client Top Wagen"). This keeps the document generation pipeline running smoothly without hitting unhandled compilation crashes. ΓÇó Type Constraint Enforcement Checkpoints: Forces all downstream template parameters through strict string converters (str()) backed by logical fallback alternatives (or 'N/A'). This design pattern guarantees that the ReportLab text writer never encounters a missing parameter or a NoneType variable. This prevents fatal document generation failures on the host server. ΓÇó Instantiates an unblocked memory data stream container (BytesIO()) to serve as a high-speed virtual file wrapper. It launches the ReportLab drawing layer Canvas, setting page configurations strictly to the A4 standard format structure layout. ΓÇó Vector Layout Mapping: It uses .drawString(x, y, text) to write corporate metadata (such as CUI tax registration codes and trade register indices) across precise geographic coordinates, measuring layout points upward from the paper's bottom-left edge. It draws the corporate identity branding logo graphic via .drawImage(), configures line weight properties, and draws an elegant vector dividing rule (p.line()) across the page to structure the contract layout. ΓÇó Compiles localized runtime date strings using the uniform "%d.%m.%Y" formatting layout mask, centering the main title line smoothly on the page template via .drawCentredString(). ΓÇó The Decoupled Vertical Stacking Loop Engine: Trying to print large blocks of text using individual, hardcoded coordinate calls requires extensive maintenance and slows down backend modifications. This module uses a clean, automated list iteration approach. It packs formatted template text blocks into a clean array list (lines). It then initializes an operational vertical coordinate index pointer (y = 670). As the loop iterates over the array, it writes each line text row at the exact horizontal margin boundary (50), and dynamically shifts the vertical index downward after each pass (y -= 20). This creates perfectly spaced, uniform paragraph line blocks automatically. ΓÇó Renders the company's official management title labels onto the layout grid. It uses .drawImage() to load the administrative signature graphic asset from static disk storage, applying the advanced structural layout flag mask='auto' to automatically filter out background elements and layer the signature cleanly over the page lines. ΓÇó The Asynchronous Base64 Image Decoding Engine: When an administrative operator completes a contract extension on the frontend touchscreen canvas, the customer's handwritten signature paths travel to the backend as a serialized base64 data URL string. ΓÇó How it Works: This script processes the signature string safely: it checks the data type, separates the data headers via .split(',', 1), and runs base64.b64decode to convert the text characters back into an independent binary byte string array. To prevent slow, high-overhead local disk writes, it loads the decoded bytes directly into a virtual memory stream handle (BytesIO(client_sig_bytes)). It wraps this virtual file wrapper inside a ReportLab ImageReader context. This parses out image properties completely in RAM, using the vector parameter mask='auto' to strip background borders instantly. This stamps a clean, transparent digital signature onto the finalized contract template layout, keeping operations fast and efficient. ΓÇó The Structural Fallback Shield Branch: If the base64 decoding string fails due to a network glitch or corrupted data formats, a naive rendering engine would crash the entire worker thread, returning a 500 error code to the user screen. This error handling configuration shields operations: it catches the exception, prints explicit trace logs to backend diagnostic streams, and writes a clean placeholder text tag ("[Semn─âtur─â Digital─â Procesat─â]") right onto the document layout. This allows the system to finalize the transaction successfully under all conditions. Finally, .showPage() renders the page, .save() closes the document, and .seek(0) rewinds the memory stream pointer. This outputs a clean, compiled binary PDF data block ready for use by downstream storage or delivery modules. Systemic Role within the Application This method functions as the system's core In-Memory Legal PDF Contract Compiler, Automated Multipurpose Layout Engine, and Cryptographic Visual Asset Injector. Its role within the software application lifecycle is vital: 1. Zero-Disk Footprint Contract Synthesis: It operates as an absolute data privacy shield. By compiling entire multi-page legal documents and converting digital signature streams completely inside RAM variables (BytesIO), it bypasses the need for high-overhead local disk caching. This completely eliminates data footprint trails and secures customer paperwork from unauthorized folder scraping. 2. The Core Engine for Document Generation: It handles the automated compilation of custom contract extensions and addendums. It standardizes loose data inputs, calculates multi-currency totals using safety exchange margins, and arranges lines into organized, spaced paragraphs, generating a verified legal artifact. 3. Advanced Vector Background Alpha Filtering: By using deep ReportLab parameter flags (mask='auto') combined with memory-buffered image readers, it decodes touchscreen signature strings and strips background borders entirely in RAM. This stamps transparent signatures onto the contract template layout, preventing legal text or grid lines from being overwritten and ensuring an enterprise-ready document design.

def generate_extension_pdf(info, signature_base64):
    settings = get_current_exchange_settings()
    current_db_rate = float(settings['rate'])
    use_margin = int(settings['use_margin'] or 0)

    multiplier = 1.01 if use_margin == 1 else 1.0
    price_eur = float(info.get('extension_price') or 0)
    price_ron = round(price_eur * (current_db_rate * multiplier), 2)

    if info.get('customer_name') and str(info['customer_name']).strip().upper() != 'NONE':
        c_name = str(info['customer_name']).strip()

    elif info.get('first_name') or info.get('last_name'):
        prenume = str(info.get('first_name') or '').strip()
        nume = str(info.get('last_name') or '').strip()
        c_name = f"{prenume} {nume}".strip()
    else:
        c_name = "Client Top Wagen"

    c_plate = str(info.get('registration_plate') or 'N/A').strip()
    c_car = str(info.get('car_name') or 'Autoturism').strip()
    c_contract_nr = str(info.get('rent_contract_number') or 'N/A').strip()
    c_contract_date = str(info.get('contract_date') or 'N/A').strip()
    c_new_date = str(info.get('new_return_date') or 'N/A').strip()
    c_new_hour = str(info.get('new_return_hour') or 'N/A').strip()

    sig_path_admin = os.path.join(current_app.root_path, "static", "assets", "imgs", "signature2.jpg")
    header_img = os.path.join(current_app.root_path, "static", "assets", "imgs", "header_img.jpg")

    buffer = BytesIO()
    p = Canvas(buffer, pagesize=A4)

    p.setFont("ArialUnicode", 8)
    p.drawString(200, 820, "SC xxxxxxxxx SRL")
    p.drawString(200, 810, "CUI xxxxxxxxx")
    p.drawString(200, 800, "xxxxxxxxxxxx")
    p.drawString(200, 790, "Str. xxxxxxxxxx, nr. 3")
    p.drawString(200, 780, "Iasi, jud. Iasi")

    p.drawString(400, 820, "tel: 0040.755.156.757")
    p.drawString(400, 810, "site: topwagen.ro")
    p.drawString(400, 800, "email: contact@topwagen.ro")
    
    p.drawImage(header_img, 20, 770, 120, 60)
    p.setLineWidth(1)
    p.line(20, 770, 580, 770)

    p.setFont("ArialUnicode", 12)
    today = datetime.now().strftime("%d.%m.%Y")
    p.drawCentredString(300, 730, f"ACT ADIȚIONAL NR. {info['act_nr']} din data de {today}")
    
    p.setFont("ArialUnicode", 10)
    p.drawCentredString(300, 715, f"la contractul nr. {c_contract_nr} din {c_contract_date}")

    p.setFont("ArialUnicode", 11)
    y = 670 
    lines = [
        f"  Încheiat astăzi, {today}, între {c_name} și societatea SC xxxxx SRL.",
        f"Prezentul act adițional prelungește durata de închiriere a mașinii {c_car}",
        f"cu numărul de înmatriculare: {c_plate} până pe data de {c_new_date}, ora {c_new_hour}.",
        "",
        f"Cost prelungire: {price_eur} EUR / {price_ron} RON"
    ]
    
    for line in lines:
        p.drawString(50, y, line)
        y -= 20

    p.setFont("ArialUnicode", 8)
    if use_margin == 1:
        p.drawString(50, y, "* Cursul de schimb pentru euro, dolar sau lira sterlina este dat de banca Transilvania +1% din ziua efectuarii platii")
    else:
        p.drawString(50, y, "* Cursul de schimb pentru euro, dolar sau lira sterlina este dat de banca Transilvania")

    p.setFont("ArialUnicode", 10)
    p.drawString(50, 520, "Reprezentant Top Wagen")
    p.drawString(50, 510, "representative name")
    p.drawImage(sig_path_admin, 60, 400, 100, 100, mask='auto')

    p.drawString(400, 480, "Client (Locatar)")
    p.drawString(400, 465, c_name)

    if signature_base64 and isinstance(signature_base64, str) and ',' in signature_base64:
        try:
            header, encoded = signature_base64.split(',', 1)
            client_sig_bytes = base64.b64decode(encoded)
            clean_stream = BytesIO(client_sig_bytes)
            p.drawImage(ImageReader(clean_stream), 380, 380, 120, 100, mask='auto')
        except Exception as e:
            print(f"[Eroare Semnătură]: Generarea imaginii a eșuat, aplicăm text: {e}")
            p.drawString(400, 420, "[Semn─âtur─â Digital─â Procesat─â]")
    else:
        p.drawString(400, 420, "[Semn─âtur─â Digital─â]")

    p.showPage()
    p.save()
    buffer.seek(0)
    return buffer
>__Distributed Real-Time ERP Commercial Quoting & Cross-Platform Sync Engine

An essential core feature of this platform is its real-time, end-to-end ERP Commercial Funnel, engineered across five central subsystems: search_free_cars_extended, calc_fleet_prices_native, calculate_prices_via_api, save_lead_prospect_pipeline, and launch_direct_wp_sql_booking. Architected under a zero-trust, multi-tenant paradigm, this pipeline automates the entire lifecycle of a vehicle rental transactionΓÇötransforming an unstructured, manual customer lead into a fully synchronous production record in under a second.The operational pipeline triggers through a precise chronological sequence modeled around real-world fleet logistics: Phase 1: Ingestion & Live Discovery: The workflow begins when an administrative agent receives an over-the-counter query, phone call, or email from a prospective client. The agent inputs the target date thresholds into the Flask control panel. The system instantly evaluates transient state arrays, current active contracts, and manual scheduling overrides within application memory to extract an absolute pool of vacant physical vehicle frames for that specific future interval. Phase 2: Multi-Variant Quoting & Session Popping: Once availability is established, the agent flags the targeted vehicle models, rental extras, and destination hubs. The pricing engine establishes multi-tenant database connection pools directly to the remote, third-party WordPress/WooCommerce live storefront. It parses seasonal pricing matrices and location-based after-hours timedeltas, utilizing an in-memory session popping algorithm to safely anchor unique vehicle license plates on-the-fly and prevent concurrent allocation race conditions. Phase 3: Relational Persistence & WhatsApp Funneling: Upon calculation, the engine establishes a One-to-Many relational link across two local tables, committing the master transaction metadata into commercial_offers while pushing the calculated vehicle combinations into the commercial_offer_cars child table. Simultaneously, a dynamic string parser compiles a clean, Markdown-formatted sales brief and streams it to the prospect's mobile device via an outbound WhatsApp Gateway HTTP API call. Phase 4: Distributed Atomic Conversion: When the client confirms the quote, the agent retrieves the historical record from the centralized sales pipeline list and executes the direct reservation action. This initializes an isolated cross-server distributed transaction with autocommit = False. The system writes customer profiles to the third-party production table, performs final microsecond-level time-series overlap checks to verify the car remains free, generates official tracking codes, maps internal accessory SKUs, and compiles a comprehensive inline HTML invoiceΓÇödispatching a secure email confirmation over a native SMTP SSL context while enforcing a global database rollback on any exception to protect data synchronization. Phase 5: Automated Loop Closure: Once Committed, the external database state is natively synchronized. The third-party WordPress reservation enters the active ledger, where the local Flask application intercepts it instantly via core analytics enginesΓÇödisplaying the final converted reservation seamlessly on the main Home Dashboard as a standard, active operational entry. We will examine these aspects, by way of example, in the following sections..

[Incoming Commercial Lead (Call/Email)]
                 |
                 v
[1. search_free_cars_extended()] --------> Validates WTForms temporal data
                 |                         Queries local fleet availability tables
                 |                         Bundles active transient pipelines
                 v
[2. In-Memory Time-Series Radar] --------> Matches timestamps in raw RAM via O(1) loop
                 |                         (exist_start_dt < new_end_dt AND exist_end_dt > new_start_dt)
                 |                         Intercepts overrides and active contract extensions
                 v
[3. calc_fleet_prices_native()] ---------> Establishes pooling socket tunnels to live WordPress
                 |                         Computes dynamic seasonal pricing and tax factors
                 |                         Parses open/close times for after-hours fees
                 v
[4. Relational Draft Ingest Engine] ----> [INSERT INTO local.commercial_offers] (draft_calculating)
                 |                         Pops active plates from session to block duplicates
                 |                         [INSERT INTO local.commercial_offer_cars] (Child table variants)
                 v
[5. save_lead_prospect_pipeline()] ----> Translates matrices to deduce financial risk regimes
                 |                         Compiles Complex Markdown Outbound Strings
                 |                         [requests.post() to External WhatsApp Gateway HTTP API]
                 v
                 +------------------------> [Asynchronous Outbound WhatsApp Offer Sent]
                 |                          (Client Decides / Agent Reviews via Dashboard)
                 v
[6. launch_direct_wp_sql_booking()] ----> Initializes Isolated Cross-Server distributed transaction
                 |                         [SETS db_wp.autocommit = False]
                 |
                 +---> Step A: [INSERT INTO wp_car_rental_customers] --------> Generated Customer ID
                 +---> Step B: [INSERT INTO wp_car_rental_bookings] ---------> Generated Booking ID
                 +---> Step C: [UPDATE booking_code via Custom Engine] -----> R[ID]A[SUFIX_5] Pattern Match
                 +---> Step D: [INSERT INTO wp_car_rental_booking_options] -> Injects native accessory SKUs
                 +---> Step E: [INSERT INTO wp_car_rental_invoices] --------> Injects raw HTML invoice templates
                 +---> Step F: [INSERT INTO flask_casco_registry] ----------> Logs financial audit records
                 |
                 v
[7. Isolated SMTP Dispatcher] ----------> Pulls environment variables (.env) from local worker
                 |                         Compiles responsive multi-table HTML transactional confirmation
                 |                         Dispatches secure email packet over native SSL Context (Port 465)
                 v
[8. Distributed Transaction Commit] -----> [Executes db_wp.commit()] ----> Commits mutations simultaneously
                                           [*ROLLBACK ON ANY EXCEPTION*] -> Drops partial records to prevent data drift
                 |
                 v
   [Integrated Dashboard View] ---------> Local Flask Home Screen automatically captures the newly 
                                            injected third-party reservation as a live operational row
>__Initial entry point and Discovery Phase - ERP Commercial Quoting

The 'search_free_cars_extended' function serves as the initial entry point and Discovery Phase of the entire commercial ERP pipeline. The workflow triggers the exact moment a back-office agent is contacted by a prospective client (via phone call, email, or over-the-counter) requesting to know which physical vehicles are unallocated for a specific future date range and at what baseline cost. ΓÇó The critical systemic role of this function is to scan the operational state of the entire fleet instantly. It filters out vehicles tied to pending website drafts, active contracts, ground-level manual plate swaps, and live contract extensions, returning a 100% clean lookup index of vacant vehicle frames. This data is then securely streamed to the dynamic pricing engine to compile the commercial quote. ΓÇó Executes high-speed, non-blocking snapshot queries that pull all active scheduling variables from the database into the application's RAM in a single step, allowing the downstream Python time-series intersection engine to evaluate availability without issuing redundant disk queries. ΓÇó Dynamically loops over the buffered client rows and converts raw database lists into optimized Hash-Maps (Key-Value In-Memory Dictionaries) indexed strictly by the unique relational primary keys (booked_id and external_booked_id). ΓÇó Shits data tracking costs from slow disk operations into CPU memory cache. When the main iteration loop processes incoming allocations, it executes verification lookups at a lightning-fast constant complexity ceiling of O(1), completely avoiding nested quadratic loops O(N^2) that would otherwise exhaust server resources under heavy multi-user loads. The function's query solves a highly complex fleet logistics problem: a client on the road can extend their contract multiple times. The application must identify only the latest active extension parameter without parsing outdated data. ΓÇó LEFT JOIN contracts_data c: Establishes a relational connection between the extensions child table and the master contract state ledger using their relational foreign key mapping. ΓÇó WHERE (c.is_completed IS NULL OR c.is_completed != 1): Implements early data trimming on the database engine level. It instantly drops historical closed records where the car has safely returned to the lot, isolating only active, live vehicles currently driving on public roads. ΓÇó e.id IN (SELECT MAX(id) FROM ... GROUP BY booked_id): Deploys an advanced subquery utilizing a SQL aggregation function (MAX) grouped by the booking identifier. This forces the storage engine to sort the indexes and isolate exclusivelythe most recent extension row record, neutralizing data-drift and ignoring obsolete extensions. ΓÇó This code segment operates as the system's Operational Context Aggregator & Batch Data Broker. Its main architectural role is to systematically eliminate the notorious O(N+1) Query Bottleneck. Instead of executing individual database roundtrips in a loop for each vehicle frame to assess overrides or extension statuses, it issues 4 massive batch operations at startup, streaming the fleet's entire operational layout into RAM so the downstream time-series intersection engine can execute smoothly in isolation. Complexity Ceiling Statement By executing conditional subqueries directly within the MySQL database engine layer and serializing the datasets into optimized hash-structures inside Python, the dataset collection pipeline operates at a highly predictable, optimized linear complexity ceiling of O(N + M), preventing reservation dashboard latency degradation as your historical booking tables and physical vehicle fleet scale up over time.

...
db_conn = pool_new.get_connection()
cursor = db_conn.cursor(dictionary=True, buffered=True)
...
assigned_plates = {row['booked_id']: row['car_number'] for row in cursor.fetchall()}
overrides = {row['external_booked_id']: row for row in cursor.fetchall()}
...
SELECT e.booked_id, e.new_return_date, e.new_return_hour 
FROM contract_extensions e
LEFT JOIN contracts_data c ON e.booked_id = c.booked_id
WHERE (c.is_completed IS NULL OR c.is_completed != 1)
AND e.id IN (SELECT MAX(id) FROM contract_extensions GROUP BY booked_id)
...
>__Filtering, Fetching, and Session Isolation Block - ERP Commercial Quoting

The 'search_free_cars_extended' operates as a critical bridge between local state filtering and remote third-party table synchronization. It focuses heavily on data normalization, algorithmic optimization using constant time lookups, and session serialization to maintain pipeline consistency. Alphanumeric Normalization and Constant-Time Filter Guards ΓÇó str(p_raw).strip().replace(" ", "").upper(): Enforces absolute data normalization at runtime. It removes padding space, strips out internal blank gaps, and forces a strict uppercase transformation. This guarantees that variations in manual user data entry (e.g., "is-01-wgn", "is 01 wgn", or "Is01Wgn") are flattened into a standardized hash key (e.g., "IS01WGN"). ΓÇó if p_clean in busy_car_plates: continue: Deploys an instant constant-time lookup guard. Because busy_car_plates was built as a native Python Hash-Set (set()), verifying whether a license plate is busy resolves at an optimal O(1) speed, allowing the loop to skip blocked assets immediately without causing CPU core processing spikes. ΓÇó if p_clean in car_availability_data: ... continue: Evaluates partial or turnaround collisions (e.g., same-day vehicle handovers). If a plate matches the turnaround index, it skips the default exclusion boundary, packaging the asset directly into the available_cars array along with its timeline transition metadata. Cross-Server Querying and String Pruning Selection ΓÇó SELECT DISTINCT extra_name: Leverages the SQL database engine to perform uniqueness grouping directly inside the remote WordPress environment. This drops the network payload footprint by returning only unique string categories over the wires, removing data replication before the packet hits your Flask worker. ΓÇó name_brut[3:] if ... else name_brut: Implements inline conditional slicing logic to scrub legacy layout data on-the-fly. The public storefront often prefixes optional accessories with numeric sorting keys (e.g., "01. GPS System"). This string parser strips out the leading integers dynamically, translating chaotic e-commerce naming variables into clean, human-readable portfolio text fields ("GPS System"). ΓÇó Defensive finally Exception Capsule: Explicitly closes out both cursor_live and db_conn_live inside a finally block, ensuring that even if the remote website database connection suffers network lag or timeouts, the socket connection is safely recycled back to the pool_live container, avoiding memory leaks. In-Memory Fleet Mapping and Session State Isolation ΓÇó if m_name not in free_fleet_map: free_fleet_map[m_name] = []: Builds a localized, dynamic inverted lookup hash table (Inverted Index Map). It groups individual physical license plates together under their main vehicle model names as lists. ΓÇó session['last_free_fleet'] = free_fleet_map: Serializes the newly processed layout dictionary straight into Flask's client-side session cookie context. This acts as a reliable Volatile State Lock. When the next component in the pipeline (calculate_prices_via_api) runs to generate a formal quote draft, it pops license plates directly out of this session tracking map, creating an inventory shield that prevents concurrent booking operations from claiming the exact same vehicle. Systemic Role within the Component and Application This code segment functions as the applicationΓÇÖs Inventory State Broker & Cross-System Synchronizer. Its systemic role within the ERP architecture is to reconcile raw database rows into isolated, user-specific workflow contexts. By isolating available license plates into user sessions and pulling accessory metadata directly from production schemas, it decouples the search view from the database persistence layers, ensuring that data states remain uniform across different booking stages. Complexity Ceiling Statement By leveraging efficient internal Python lookups over native buffered database tables and grouping car models using a single linear tracking sweep, this state mapping layer runs at an optimal complexity ceiling of O(C + E) (where C is total cars and E is unique extras), preventing interface latency issues even when handling massive fleet directories and large accessory listings.

...
for car in all_cars:
            m = car['car_model']
            p_raw = car['car_number']
            cid = car['id']
            p_clean = str(p_raw).strip().replace(" ", "").upper()

            if p_clean in busy_car_plates:
                continue 
            if p_clean in car_availability_data:
                available_cars.append({'id': cid, 'model': m, 'plate': p_raw})
                continue
            available_cars.append({'id': cid, 'model': m, 'plate': p_raw})

        data.get_locations_names()
        all_wp_locations = list(data.all_locations.values())
        all_wp_extras = []
        try:
            db_conn_live = pool_live.get_connection()
            cursor_live = db_conn_live.cursor(dictionary=True)
            cursor_live.execute('SELECT DISTINCT extra_name FROM wp_car_rental_extras')
            raw_extras = cursor_live.fetchall()
            for extra in raw_extras:
                name_brut = extra['extra_name']
                if not name_brut: continue
                clean_name = name_brut[3:] if len(name_brut) > 3 and name_brut[0:3].isdigit() else name_brut
                all_wp_extras.append({'extra_name_raw': name_brut, 'extra_name_clean': clean_name})
        except Exception as e:
            print(f"Eroare extragere opționale: {e}")
        finally:
            if 'cursor_live' in locals() and cursor_live: cursor_live.close()
            if 'db_conn_live' in locals() and db_conn_live: db_conn_live.close()
        free_fleet_map = {}
        for car in available_cars:
            m_name = car['model'].strip()
            p_num = car['plate'].strip()
            if m_name not in free_fleet_map:
                free_fleet_map[m_name] = []
            free_fleet_map[m_name].append(p_num)
        session['last_free_fleet'] = free_fleet_map
...
>__Core Mathematical Valuation and Pricing Matrix Engine - ERP Commercial Quoting

The 'calc_fleet_prices_native' function serves as the Core Mathematical Valuation and Pricing Matrix Engine of the entire commercial funnel. Once the previous discovery phase (search_free_cars_extended) isolates a clean pool of available vehicle frames, this function is triggered to calculate exact rental fees, optional accessories, after-hours overheads, and liability protection tiers. Its critical pipeline role is to achieve 100% pricing synchronization with the third-party public storefront (WordPress/WooCommerce). Instead of forcing administrative agents to run calculations manually on external calculators or sheets, this engine accepts raw temporal inputs and dynamically computes quotes. The resulting calculated matrix is then handed over to the database ingestion and notification systems, translating raw inventory states into structured commercial quotes. Temporal Normalization & Calendar Discretization Layer. Its primary engineering purpose is to ingest loose time-series string inputs from the frontend, sanitize them into strict data configurations, and apply fractional temporal rounding rules to establish a stable chronological baseline for downstream database plan querying. ΓÇó if len(...) == 5: ... += ":00": Enforces a strict pattern alignment guard at runtime. Standard HTML form clock inputs pass time strings in truncated format (e.g., "10:30"). The compiler intercepts these tokens and dynamically appends seconds precision ("10:30:00"), adapting fields to match the explicit structural formats required by database engines. ΓÇó datetime.strptime(..., datetime_format): Combines separate date and time string inputs into fully timezone-aware, localized Python datetime instances. This acts as an initial verification step, trapping user formatting errors at the application boundary before any queries hit the external server database. Fractional Time Rounding & Rental Duration Evaluation ΓÇó (return_datetime - pickup_datetime).total_seconds(): Performs high-precision time delta arithmetic, converting calendar spans into absolute integer seconds to bypass human calculation differences or manual errors. ΓÇó if total_seconds <= 0: total_seconds = 3600: A defensive fail-safe configuration rule. If an operator accidentally enters a return timestamp that occurs before or exactly at the pickup timestamp, this boundary prevents crashes or negative values by establishing a baseline 1-hour processing window. ΓÇó math.ceil(total_seconds / 86400): Deploys a strict fractional ceiling-rounding algorithm. In commercial vehicle leasing, exceeding a 24-hour block (86400 seconds) by even a single second dynamically triggers a whole additional rental day charge. This mathematical calculation guarantees absolute compliance with corporate business logic, matching the website's pricing system. Reflective Calendar Day-String Indexing ΓÇó strftime('%a').lower(): Extracts the standardized short name representation of the day of the week (e.g., converting a date to "mon", "tue", or "sat"). This is used as an input parameter for the subsequent database engine layer, allowing it to target specific daily tariff fields directly, without relying on long inline conditional mappings. Systemic Role within the Component and Application This block functions as the engine's Chronological Input Sanitizer & Data Normalizer. Its systemic role is to shield the external database from unvetted or fragmented user timezone entries. By standardizing time formats to full precision, applying ceil-rounding logic to compute rental lengths, and mapping days of the week to lower-case string tags, it creates a predictable, structured dataset. This setup allows the downstream loop to execute targeted daily database queries safely. Complexity Ceiling Statement Because this block relies entirely on flat string manipulation and native, highly optimized Python datetime mathematics, it operates at a constant complexity ceiling of O(1) (constant execution time), ensuring instant validation turnarounds that remain completely unaffected by the overall database capacity or corporate transaction volume.

...
if len(pickup_time_str) == 5: pickup_time_str += ":00"
if len(return_time_str) == 5: return_time_str += ":00"

datetime_format = "%Y-%m-%d %H:%M:%S"
pickup_datetime = datetime.strptime(f"{start_date_str} {pickup_time_str}", datetime_format)
return_datetime = datetime.strptime(f"{end_date_str} {return_time_str}", datetime_format)
...
total_seconds = int((return_datetime - pickup_datetime).total_seconds())
if total_seconds <= 0:
    total_seconds = 3600
    
days_render = int(math.ceil(total_seconds / 86400))
if days_render <= 0: 
    days_render = 1
...
pickup_day_short = pickup_datetime.strftime('%a').lower()
return_day_short = return_datetime.strftime('%a').lower()
>__Logistical Constraint Router & Tax Coefficient Ingest Engine - ERP Commercial Quoting

The pricing engine of the 'calc_fleet_prices_native' has a Global Configuration Ingestion and Dynamic Location After-Hours Evaluation Phase. Its pipeline role is to dynamically analyze store configurations and operational branch schedules directly from live tables. By reading localized store tax rules (wp_car_rental_settings) and checking specific branch operating windows, it determines if an out-of-hours late fee applies to the pickup or return window. It factors these variables into a combined logistical cost multiplier (total_location_fees), ensuring that administrative quotes accurately reflect real-time store rules and operating hours. Global Parametric Ingestion and Structural Tax Extraction ΓÇó conf_key IN ('conf_show_price_with_taxes', ...): Uses a targeted SQL constraint filter to fetch only the configuration keys needed for the application. This approach reduces network payload size over the wire, optimizing data retrieval. ΓÇó settings = {row['conf_key']: row['conf_value'] ...}: Implements an in-memory dictionary comprehension that serializes flat relational rows into an optimized key-value hash map. This enables constant-time O(1) lookups when extracting config values, keeping processing fast. ΓÇó tax_factor = (1 + tax_percentage / 100) if... else 1.0: Deploys an inline ternary condition to establish a dynamic multiplier. If the store's administrative flag requires displaying prices with VAT included (show_with_tax == 1), it compiles a floating-point scaling coefficient (e.g., 1.19 for Romanian 19% VAT); otherwise, it defaults to a neutral 1.0, ensuring total calculation flexibility based on store settings. Dynamic String Interpolation and MySQL Time Conversion Workarounds ΓÇó open_time_{pickup_day_short}: Implements dynamic column text interpolation inside the SQL syntax shell. Because store operating hours vary depending on the calendar day, the compiler references the short day-string generated earlier (e.g., open_time_mon or close_time_sun), targeting the correct column directly without messy inline database switch blocks. Python Timedelta Sanitization and Operational Boundary Checking ΓÇó isinstance(p_open_raw, timedelta): Resolves a critical database object driver serialization issue. When pulling TIME type fields from a MySQL table, the Python connector often reads the database row data as a native datetime.timedelta object instead of a clean text string. This type guard checks the variable structure dynamically. ΓÇó str(p_open_raw).zfill(8): Sanitizes the resulting timedelta string by left-padding it with zero characters until it reaches full length precision (e.g., transforming a short duration value "8:00" or "17:30" into a fully normalized HH:MM:SS tracking token: "08:00:00"). ΓÇó pickup_time_str < p_open or pickup_time_str > p_close: Executes a string-based chronological comparison boundary check. Because both variables have been flattened into normalized HH:MM:SS strings, the system compares them alphabetically: if the user's requested time occurs before the branch opens or after it closes, the condition evaluates to true. ΓÇó night_pickup_fee = float(...): Applies the specific late-night fee found in the database row for that branch location if the user requests an out-of-hours pickup or return, ensuring accurate pricing enforcement. Systemic Role within the Component and Application This code segment functions as the system's Logistical Constraint Router & Tax Coefficient Ingest Engine. Its systemic role within the pricing flow is to analyze branch operational parameters in real time before calculating vehicle base rates. By combining global VAT metrics and location schedule boundaries into an isolated, predictable variable (total_location_fees), it establishes an accurate logistical baseline, preventing pricing mismatches between office operations and the storefront. Complexity Ceiling Statement Because this block relies entirely on single-row lookups targeted strictly by database index keys and evaluates conditional time strings in memory, its execution footprint scales at a constant complexity ceiling of O(1), ensuring instant validation turnarounds regardless of how many branches or settings exist in the system database.

...
cursor.execute("""
    SELECT conf_key, conf_value 
    FROM wp_car_rental_settings 
    WHERE conf_key IN ('conf_show_price_with_taxes', 'conf_tax_percentage')
""")
settings = {row['conf_key']: row['conf_value'] for row in cursor.fetchall()}
show_with_tax = int(settings.get('conf_show_price_with_taxes', 0))
tax_percentage = float(settings.get('conf_tax_percentage', 19.00))
tax_factor = (1 + tax_percentage / 100) if show_with_tax == 1 else 1.0
...
SELECT pickup_fee, afterhours_pickup_fee, open_time_{pickup_day_short}, close_time_{pickup_day_short} 
FROM wp_car_rental_locations WHERE location_id = %s
...
p_open_raw = loc_p.get(f'open_time_{pickup_day_short}')
p_open = str(p_open_raw).zfill(8) if isinstance(p_open_raw, timedelta) else str(p_open_raw or '08:00:00')

if pickup_time_str < p_open or pickup_time_str > p_close:
    night_pickup_fee = float(loc_p['afterhours_pickup_fee'] or 0)
>__Relational Pricing Matrix & State Collision Guard - ERP Commercial Quoting

The pricing engine of the 'calc_fleet_prices_native' has a Core Multi-Variant Valuation, Plan Mapping, and Anti-Duplication Phase. It is the absolute programmatic engine room of your rental quotation funnel. After evaluating global tax constants and out-of-hours branch parameters, the compiler runs this block to step through each selected vehicle option separately. Its system pipeline role is to translate a dynamic list of raw text models (car_models) into an explicitly calculated, highly compliant financial payload array. To achieve 100% price synchronization with your independent WooCommerce storefront, the engine traverses your calendar selection day-by-day inside this block, checking active tables for seasonal rate updates, tiered volume discounts, and accessory pricing structures [A1]. It resolves risk coverage models, strips out duplicate asset parameters, and formats the output data into standalone records ready for database storage and client delivery. Direct Catalog Resolution & Parametric Risk-Coverage Branching ΓÇó model_name = model_name.strip() & if not model_name: continue: Performs an initial pattern sanity check. It strips away blank padding variables and skips empty indexes immediately, acting as a gatekeeper rule before issuing queries. ΓÇó fixed_rental_deposit & wp_insurance_per_day: Pulls specific catalog parameters and daily protection rates (wp_car_rental_extras) tied directly to the vehicle's unique structural primary key (item_id). ΓÇó if risk_coverage_choice == 'insurance':: Implements an exclusive risk-routing logic branch based on dashboard controls. If the operator selects Full CASCO protection, the daily cost coefficient (applied_risk_day) is assigned the verified price rate while the contract security deposit (applied_guarantee) is overridden to a neutral 0.0. If the operator selects a Standard Deposit regime, the configuration flips: the insurance fee drops to zero while the catalog's fixed deposit amount (e.g., 2000.00) is assigned, enforcing accurate insurance rule handling In-Memory Calendar Discretization & Dynamic Column Interrogations ΓÇó for single_day_idx in range(days_render): Splits the rental span into clear daily increments. By running calculations step-by-step rather than multiplying flat totals, it tracks fluctuating mid-week changes, holiday spikes, and weekend rate updates across seasonal boundaries without calculation drift. ΓÇó f"daily_rate_{current_day_obj.strftime('%a').lower()}": Uses dynamic string generation to compile the targeted SQL table field on-the-fly (e.g., daily_rate_mon, daily_rate_sat). This replaces long conditional statements with a direct lookup check. ΓÇó DATE(FROM_UNIXTIME(start_timestamp)): Normalizes internal integer epochs into standard string values directly on the MySQL engine layer, avoiding data processing overhead inside your Python worker. ΓÇó ORDER BY seasonal_price DESC LIMIT 1: Enforces strict prioritization rules at the query execution level. It ranks matching rows so that high-priority seasonal price plans automatically override basic rate parameters in a single fetch. Volume-Based Discount Processing & Accessory Multipliers ΓÇó days_render * 86400: Converts total days into operational seconds to test parameters cleanly against scale duration entries (period_from and period_till), applying dynamic volume discounts on longer rentals. ΓÇó extra_price_type == 1: Evaluates the accessory billing structure flag. If the option is marked as a daily charge (extra_price_type == 1), the base parameter is multiplied by the total days (days_render); if it is a fixed per-rental item, it applies a flat rate, matching storefront pricing mechanics. The Anti-Duplication Guard & Separate Deposit Logic ΓÇó if "CASCO" in str(opt['name']).upper(): Implements a crucial safety guard against duplication issues. If an operator checks a Full CASCO accessory from the interface list while leaving the main radio selection active, a basic summation would double-bill the client. This loop inspects names in memory and sets a boolean flag to block double charging. ΓÇó total_insurance_cost = 0.0: Automatically overrides the protection value if coverage was already accounted for in the accessory lines, ensuring accurate calculations. ΓÇó Isolating the Security Deposit: By computing 'grand_total_price' using only active hire costs and tax values while leaving 'applied_guarantee' completely out of the sum, the application separates actual revenue from temporary holdings, protecting financial metrics during ingestion. Systemic Role within the Component and Application This structural block acts as the engine's Relational Pricing Matrix & State Collision Guard. Its systemic role within the architecture is to resolve dynamic e-commerce catalog states into reliable pricing profiles. By combining individual time-series loops, seasonal plans, accessory rules, and protection parameters into an un-duplicated financial layout, it provides clean, aligned payloads that support accurate quoting across the workflow. Complexity Ceiling Statement By using optimized index lookups to fetch records from target tables and tracking state metrics in memory, the calculation loop runs at a highly efficient complexity ceiling of O(D * E) (where D is total days and E is active extras), preventing response lag even when computing massive fleet combinations and long-term rental ranges.

...
cursor.execute("""
    SELECT item_id, price_group_id, fixed_rental_deposit 
    FROM wp_car_rental_items WHERE model_name = %s AND enabled = 1 LIMIT 1
""", (model_name,))
item_record = cursor.fetchone()
wp_fixed_deposit = float(item_record['fixed_rental_deposit'] or 0.0) if item_record else 0.0

if risk_coverage_choice == 'insurance':
    applied_risk_day = wp_insurance_per_day
    applied_guarantee = 0.0
else:
    applied_risk_day = 0.0
    applied_guarantee = wp_fixed_deposit
...
for single_day_idx in range(days_render):
    current_day_obj = pickup_datetime + timedelta(days=single_day_idx)
    formatted_day_str = current_day_obj.strftime('%Y-%m-%d')
    weekday_column_field = f"daily_rate_{current_day_obj.strftime('%a').lower()}"
    
    query_plans = f"""
        SELECT price_plan_id, {weekday_column_field} AS price_plan_rate 
        FROM wp_car_rental_price_plans 
        WHERE price_group_id = %s AND (coupon_code = '' OR coupon_code IS NULL)
        AND (seasonal_price = '0' OR (seasonal_price = '1' AND DATE(%s) BETWEEN DATE(FROM_UNIXTIME(start_timestamp)) AND DATE(FROM_UNIXTIME(end_timestamp))))
        ORDER BY seasonal_price DESC LIMIT 1
    """
...
cursor.execute("""
    SELECT discount_percentage FROM wp_car_rental_discounts 
    WHERE price_plan_id = %s AND (%s BETWEEN period_from AND period_till) 
    ORDER BY discount_id DESC LIMIT 1
""", (plan_record['price_plan_id'], days_render * 86400))

# ... Accessory loop parsing ...
if extra_price_type == 1:
    calculated_extra_cost = raw_extra_price * days_render
else:
    calculated_extra_cost = raw_extra_price
...
is_insurance_already_in_extras = False
for opt in detailed_extras_list:
    if "CASCO" in str(opt['name']).upper() or "INSURANCE" in str(opt['name']).upper():
        is_insurance_already_in_extras = True
        break

total_insurance_cost = applied_risk_day * days_render
if is_insurance_already_in_extras:
    total_insurance_cost = 0.0
...
>__API Orchestration, Input Sanitization, and Core Valuation Link - ERP Commercial Quoting

The 'calculate_prices_via_api' function serves as the API Orchestration, Input Sanitization, and Core Valuation Link of the entire commercial funnel. When an operator submits a quoting query from the search form, this endpoint acts as the direct boundary receiver. Its critical pipeline role is to ingest the raw, unvetted payload strings from the HTTP POST request, clean and standardize the tracking parameters, and securely route them into the calculation engine (calc_fleet_prices_native). By intercepting raw forms, parsing out structural sorting artifacts, and sanitizing location identifiers, it transforms loose user input into a reliable dataset. It coordinates data handling before the system initiates database rows or hooks into remote third-party systems, ensuring data consistency early in the process. ΓÇó request.form.get(..., '10:00'): Implements inline default fallback parameters during form ingestion. If an administrative worker submits an incomplete clock configuration, the runtime assigns a standard time token ("10:00"), avoiding null pointers before compiling data. ΓÇó or request.form.get('pickup_location_id_wp'): Establishes a fallback structure across different interface naming styles. Since the application handles inputs from both custom local forms and legacy third-party panels, this step matches variable naming styles, ensuring reliable data tracking regardless of the source page format. ΓÇó request.form.getlist('selected_cars'): Captures multi-select parameters from the interface. It packages multiple selections into an iterable Python list array, preserving data relationships for parallel calculations. ΓÇó extra_item.split(". ", 1): Implements a string-splitting mechanism to strip out catalog organization artifacts on-the-fly. The administrative interface often loads extra options with sorting numbers (e.g., "1. Extra Driver Charge"). The compiler splits on the first dot-space boundary, isolating the true string token ("Extra Driver Charge"). This approach cleans up metadata parameters before running query matching steps against database records. ΓÇó [str(car).strip() for car in ... if car]: Utilizes an inline list comprehension to cleanse the vehicle model strings. It removes empty records and trims tracking noise from array strings, preventing spacing bugs from distorting matching lookups. ΓÇó int(...) if ... .isdigit() else 0: Implements a strict type guard condition. It verifies that the location string contains only numeric values before converting it to an integer row key. If an invalid or alphanumeric code enters the field, it assigns a neutral 0, protecting downstream SQL logic from casting failures. ΓÇó calc_fleet_prices_native(...): Links directly into the pricing calculation pipeline, passing the sanitized values to process accurate quotation results across the system. Systemic Role within the Component and Application This block functions as the application's HTTP Gateway Controller & Input Sanitization Layer. Its systemic role is to act as a secure buffer between raw browser requests and database calculation tools. By cleaning string arguments, removing list entry noise, handling naming variations, and enforcing type safety on location keys, it ensures that subsequent pricing logic executes reliably without crashing from dirty input data. Complexity Ceiling Statement Because this block relies entirely on flat array scanning and basic string split logic over a small set of form elements, its execution performance scales at an optimal linear complexity ceiling of O(V + E) (where V is selected vehicles and E is active extras), ensuring instant response turnarounds that remain unaffected by total database size or background system traffic.

...
start_date = request.form.get('wp_start_date')     
end_date = request.form.get('wp_end_date')         
pickup_time = request.form.get('pickup_time', '10:00')      
return_time = request.form.get('return_time', '10:00')      

pickup_location_id = request.form.get('pickup_location_id') or request.form.get('pickup_location_id_wp')
return_location_id = request.form.get('return_location_id') or request.form.get('return_location_id_wp')
...
selected_car_models_raw = request.form.getlist('selected_cars') 
selected_extras_raw = request.form.getlist('extras')       

selected_extras_names = []
for extra_item in selected_extras_raw:
    if extra_item and ". " in extra_item:
        split_parts = extra_item.split(". ", 1)
        selected_extras_names.append(split_parts[1].strip() if len(split_parts) > 1 else extra_item.strip())
    elif extra_item:
        selected_extras_names.append(str(extra_item).strip())
...
clean_car_models = [str(car).strip() for car in selected_car_models_raw if car]

wp_response_data = calc_fleet_prices_native(
    pool_live, start_date, end_date, pickup_time, return_time,
    int(pickup_location_id) if pickup_location_id and str(pickup_location_id).isdigit() else 0, 
    int(return_location_id) if return_location_id and str(return_location_id).isdigit() else 0,
    clean_car_models, selected_extras_names,
    risk_coverage_choice  
)
>__The Role of this Persistence and State-Locking Block within the calculate_prices_via_api Function

This block represents the Relational Draft Instantiation, In-Memory Accessory Decomposition, and Anti-Race Condition Allocation Phase of the calculate_prices_via_api route. Once the valuation engine (calc_fleet_prices_native) returns a successful pricing payload, the pipeline invokes this block to handle the persistent tracking layer. Its critical system role is to materialize a calculated quote into a persistent draft state across a relational One-to-Many architecture within the local management database. Before displaying the financial options to the back-office operator, the system breaks down accessory arrays, injects a master summary row into commercial_offers, and loops through calculated vehicle combinations to dynamically bind physical license plates popped from the volatile session cache. This creates a reliable workflow draft, ensuring that specific vehicle assets are held temporarily in place while the client considers the quote via the outbound communication funnel. Alphanumeric Key Stripping & String Inversion Lookup Maps ΓÇó .replace('LO_', '').strip(): Cleans up legacy dropdown interface values on-the-fly. Web forms often append designator strings (e.g., "LO_6") to option indexes. This parser strips the metadata prefix, resolving raw character data into numeric structural foreign keys. ΓÇó clean_p_id.isdigit() else "2": Acts as an inline type safety validation rule. It verifies the cleanliness of the extracted id; if an invalid token is passed, it forces a baseline default fallback value ("2"), blocking potential SQL casting exceptions. ΓÇó if "WASH" in opt_upper or "SP─éLARE" in opt_upper:: Implements an in-memory keyword decomposition loop. Since optional accessory descriptions can vary across database records, the processor normalizes string rows to uppercase and performs sub-string matches. It maps pricing elements directly into a standardized tracking array (option_rates) in RAM, avoiding nested database joins. Relational Master Records Materialization (The Parent Ingest) ΓÇó INSERT INTO commercial_offers: Commits the master quote parameters into the parent table, assigning a localized identifier with a tracking state of 'draft_calculating' to designate the entry as a background computation. ΓÇó row.draft_offer_id = cursor.lastrowid: Captures the auto-incremented primary key generated by the MySQL storage engine. This token is preserved as a relational anchor to build the One-to-Many dependency layer across child rows. Volatile Session State Trimming & Concurrent Race Condition Shields ΓÇó assigned_plate = session_fleet[current_model].pop(0): Implements a high-performance In-Memory State Trimming Lock. By pulling the unallocated fleet map from the encrypted session cookie and using a destructive .pop(0) operation on the models array at execution runtime, it blocks parallel processing collisions. If multiple car variations under the same calculation pass are processed concurrently, this array reduction guarantees that no two lines claim the exact same physical plate asset. ΓÇó f"{current_model} - {assigned_plate}": Modifies the output string structure dynamically for the frontend template. This isolates design formatting changes exclusively to the view layer while preserving structural variables during local data storage. Dependent Child Entry Materialization (The Many Ingest) ΓÇó offer_id = draft_offer_id: Maps the parent primary key directly into the child row context as an explicit database foreign key. This ensures referential binding, allowing easy tracking of multiple quote variants under a single system id. ΓÇó current_model vs car['car_model']: Writes the clean, un-interpolated car model string (e.g., "Ford Fiesta") and the pure isolated plate string into separate database rows to keep storage structures fully normalized, while sending the combined text layout ("Ford Fiesta - IS 16 RJV") out to frontend templates. ΓÇó db_conn.commit() & session['last_free_fleet'] = ...: Atomically commits the sql rows to physical storage while saving the updated, trimmed plate arrays back to the client session cookie, ensuring state consistency across subsequent stages of the pipeline. Systemic Role within the Component and Application This block functions as the application's Relational Draft Ingestion Engine & State Lock Broker. Its systemic role within the workflow is to take transient pricing arrays and lock them down into stable database entities across a One-to-Many schema layout. By isolating vehicle arrays inside session cookies, parsing accessory parameters in RAM, and mapping child row details to parent transaction handles, it protects system state consistency, ensuring that subsequent delivery steps operate over a stable dataset. Complexity Ceiling Statement By processing relational rows via sequential batch execution matrices rather than nested transaction constraints and managing state mutations inside localized memory structures, this persistence layer operates at an optimal linear complexity ceiling of O(A + C) (where A is parsed accessory tokens and C is calculated vehicle lines), ensuring instant database storage turnarounds that remain unaffected by global database capacity or traffic volume.

...
clean_p_id = str(pickup_location_id).replace('LO_', '').strip()
wp_response_data['meta_pickup_location'] = clean_p_id if clean_p_id.isdigit() else "2"

option_rates = {'wash': '0.00', 'seat': '0.00', 'pack_seat': '0.00', 'gps': '0.00', 'driver': '0.00', 'cross': '0.00'}
for opt in sample_options:
    opt_upper = str(opt['name']).upper()
    opt_rate = str(opt['price'])
    if "WASH" in opt_upper or "SP─éLARE" in opt_upper: option_rates['wash'] = opt_rate
    # ... successive string mapping conditions ...
insert_draft_offer_sql = """
    INSERT INTO commercial_offers (
        telephone, start_date, end_date, pickup_time, return_time,
        pickup_location, return_location, ..., whatsapp_status
    ) VALUES ('PENDING', %s, %s, %s, %s, %s, %s, ..., 'draft_calculating')
"""
cursor.execute(insert_draft_offer_sql, (...))
draft_offer_id = cursor.lastrowid
...
session_fleet = session.get('last_free_fleet', {})

for car in wp_response_data.get('cars', []):
    assigned_plate = "N/A"
    current_model = car['car_model'].strip()
    
    if current_model in session_fleet and len(session_fleet[current_model]) > 0:
        assigned_plate = session_fleet[current_model].pop(0)

    if assigned_plate != "N/A":
        car['car_model'] = f"{current_model} - {assigned_plate}"
...
insert_car_sql = """
    INSERT INTO commercial_offer_cars (offer_id, car_model, casco_insurance, car_guarantee, car_base_cost, final_price, car_plate)
    VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
cursor.execute(insert_car_sql, (draft_offer_id, current_model, str(total_casco_value), str(car.get('guarantee', '0.00')), ... , assigned_plate))
session['last_free_fleet'] = session_fleet
db_conn.commit()
...
>__Relational Context Hydrator & Transition Control Layer

The 'view_single_commercial_offer' function serves as the Operational Context Hydration & Conversion Preparation Layer of the pipeline. When a prospective client contacts the company back to accept a quote sent via the outbound WhatsApp funnel, the administrative worker retrieves that specific record. Its critical system pipeline role is to rebuild the historical quotation state by executing a targeted One-to-Many relational join in memory. It pulls the parent summary row (commercial_offers), hooks into the child table (commercial_offer_cars) to find all calculated car variations, and automatically builds an execution form (ManualBookingForm). By pre-populating fields like the tracking identifier into hidden fields and the client's verified phone number straight on the server, this route sets up a quick transition. This enables the operator to convert the passive quote into a live production reservation on a third-party platform with a single button click. SQL Timestamp Normalization & Multi-Format Regional Conversions ΓÇó WHERE id = %s: Deploys a strict parameterized primary key query constraint filter. This shifts structural searching execution directly onto MySQL's optimized integer B-Tree index, completing row lookups at lightning-fast speeds. ΓÇó if not offer_data: return ..., 404: Implements an immediate operational guard condition. If an invalid or non-existent identifier is requested, it cuts processing instantly and flags a clean HTTP 404 state, protecting the application from null pointer errors during subsequent property mapping. ΓÇó offer_data['created_at'].strftime(...): Normalizes native SQL datetime objects into human-readable text strings, adapting system logs into clear representations for back-office operators. ΓÇó '-' in str(offer_data['start_date']): Implements a string-pattern validation guard. Before running conversion calculations, it checks the variable formatting structure to verify whether the data resides in ISO database format (YYYY-MM-DD). ΓÇó datetime.strptime(..., '%Y-%m-%d') followed by .strftime('%d-%m-%Y'): Performs dynamic regional string conversion. It transforms ISO tracking arguments into European regional formats (e.g., changing "2026-06-10" into "10-06-2026"), ensuring presentation alignment inside front-end interface views. ΓÇó except Exception: pass: A defensive processing rule. If the data has already been formatted or contains an irregular structure, the exception block traps errors silently and applies a fallback that leaves the baseline string asset unchanged rather than crashing the layout loop. Relational One-to-Many Hydration & Server-Side Form Pre-Loading ΓÇó WHERE offer_id = %s: Reconstructs the database relational link. It queries the child table (commercial_offer_cars) using the master record identifier as a foreign key constraint, pulling all computed vehicle variations associated with the quote. ΓÇó automation_form.context_offer_id.data = str(offer_id): Injects the active transaction identifier straight into a WTForms hidden input field on the server layer. This establishes a secure Context Token Lock. When the operator submits the confirmation action later, the application reads this token to reference historical rows, preventing data truncation or multi-user state manipulation. ΓÇó automation_form.client_phone.data = str(...): Pre-loads the verified phone string from the database record straight into the form's input properties, eliminating manual data entry steps for lot dispatches. Systemic Role within the Component and Application This function operates as the system's Relational Context Hydrator & Transition Control Layer. Its systemic role within the workflow is to take stored, separate database rows and compile them back into an interactive operational panel . By reading parent-child records via batch operations, re-formatting time variables to regional layouts, and pre-loading conversion tokens into secure server-side form instances, it provides a safe, highly responsive dashboard view that supports fast conversion transitions across the application. Complexity Ceiling Statement By executing targeted query lookups strictly via indexing parameters and handling string-pattern conversions inside isolated memory passes, this data hydration layer executes at a highly efficient linear performance ceiling of O(C) (where C is the total count of vehicle variants linked to the target quote), ensuring instant page responses that remain entirely unaffected by global database size or traffic volumes.

...
cursor.execute("SELECT * FROM commercial_offers WHERE id = %s", (offer_id,))
offer_data = cursor.fetchone()

if not offer_data:
    return "Operational Fault: Requested commercial offer record was not found.", 404
...
if offer_data.get('created_at'):
    offer_data['formatted_date'] = offer_data['created_at'].strftime('%d-%m-%Y %H:%M')

if offer_data.get('start_date') and '-' in str(offer_data['start_date']):
    try:
        date_obj = datetime.strptime(str(offer_data['start_date']).strip(), '%Y-%m-%d')
        offer_data['start_date'] = date_obj.strftime('%d-%m-%Y')
    except Exception:
        pass
...
cursor.execute("SELECT * FROM commercial_offer_cars WHERE offer_id = %s", (offer_id,))
associated_cars = cursor.fetchall()

automation_form = ManualBookingForm()
automation_form.context_offer_id.data = str(offer_id)

if offer_data and offer_data.get('telephone'):
    automation_form.client_phone.data = str(offer_data['telephone'])
...
>__The Role of these Helper Functions within the Quoting and Booking Pipeline

These three standalone utility systems function as the Cryptographic Identifier Generator, Dynamic Cross-Server Option Injector, and Resilient Timestamp Parser of the conversion engine. They are decoupled from the main Flask routing views to act as specialized middleware helpers during the final atomic ingestion phase (launch_direct_wp_sql_booking). Their critical pipeline role is to provide operational translation layer utilities: ΓÇó generate_site_booking_code creates a unique, non-sequential tracking code matching the pattern used by the live third-party platform. ΓÇó inject_wp_extra_option_natively parses accessory parameters and maps local quote choices directly onto remote production database tables. ΓÇó parse_date_safely serves as a vital date parsing guard, converting inconsistent date string structures into clean, standardized UNIX integers. Together, they sanitize incoming parameters, reconcile mismatched tracking structures, and secure cross-platform synchronization during data conversion. Cryptographically Secure Tracking Token Synthesis ΓÇó string.ascii_uppercase + string.digits: Compiles an alpha-numeric character mapping matrix array consisting of 36 base markers (A-Z, 0-9), defining a broad variable tracking field. ΓÇó secrets.choice(chars): Deploys a high-security, Cryptographically Secure Pseudo-Random Number Generator loop layer. Unlike standard, predictable random libraries, this system leverages host operating system entropy pools to synthesize characters. This approach prevents sequential numbering exploits, ensuring unique tracking codes. ΓÇó f"R{booking_id}A{random_suffix}": Generates a distinct composite string matching the third-party platform's pattern (e.g., "R1452A9K87W"), mapping the database row primary key (booking_id) directly into the token structure for trace tracking. Dynamic Cross-Server Option Mapping & Pivot Injection ΓÇó extra_name LIKE %s: Deploys a wildcard parameterized sub-string pattern query constraint (e.g., '%GPS%'). This maps loose local text names directly onto explicit store codes, neutralizing minor vocabulary changes across systems. ΓÇó (item_id = %s OR item_id = 0): Implements conditional hierarchy fallback logic. It checks for accessories assigned specifically to that vehicle model (item_id = %s), but falls back to generic global options (item_id = 0) if no model-specific row exists, ensuring reliable lookup handling. ΓÇó ORDER BY item_id DESC LIMIT 1: Instructs the database storage engine to prioritize model-specific rows over global fallback configurations, resolving business prioritization rules directly within the database lookup. ΓÇó INSERT INTO wp_car_rental_booking_options: Injects a row into the remote pivot table using the retrieved extra_sku, bridging the separate booking and accessory records under the active generated_booking_id primary key context. Polymorphic Fallback Architecture for Safe Date Parsing ΓÇó full_str = f"{date_str} {time_str}:00": Merges separate text inputs and appends zero-padded seconds to construct a normalized, complete time tracking token format ("10-08-2026 14:30:00"). ΓÇó Cascading try/except ValueError Matrix: Implements a strict polymorphic parsing fallback loop. Because data points can arrive from legacy table logs (YYYY-MM-DD) or regional admin inputs (DD-MM-YYYY), a single extraction rule would cause system crashes. This cascade attempts sequential format lookups, catching parsing errors cleanly via pass statements to advance the fallback logic. ΓÇó full_str.replace("/", "-"): Resolves format variations at the character layer, replacing common slash markers with standard dashes to align raw inputs before executing pattern-matching routines. ΓÇó int(datetime.strptime(...).timestamp()): Extracts the absolute timezone-aware UNIX epoch integer value from the processed datetime object. This translates chaotic, multi-format text entries into a single standardized number, optimizing future query performance. Systemic Role within the Component and Application These helper functions function as the platform's Cross-Platform Relational Broker & Input Data Normalizer. Their systemic role is to shield the master distributed transaction logic from data format inconsistencies and character noise. By handling alphanumeric token generation, mapping dynamic accessory codes across remote tables, and converting multi-format datetime entries into clean UNIX integers, they ensure consistent data tracking, allowing the parent ingestion engine to process transactions safely without risks of null exceptions or state sync failure. Complexity Ceiling Statement Because these utility systems process data using flat hash-indexed database calls and targeted string parsing matrices without nested iteration loops, they scale at a highly efficient constant performance ceiling of O(1), ensuring rapid data conversions that remain completely unaffected by total platform capacity or transaction scale.

import secrets
import string

def generate_site_booking_code(booking_id):
    chars = string.ascii_uppercase + string.digits
    random_suffix = "".join(secrets.choice(chars) for _ in range(5))
    return f"R{booking_id}A{random_suffix}"

def inject_wp_extra_option_natively(cursor_wp, generated_booking_id, wp_item_id, extra_search_name):
    cursor_wp.execute("""
        SELECT extra_sku FROM wp_car_rental_extras 
        WHERE extra_name LIKE %s AND (item_id = %s OR item_id = 0) 
        ORDER BY item_id DESC LIMIT 1
    """, ('%' + extra_search_name + '%', wp_item_id))
    extra_record = cursor_wp.fetchone()
    
    if extra_record:
        insert_extra_pivot_sql = """
            INSERT INTO wp_car_rental_booking_options (booking_id, item_sku, extra_sku, option_id, units_booked, blog_id) 
            VALUES (%s, '0', %s, 0, 1, 1)
        """
        cursor_wp.execute(insert_extra_pivot_sql, (generated_booking_id, extra_record['extra_sku']))
    

def parse_date_safely(date_str, time_str):
    full_str = f"{date_str} {time_str}:00"
    try:
        return int(datetime.strptime(full_str, "%d-%m-%Y %H:%M:%S").timestamp())
    except ValueError:
        pass
    try:
        return int(datetime.strptime(full_str, "%Y-%m-%d %H:%M:%S").timestamp())
    except ValueError:
        cleaned_str = full_str.replace("/", "-")
        try:
            return int(datetime.strptime(cleaned_str, "%d-%m-%Y %H:%M:%S").timestamp())
        except ValueError:
            return int(datetime.strptime(cleaned_str, "%Y-%m-%d %H:%M:%S").timestamp())
>__Distributed Integration & Data Lifecycle Topology of the ERP Commercial Quoting

The quoting pipeline effectively concludes once the client decides to book a car and the operator processes the booking in the application; this triggers an entry in the WordPress site's database, sends a confirmation email to the client, and locks the vehicle within the fleetΓÇösimultaneously assigning a license plate number to the reserved car (following an automated availability check). When an administrative agent confirms an offer that the client accepted via WhatsApp, the 'launch_direct_wp_sql_booking', which is a massive 600 line function executes a cross-server distributed transaction. It registers customer profiles, inserts the core reservation schema, runs a microsecond-level safety check to verify that the vehicle frame remains free, maps accessory SKUs, generates custom invoice payloads, and dispatches an SSL email confirmation. Once committed, the external database state is natively updated, letting the local Flask application instantly capture the newly injected third-party reservation on the main Home Dashboard as a standard, active operational entry. The Cross-Server Atomic Safeguard Boundary: The entire 600-line routine operates inside a strict database transaction wrapper that sets db_wp.autocommit = False. By forcing manual commit management across separate network wires, it guarantees that six interdependent tables on a completely separate remote infrastructure are modified simultaneously as a single atomic unit. If a single step failsΓÇöeven an outbound email timeout at the very last secondΓÇöthe system fires a global .rollback(), completely wiping out partial records across all environments to guarantee absolute zero-data-drift. The In-Memory Real-Time Collision Interceptor & Automated License Plate Allocation: Right before writing to the production database, the function deploys a secondary time-series overlap validation matrix (exist_start_dt < new_end_dt and exist_end_dt > new_start_dt). It re-scans active allocations in RAM to intercept race conditions where two fleet dispatchers try to claim the exact same physical frame at the exact same millisecond. If and only if the target vehicle is confirmed 100% vacant for the selected timeline, the system automatically allocates and locks the specific license plate (target_car_plate) directly to the newly generated reservation. If a conflict is caught, it triggers an intelligent split-path logic fallback: it safely routes the core transaction to website storage under a unique tracking code but blocks the local physical fleet allocation, flashing a protective UI warning that prompts manual operator intervention rather than crashing the system thread. Cascade Pivot Option Injection: Automatically reviews active pricing option columns (gps, child_seat, car_wash_fee, etc.). It maps chosen accessories directly to their production SKU rows, and injects data records into the remote pivot table (wp_car_rental_booking_options) under the active booking context. Dual persistence State Synchronization: Performs parallel update operations across separate database pools. It logs transaction records inside the external register while altering the local lead status to, fully closing the automated customer funnel loop. Multi-Recipient Secure SMTP Routing: Pulls server configurations directly from environmental variable systems (.env). It compiles a responsive multi-table HTML summary, establishes an implicit secure SSL wrapper (Port 465), and routes transaction confirmation packets to both the client and the corporate backup box simultaneously.

.  [INBOUND STIMULUS]            [CENTRAL APPLICATION LAYER]                [OUTBOUND EFFECTORS]
  
  +------------------+          +---------------------------+

  | Client Call/Email| -------->| search_free_cars_extended |
  +------------------+          +---------------------------+
                                              |
                                              v [Extracts Vacant Assets Loop]
                                +---------------------------+

                                | calc_fleet_prices_native  | <====== Connection Pooling [pool_live]
                                +---------------------------+
                                              |
                                              v [Calculates Daily Tariffs & Discounts]
                                +---------------------------+

                                | calculate_prices_via_api  | ======> [INSERT] -> local.commercial_offers
                                +---------------------------+         [INSERT] -> local.commercial_offer_cars
                                              |
                                              v [Establishes One-to-Many Memory State Lock]
                                +---------------------------+

                                | save_lead_prospect_pipeline| =====> [POST Payload Request]
                                +---------------------------+                      |
                                              |                                    v
                                              |                         +----------------------+

                                              |                         | WhatsApp Gateway API |
                                              |                         +----------------------+

                                              |                                    |
                                              v [Agent Executes Confirmation]       v [Quote Sent to Mobile]
                                +---------------------------+           +----------------------+

                                | launch_direct_wp_sql_booking|          |  Client Decision Box |
                                +---------------------------+           +----------------------+
                                              |
                     +------------------------+------------------------+

                     |                        |                        |
                     v [Atomic ACID Ingest]   v [Encrypted SMTP SSL]   v [Dynamic Hook Closure]
        +--------------------------+   +-------------------+   +-----------------------+

        | Remote WordPress Live DB |   | Secure Client Mail|   | Local Flask Dashboard |
        | (6 Relational Tables Snc)|   |  (HTML Invoice)   |   | (Captured Live Entry) |
        +--------------------------+   +-------------------+   +-----------------------+
>__The Distributed Multi-National Intelligent OCR Engine & Contract Provisioning Pipeline

End-to-End Core Integration & Architectural Data Flow The document ingestion, linguistic translation, and legal provisioning subsystem forms a highly synchronized, asynchronous processing pipeline. Engineered specifically for decoupled execution within memory-constrained production environments, the architecture bridges raw unstructured physical document images with multi-signatory production database schemas and immutable PDF contract outputs. Asynchronous Parallel Ingestion & Lazy-Loaded Isolation The workflow begins at the Flask endpoint @app.route("/pre-contract-ocr/<int:booking_id>"). The controller checks checkout status and checks out a thread-safe connection from the local pool pool_new, querying document file identifiers across six specific categorical slots spanning primary and secondary client credentials. Rather than compounding re-transmission network latency on the primary thread through legacy loop iterations, the payload is offloaded to process_ocr_limited_resources.This orchestrator instantiates an in-memory ThreadPoolExecutor bounded by the active file volume (N Γëñ 6). Individual workers (worker_ocr) deploy lazy-loading isolation, declaring heavy dependencies like google.cloud.vision and google.oauth2.service_account strictly inside their local method scope. This prevents process-level RAM bloat on startup. The workers retrieve keypaths from environment configurations (GOOGLE_APPLICATION_CREDENTIALS), execute a single-pass REST-transport cloud API request, and yield index-aligned unstructured text fragments back to the master process. Deterministic Country Classification & Linguistic Processing Matrix Once the async pool resolves, the text blocks are processed by ten specialized sub-routines (extract_uk, extract_germany, extract_switzerland, etc.). The root orchestrator runs cascading string-distance and linguistic keyword validation checks (any(k in u_text)) over uppercase text blocks to classify the document's nation of origin. Each sub-routine operates as an isolated parsing engine customized for target regional variations. For example, extract_uk scans postal records via alphanumeric expressions ([A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}) and traverses relative line structures to capture street addresses while stripping noise characters. Meanwhile, extract_germany identifies specific alphanumeric licensing strings using structural fallback regex patterns, applying an implicit century evaluator to handle shorter 2-digit birth and expiration tokens. The unified data payload is saved to the server session wrapper (session['ocr_temp_data']) before an HTTP redirect transfers control to the frontend contract creation endpoint. Hybrid State Reconciliation & Data Pre-Population When hitting create_contract under the HTTP GET state, the endpoint accesses three auxiliary data layout systems to reconstruct business logic parameters without data synchronization risks: ΓÇó The GetData() State Cache Engine: Direct-maps core fleet specifications, physical car profiles, accessory tracking listings, and base booking structures from remote platforms. ΓÇó The get_booking_overrides() Logic Matrix: Evaluates pricing records to apply manual fee or rate adjustments made by field operators, overriding default parameters. ΓÇó The safe_date_convert() Utility Wrapper: Uses polymorphic try/except parsing blocks to parse inconsistent multi-format date entries from the OCR results into standardized datetime.date objects. This data is mapped into a ContractForm instance, pre-populating fields on the user interface (rent_car.html) to eliminate data entry typos for field agents. Multi-Tier Defensive Canvas Ingestion & Atomic PDF Storage Upon form submission (POST state), the application switches paths based on operator selections (primary_signature_send vs. sign_both). To block exploitation of the client interface touch signature canvas element, the routine routes incoming Base64 graphics data through a 4-tier defensive validation pipeline: ΓÇó Data-Flood Prevention: Drops incoming payload strings exceeding 400,000 characters to stop buffer exhaustion attempts. ΓÇó MIME Integrity Verification: Validates string split positions by verifying the presence of base64 comma separators (','). ΓÇó In-Memory Transcoding Isolation: Decodes base64 buffers directly into volatile RAM allocations using BytesIO, avoiding physical disk overhead. ΓÇó Pixel-Bomb Traps: Loads arrays into Pillow (Image.open) to verify physical boundaries (width > 1500 or height > 1500), discarding high-resolution memory-exhaustion exploits. The validated graphical objects are packed along with normalized form details into generate_pdf_contract. This engine creates a legal document stream, returning a binary buffer via .getvalue(). The pipeline completes by verifying serial numbers through conditional DB interogations (CAST(rent_contract_number AS UNSIGNED)). Finally, it writes 67 data fields alongside the raw PDF stream into a long binary column (LONGBLOB) in contracts_data. It commits the database transaction manually, clears out cache structures using data.pending_bookings.clear(), and updates the dashboard view.

.                              [OPERATOR TRIGGER]
                                         Γöé
                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé                         1. pre_contract_ocr(booking_id)                       Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : booking_id (int)                                                     Γöé
 Γöé ACTIONS: Checks checkout status, pulls DB connection from pool_new, queries   Γöé
 Γöé          clients_docs table for 6 document image file path identifiers.       Γöé
 Γöé OUTPUT : Array of 6 target image file paths wrapped in positional metadata    Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                         Γöé
                                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé                  2. process_ocr_limited_resources(id_filename, ...)           Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : 6 raw file strings from pre_contract_ocr                             Γöé
 Γöé ACTIONS: Filters out missing payloads, instantiates ThreadPoolExecutor, spans Γöé
 Γöé          concurrent non-blocking thread workers dynamically                   |
 |          (N  session['ocr_temp_data']                                         Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                         Γöé
                                                  (HTTP REDIRECT)
                                                         Γöé
                                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé                 5. create_contract(booking_id) - STATE: [GET]                 Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : booking_id, session['ocr_temp_data'], and application data layers:   Γöé
 Γöé          Γö£ΓöÇΓû║ GetData() Object       : Memory cache manager for fleet specs    Γöé
 Γöé          Γö£ΓöÇΓû║ get_booking_overrides(): Manual pricing adjustments array        Γöé
 Γöé          ΓööΓöÇΓû║ safe_date_convert()    : Polymorphic string-to-date converter    Γöé
 Γöé ACTIONS: Reconciles extracted data with core systems, calculates timestamps   Γöé
 Γöé          to compute rent days, pre-populates WTForms instance data fields.    Γöé
 Γöé OUTPUT : Renders interactive HTML form interface template (rent_car.html)     Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                         Γöé
                                              (OPERATOR SUBMIT)
                                                         Γöé
                                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé                 6. create_contract(booking_id) - STATE: [POST]                Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : request.form data fields, request.form['canvasData']                 |
 |          signature payload                                                    Γöé
 Γöé ACTIONS: Evaluates form status flags ('primary_signature_send' / 'sign_both'),Γöé
 Γöé          executes 4-tier client canvas threat defensive verification layer:   Γöé
 Γöé          1. Data-Flood Limit Check (>400KB characters blocked)                Γöé
 Γöé          2. MIME Separator Normalization (Splits base64 via string context)   Γöé
 Γöé          3. BytesIO In-Memory Decoding Stream Isolation                       Γöé
 Γöé          4. Pixel-Bomb High-Resolution Boundary Scan (>1500px rejected)       Γöé
 Γöé OUTPUT : Validated memory stream references dispatched to generation layer    Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                         Γöé
                                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé             7. generate_pdf_contract(contract_data, image, [image_sec])       Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : Sanitized contract dictionary data,                                  |
 |          single/dual signature ImageReaders                                   Γöé
 Γöé ACTIONS: Compiles legally-binding HTML layout structure templates, embeds     Γöé
 Γöé          pricing grids, stamps verified client signatures directly on layout. Γöé
 Γöé OUTPUT : Returns transient memory address buffer containing compiled raw PDF  Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                         Γöé
                                                         Γû╝
 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
 Γöé                     8. PRODUCTION DATABASE TRANSACTION EXECUTION              Γöé
 Γö£ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöñ
 Γöé INPUT  : Computed contract number, structural variables, raw PDF binary data  Γöé
 Γöé ACTIONS: Runs thread-safe connection check out, inserts 67 schema attributes  Γöé
 Γöé          and stores the PDF stream into `contracts_data` as a LONGBLOB,       Γöé
 Γöé          invokes db_conn.commit(), clears memory with pending_bookings.clear()Γöé
 Γöé OUTPUT : Flash Message notification banner -> Redirects to booking_details    Γöé
 ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
>__Functional Topology: Asynchronous State Reconciliation & Multi-Signatory Provisioning

An alternative architectural blueprint detailing the lifecycle of this automation pipeline can be analyzed here. While the core engine relies on a concurrent ingestion network, this topology map illustrates the system from a State Management, Runtime Security, and User-Interface Reconciliation perspectiveΓÇöhighlighting how transient OCR telemetry is safely bridged into session contexts, evaluated against defensive graphics boundaries, and committed as immutable, multi-signatory legal documents.

[Multipart Document Payload / Operator Trigger]
                           Γöé
                           Γû╝
     @app.route("/pre-contract-ocr/<booking_id>") ΓöÇΓöÇ(Intercepted by @monitor_speed)
                           Γöé
                           Γö£ΓöÇΓöÇΓû║ [Connection Pool (pool_new)] ΓöÇΓöÇΓû║ Pulls 6 Multi-format File Pointers
                           Γöé
                           Γû╝
           [process_ocr_limited_resources] ΓöÇΓöÇ(Instantiates ThreadPoolExecutor Context)
                           Γöé
                           Γö£ΓöÇΓû║ [worker_ocr (Thread 1 - Principal ID)]       ΓöÇΓöÇΓû║ Google Vision API ΓöÉ
                           Γö£ΓöÇΓû║ [worker_ocr (Thread 2 - Principal License)]  ΓöÇΓöÇΓû║ Google Vision API Γö£ΓöÇΓû║ [Index-Aligned Output]
                           ΓööΓöÇΓû║ [worker_ocr (Thread N - Secondary Docs)]     ΓöÇΓöÇΓû║ Google Vision API Γöÿ           Γöé
                                                                                                              Γû╝
                                                                                          [Linguistic Classifiers & Country Selection]
                                                                                                              Γöé
           ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
           Γû╝                                  Γû╝                                       Γû╝                               Γû╝
[extract_switzerland(text)]         [extract_ireland(text)]                [extract_germany(text)]         [extract_uk(text)]  ... (+6 functions)
           Γöé                                  Γöé                                       Γöé                               Γöé
           ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                                  Γû╝
                                               [Flask Session Context ('ocr_temp_data')]
                                                                  Γöé
                                                                  Γû╝ (HTTP Redirect Hand-off Window)
                                              @app.route("/rent-car/<booking_id>")
                                                                  Γöé
                    ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
                    Γû╝ (State: POST - Canvas Submission)                                                         Γû╝ (State: GET - Form Display)
       [Multi-Signatory Security Layer]                                                         [Instantiate WTForms & Map Fallbacks]
                    Γöé                                                                                           Γöé
  ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ                                                                         Γö£ΓöÇΓû║ [GetData() Cache System]
  Γû╝ (Case: Single Signature)          Γû╝ (Case: Dual Signature)                                                  Γö£ΓöÇΓû║ [get_booking_overrides()]
[Data-Flood & Pixel-Bomb Guards]     [Dual base64 Stream Transcoders]                                           ΓööΓöÇΓû║ [safe_date_convert()]
  Γöé                                   Γöé                                                                         Γöé
  Γû╝                                   Γû╝                                                                         Γû╝
[generate_pdf_contract(1 Image)]     [generate_pdf_contract(2 Images)]                                   [Render 'rent_car.html' UI Form]
  Γöé                                   Γöé
  ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                    Γû╝
      [Target Database Persistence]
                    Γö£ΓöÇΓöÇΓû║ manual db_conn.commit() to `contracts_data` (LONGBLOB)
                    ΓööΓöÇΓöÇΓû║ Memory Buffer Purge via `data.pending_bookings.clear()`
>__Architectural System Topology: Financial Analytics & Fleet Performance Pipeline

This business intelligence (BI) ecosystem transforms unstructured financial log registries and database strings into deterministic fleet performance indicators. The engine is engineered to prevent long-running table locks on the production transaction schema by pulling raw, flat row sets in single-pass operations and offloading calculation tasks entirely to the application's RAM workspace.

.                               [ADMIN OPERATOR / BI DASHBOARD VIEW]
                                                 Γöé
                                                 Γû╝
                           @app.route("/reports") ΓöÇΓöÇ(Intercepted by @monitor_speed)
                                                 Γöé
                  ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
                  Γû╝                                                             Γû╝
       [GET: Monthly Aggregates]                                     [GET: Sliding Range Arrays]
                  Γöé                                                             Γöé
      @app.route("/reports/fleet")                                 @app.route("/reports/fleet/analytics")
                  Γöé                                                             Γöé
         ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö¼ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ                 ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
         Γû╝                 Γû╝                         Γû╝                 Γû╝                                 Γû╝
   [report_fleet]   [report_car_]           (HTTP REDIRECT)     [report_fleet_]             [report_car_analytics_]
  (Monthly Matrix)  [   details ]                    Γöé          [  analytics  ]             [       details       ]
         Γöé                 Γöé                         Γöé                 Γöé                                 Γöé
         Γöé                 Γöé                         Γû╝                 Γöé                                 Γöé
         Γöé                 Γöé           @app.route("/.../performance")  Γöé                                 Γöé
         Γöé                 Γöé                         Γöé                 Γöé                                 Γöé
         ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö╝ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö┤ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                     Γöé
                             ΓöîΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö╝ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÉ
                             Γû╝                       Γû╝                       Γû╝
                @app.route("/.../efficiency")  @app.route("/.../profitability")  @app.route("/.../seasonality")
                             Γöé                       Γöé                       Γöé
                             Γû╝                       Γû╝                       Γû╝
                    [In-Memory Hash Sets]   [Ancillary Tax Unifier] [Chronological Grouping]
                             Γöé                       Γöé                       Γöé
                             ΓööΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓö╝ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÿ
                                                     Γû╝
                                       [In-Memory RAM Buffer Output]
                                                     Γöé
                                                     Γû╝
                                 [Render Volatile Visualization Templates]
                                 Γö£ΓöÇΓöÇ Dynamic Relative Progress Bars (%)
                                 ΓööΓöÇΓöÇ Real Utilization Scheme Parameters
>__Micro-Component Interface Specification (Data Input/Output Contract) - Financial & Performance Analytics

I. view_reports ΓÇó Inputs: None (Triggered by active session check). ΓÇó Core Logic: Pulls concurrent statistical volume counters from pool_new. It counts active vehicles (cars_details) and raw contract rows (contracts_data). To calculate the actual, unique customer repository without memory bloat, it evaluates a nested database subquery (SELECT COUNT(*) FROM (...) AS unique_clients_subquery) that aggregates rows sharing a matching identity cluster (first_name, last_name, phone, email). ΓÇó Outputs: Sets structural metrics (cars_count, contracts_count, total_customers_count) to populate the primary dashboard. II. report_fleetInputs: ΓÇó URL string parameters month (Default: current MM) and year (Default: current YYYY), along with the validation string flag status ('total', 'ok'). ΓÇó Core Logic: Compiles transactional variables for a single month. It converts string column timestamps directly on the database wire (MONTH(STR_TO_DATE(pickup_timestamp, '%d-%m-%Y')) = %s), filters entries by system state via string concatenations (AND temp_status = 'nontemp'), and runs inline sql safe numerical summaries: SUM(CAST(COALESCE(NULLIF(amount_paid, ''), '0') AS DECIMAL(10,2))). ΓÇó Outputs: Generates an ordered list of monthly revenue dictionaries (stats), total processed revenue floats (total_income), and absolute volume integers (total_contracts). III. report_car_details ΓÇó Inputs: Dynamic URL routing parameter string <string:registration_plate>, query strings month, year, and status filter flags. ΓÇó Core Logic: Extracts granular history records for a single asset. It runs an inline regex cleanup query to remap compact parameters into standard database keys, queries the pooled target table by filtering on specific month/year slots, and casts currency entities (amount_paid) directly into explicit numeric arrays (contract_revenue) sorted descending by date. ΓÇó Outputs: Returns a comprehensive chronological contract breakdown array (contracts), verified registration license plate string (registration_plate), and car model identifier (car_name). IV. report_fleet_analytics ΓÇó Inputs: Interface calendar request range strings start_date and end_date, alongside structural status indicators. ΓÇó Core Logic: Builds long-term sliding-window analytics configurations. If custom range parameters are absent, it initializes an automated 90-day time boundary loop (timedelta(days=90)) relative to current server time. It resolves format discrepancies between form variables (%Y-%m-%d) and database fields (%d-%m-%Y) by applying simultaneous bi-directional STR_TO_DATE transformations on both sides of the SQL evaluation clause. ΓÇó Outputs: Populates range-bound operational statistics (stats), complete window revenue metrics (total_income), and contract volume metrics (total_contracts). V. report_car_analytics_details ΓÇó Inputs: Dynamic URL mapping tracking parameter <string:registration_plate>, interface request constraints start_date, end_date, and status validation flags. ΓÇó Core Logic: Operates as a granular extension of the calendar analytics layout. It processes unformatted asset keys via regex decomposition, constructs query bounds using explicit inequality clauses (>= STR_TO_DATE(%s, '%Y-%m-%d')), and pulls matching transaction rows, extracting localized revenues (contract_revenue) directly from the data pool rows. ΓÇó Outputs: Outputs date-bounded single-vehicle contract metrics arrays (contracts), normalized display strings (registration_plate), and structural fleet asset model descriptions (car_name). VI. report_fleet_performance ΓÇó Inputs: Interface request calendar interval boundaries start_date and end_date, and application status indicators. ΓÇó Core Logic: Operates as a fast graph-rendering engine. It uses a single-pass flat query (SELECT car_name, registration_plate, pickup_timestamp, temp_status, amount_paid FROM contracts_data) to pull the required records without execution locks, shifting calculation tasks entirely to RAM. It parses raw dates with local inline regex components, strips currency strings of formatting noise (re.sub(r'[^\d.]', '', ...)), and aggregates entries into a local hash map. It then splits this map into two separate sorting vectors: one ordered by absolute revenue contribution, and another ordered by contract volume. ΓÇó Outputs: Transmits structured percentage datasets revenue_data and contracts_data to render relative progress indicators in the frontend. VII. report_fleet_efficiency ΓÇó Inputs: URL date strings start_date, end_date, and state verification indicators. ΓÇó Core Logic: Measures true asset utilization metrics over a custom timeline window. It tracks calendar lengths using a strict date subtraction formula: days_in_range = (end_bound - start_bound).days + 1. It analyzes raw contract timestamps through precise intersection filters, trimming segments that fall outside the active window. The engine passes dates through a Python loop into an in-memory hash set structure (set().add(current_day)). Because hash sets enforce object unicity, multi-user shifts, duplicate same-day logs, and processing collisions collapse instantly into distinct operational days. ΓÇó Outputs: Returns a usage array (efficiency_data) detailing exact days rented (total_rented_days), calculated occupancy factors (occupancy_rate), and average length fields (avg_duration). VIII. report_fleet_profitability ΓÇó Inputs: Calendar argument strings start_date, end_date, and status parameters. ΓÇó Core Logic: Audits fleet profitability and extracts its core RevPAV indicator. It aligns performance profiles with main metrics by filtering contracts strictly by their initial checkout date (start_bound <= contract_start <= end_bound). It processes 10 separate ancillary columns (pickup_fee, gps, child_seat, etc.) using regex text cleaners, sums them, and scales them by the active currency exchange multiplier (total_fees_ron = sum_fees_eur * rate). It computes the total insurance capture independently and combines these values to derive the vehicle's Revenue Per Available Vehicle metric: rev_pav = allocated_rev / days_in_range. ΓÇó Outputs: Returns a comprehensive profitability matrix dictionary (profitability_data) containing items sorted by relative financial weight percentages (rev_pav_percentage). IX. report_fleet_seasonality ΓÇó Inputs: Interface request range trackers start_date and end_date, and system state filters. ΓÇó Core Logic: Evaluates historical multi-year macro-economic cycles. It runs a single-pass select query over the ledger register without applying date boundaries, parsing raw timestamps via regex groups to build custom, sortable chronological hash strings (cron_key = f"{year}-{month:02d}"). It aggregates revenue totals, contract volumes, and rental lengths under these chronological keys inside a local dictionary, calculating historical monthly Average Daily Rates: avg_daily_rate = monthly_revenue / monthly_rented_days. ΓÇó Outputs: Emits long-term historical vector groupings (trend_data) sorted chronologically from the most recent tracking period to the oldest.

@app.route('/reports')
@monitor_speed
def view_reports():
    db_conn = None
    cursor = None
    try:
        db_conn = pool_new.get_connection()
        cursor = db_conn.cursor()

        cursor.execute("SELECT COUNT(*) FROM cars_details")
        res_cars = cursor.fetchone()
        cars_count = res_cars[0] if res_cars else 0

        cursor.execute("SELECT COUNT(*) FROM contracts_data")
        res_contracts = cursor.fetchone()
        contracts_count = res_contracts[0] if res_contracts else 0

        customer_count_sql = """
            SELECT COUNT(*) FROM (
                SELECT first_name, last_name, phone, email 
                FROM contracts_data 
                GROUP BY first_name, last_name, phone, email
            ) AS unique_clients_subquery
        """
        cursor.execute(customer_count_sql)
        res_customers = cursor.fetchone()
        total_customers_count = res_customers[0] if res_customers else 0

    except mysql.connector.Error as err:
        print(f"Database error: {err}")
        cars_count, contracts_count, total_customers_count = 0, 0, 0
    finally:
        if cursor:
            cursor.close()
        if db_conn:
            if db_conn.is_connected():
                db_conn.close()

    return render_template('reports.html', 
                           cars_count=cars_count, 
                           contracts_count=contracts_count,
                           total_customers_count=total_customers_count)
>__Syntax & Algorithmic Implementations - Financial & Performance Analytics

The analytical engine relies on advanced Python design patterns, complex regular expression filters, and custom type-coercion fallbacks to maintain system stability and performance. Deep-Pass Regex Decompositions & Key Restructuring To resolve raw text layout parameters passed from the client interface, the system implements strict pattern validations to verify input data structure. ΓÇó 'plate_match' routine enforces boundary restrictions (^ and $), captures isolated regional components, and reconstructs space-padded records to align user arguments with stored primary database keys. ΓÇó When analyzing raw text timestamps, the engine uses custom grouping expressions to isolate day, month, and year parts from mixed or broken string outputs (date_match) By supporting polymorphic delimiters (-, ., /) and handling variable number padding, this expression cleans raw text metadata and prevents formatting anomalies from crashing the data processing workers. Volatile Memory Inversion Loops & Defensive Type Coercions ΓÇó To clean currency strings without using heavy database formatting functions, the system applies text replacement steps combined with character pattern filtering (clean_val). Time-Series Boundary Scaling & Volatile Hash Arrays ΓÇó To calculate true asset utilization metrics over varying timelines, the engine evaluates individual contract limits against the active dashboard window via logical bounding conditions. The boundary setup isolates the overlapping period, trimming trailing contract segments that fall outside the active reporting context. ΓÇó To process these overlapping date arrays without inflating utilization statistics during multi-user transitions or same-day drop-offs, the engine streams individual calendar objects into a native hash set structure. Because Python set collections leverage internal hash lookup tables to enforce absolute object unicity, adding identical date elements maps to the same memory slot at a fast runtime of O(1). This collapses duplicate entries instantly to deliver precise, deduplicated utilization counts

...
plate_match = re.match(r"^([A-Z]{1,2})(\d{2,3})([A-Z]{3})$", raw_plate)
if plate_match:
    db_plate = f"{plate_match.group(1)} {plate_match.group(2)} {plate_match.group(3)}"
...
date_match = re.search(r'(\d{1,2})[-./](\d{1,2})[-./](\d{4})', str(raw_ts).strip())
...
def clean_val(field_name):
    try:
        val_str = str(row[field_name]).strip()
        if not val_str or val_str in ['None', 'NULL', '']: return 0.0
        cleaned = re.sub(r'[^\d.]', '', val_str.replace(',', '.'))
        return float(cleaned) if cleaned else 0.0
    except Exception: return 0.0
...
if contract_end < start_bound or contract_start > end_bound:
    continue
overlap_start = max(start_bound, contract_start)
overlap_end = min(end_bound, contract_end)
...
current_day = overlap_start
while current_day <= overlap_end:
    fleet_records[plate]['occupied_dates_set'].add(current_day)
    current_day += timedelta(days=1)
>__Computational Complexity, Optimization Architecture, & Execution Boundaries

The core reporting architecture is split into two independent processing layers designed to minimize computing costs and preserve system resources: Optimized Indexed Sub-Queries (O(log N) Boundary) The core statistical endpoints (view_reports, report_fleet, report_fleet_analytics) run directly on the MySQL database engine. By filtering fields using explicit, indexed lookup keys (booking_id = %s, registration_plate = %s), search steps bypass sequential row scanning. The database engine navigates structured B-Tree indices to target rows directly, achieving an efficient logarithmic complexity ceiling of: O(log N) where N tracks total historical table rows. This setup minimizes processing overhead and ensures rapid data retrieval. Memory-Isolated Analytical Pipelines (O(N * D + M log M) Boundary) To compile multi-attribute top lists and analyze historical trends without overloading the production transaction database with complex JOIN operations or group locks, endpoints like performance, efficiency, profitability, and seasonality pull raw column structures using a single, streamlined query. This flat extraction operation scales at a linear complexity of: O(N) It transfers raw tracking rows directly into volatile server memory, completely avoiding database processing bottlenecks. Once the dataset is loaded into RAM, the processing engine unifies text fields, applies boundary filters, and structures associative arrays using single-pass loops. The time-series utilization trackers scale based on the length of each active lease window (D) by executing fast O(1) hash set insertions. The final sorting tasks organize these processed dictionaries by performance metrics, leveraging Python's native Timsort algorithm. This bounds the total operational scale of the data processing layer to a highly predictable complexity ceiling of: O(N * D + M log M) where N represents total historical contract volume, D is the mean contract duration in days, and M tracks total active fleet size or compiled chronological periods. By handling data transformations entirely within server RAM, this architecture isolates the underlying transaction ledger from heavy computing workloads. This configuration eliminates table contention risks and maintains high application throughput, delivering lightning-fast report rendering even during peak multi-user usage spikes.

@app.route('/reports/fleet')
@monitor_speed
def report_fleet():
    target_month = request.args.get('month', datetime.now().strftime('%m'))
    target_year = request.args.get('year', datetime.now().strftime('%Y'))
    target_status = request.args.get('status', 'total')
    
    db_connection = None
    db_cursor = None
    try:
        db_connection = pool_new.get_connection()
        db_cursor = db_connection.cursor(dictionary=True)
        status_filter = ""
        query_params = [target_month, target_year]
 
        if target_status == 'ok':
            status_filter = "AND temp_status = 'nontemp'"
        elif target_status == 'to_cancel':
            status_filter = "AND temp_status = 'temp'"

        query = f"""
            SELECT 
                registration_plate, 
                car_name,
                COUNT(id) AS total_contracts,
                SUM(CAST(COALESCE(NULLIF(amount_paid, ''), '0') AS DECIMAL(10,2))) AS total_income
            FROM contracts_data
            WHERE MONTH(STR_TO_DATE(pickup_timestamp, '%d-%m-%Y')) = %s
              AND YEAR(STR_TO_DATE(pickup_timestamp, '%d-%m-%Y')) = %s
              {status_filter}
            GROUP BY registration_plate, car_name
            ORDER BY total_income DESC
        """
        db_cursor.execute(query, tuple(query_params))
        fleet_stats = db_cursor.fetchall()

        total_income = sum(row['total_income'] for row in fleet_stats if row['total_income'])
        total_contracts = sum(row['total_contracts'] for row in fleet_stats if row['total_contracts'])
        
    except Exception as error:
        print(f"Fleet Report Error: {error}")
        fleet_stats = []
        total_income = 0
        total_contracts = 0
    finally:
        if db_cursor: db_cursor.close()
        if db_connection: db_connection.close()

    return render_template(
        'report_fleet.html', 
        stats=fleet_stats, 
        month=target_month, 
        year=target_year,
        current_status=target_status,
        total_income=total_income,
        total_contracts=total_contracts
    )

System Contact >>