
    Rh/	                         d dl Z d dlmZ d Zy)    N)	DB_CONFIGc                  F   d} t        j                  di t        }	 |j                  t         j                  j
                        5 }|j                  |        |j                         }d d d        |j                          S # 1 sw Y   xY w# |j                          w xY w)Nu  
    SELECT 
    COUNT(q.entity_id) AS total_carts,
    q.entity_id AS cart_id, 
    q.customer_firstname, 
    q.customer_lastname, 
    q.customer_email,
    q.remote_ip AS user_ip,
    q.items_qty AS items_quantity, 
    q.grand_total AS total_amount, 
    q.updated_at AS last_activity,
    GROUP_CONCAT(cpe.sku) AS product_skus,

    -- Telefone: carrinho ou fallback via customer_grid_flat
    COALESCE(qa.telephone, cg.billing_telephone) AS customer_phone,

    -- Link do carrinho
    CONCAT('https://lumixpro.com.br/checkout/cart?quote_id=', q.entity_id) AS cart_url,

    -- Imagem do produto
    CONCAT('https://lumixpro.com.br/media/catalog/product', image.value) AS product_image_url

FROM 
    lumixdb.quote AS q

JOIN 
    lumixdb.quote_item AS qi ON qi.quote_id = q.entity_id

JOIN 
    lumixdb.catalog_product_entity AS cpe ON cpe.entity_id = qi.product_id

-- Imagem principal
LEFT JOIN lumixdb.catalog_product_entity_varchar AS image
    ON image.entity_id = cpe.entity_id
    AND image.attribute_id = (
        SELECT attribute_id
        FROM lumixdb.eav_attribute
        WHERE attribute_code = 'image'
        AND entity_type_id = (
            SELECT entity_type_id 
            FROM lumixdb.eav_entity_type 
            WHERE entity_type_code = 'catalog_product'
        )
    )
    AND image.store_id = 0

-- Endereço do carrinho (com telefone)
LEFT JOIN lumixdb.quote_address AS qa 
    ON qa.quote_id = q.entity_id AND qa.address_type = 'billing'

-- Fallback do telefone via grid flat
LEFT JOIN lumixdb.customer_grid_flat AS cg 
    ON cg.email = q.customer_email

WHERE 
    q.is_active = 1
    AND q.updated_at >= NOW() - INTERVAL 1 DAY
    AND q.customer_email IS NOT NULL

GROUP BY 
    q.entity_id, 
    q.customer_firstname, 
    q.customer_lastname, 
    q.customer_email, 
    q.remote_ip,
    q.items_qty, 
    q.grand_total, 
    q.updated_at,
    qa.telephone,
    cg.billing_telephone,
    image.value

ORDER BY 
    q.updated_at DESC
LIMIT 0, 1000;

     )	pymysqlconnectr   cursorcursors
DictCursorexecutefetchallclose)query
connectionr   resultss       '/var/www/html/cart_recovery/db/query.pyget_abandoned_cartsr      s    LE\ -9-Jw99: 	(fNN5!oo'G	( 	( 	(
 	s#   )B "B(	B BB B )r   configr   r   r       r   <module>r      s     Vr   