Your IP : 216.73.217.13


Current Path : /home/deltalab/PMS/recommendations/user_profiling/components/__pycache__/
Upload File :
Current File : //home/deltalab/PMS/recommendations/user_profiling/components/__pycache__/DbService.cpython-39.pyc

a

E��d�G�@svddlmZddlmZmZmZddlmZddlm	Z	ddl
mZmZddlZ
ddlmZddlZGdd	�d	�ZdS)
�)�path)�load_collectionTypes�
read_settings�read_indaco_credentials)�MongoDB)�	DataFrame)�
create_engine�textN)�Fernetc@s�eZdZdZdd�Zed�dd�Zd$ed�dd	�Zd%d
d�Zd&dd
�Z	ed�dd�Z
ed�dd�Zed�dd�Z
ed�dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�ZdS)'�	DbServiceNc	
Cs�t�}||_||dvr,t|�\}}}}}ntd|d�d��td�|dkrdt|||||�|_n,d|�d|�d|�d|�d	|��
}t|�|_dS)
NZdatabaseNamezDatabase not available! ?�?��mongodbzmssql+pymssql://�:�@�/)r�db_typer�print�exitr�
db_servicer)	�selfr�appSettings�hostname�port�username�password�db_nameZ
url_engine�r�I/home/deltalab/PMS/recommendations/user_profiling/components/DbService.py�__init__s"zDbService.__init__)�returncCs(|jdkr|j��}nd}|�|�}|S)Nra�

            SELECT cat1._id,
                cat1.label AS 'categoryName',
                cat1.googleId,
                cat2.label AS 'parent',
                cat1.isRoot,
                cat1.isLeaf,
                cat1.createdAt,
                cat1.updatedAt
            FROM dbo.pms_categories cat1
            INNER JOIN dbo.pms_categories cat2 ON (cat1.parentId = cat2._id)

            )rrZgetProductTypes�
execute_query)rZproductTypes�queryrrr�get_productTypes!s


zDbService.get_productTypesFcs||jdkr|j�||�}n^d}|�|�}|djddd�t�dd�}t|d	d
�\}}|d�|d��fdd��|d<|S)
Nra~


             SELECT DISTINCT pms_products.title, 
                pms_products_offers.sku, 
                pms_products.brand, 
                pms_products.refrigerated, 
                pms_products.weight AS 'weight [grams]', 
                pms_products_offers.ID AS '_id', 
                pms_products_offers.channelId AS 'channel',
                pms_products.categoryId, 
                pms_products.partnerId, 
                warehouseId, 
                ISNULL(
                    indaco_general_productionarea,-1
                ) AS 'production_areas', 
                ISNULL(indaco_generalfood_biologic, 0) AS 'biologic', 
                ISNULL(indaco_generalfood_vegan, 0) AS 'vegan', 
                ISNULL(
                    indaco_generalfood_biodynamic, 0
                ) AS 'biodinamic', 
                ISNULL(
                    indaco_generalfood_glutenfree, 0
                ) AS 'gluten_free', 
                ISNULL(indaco_general_isforadult, 0) AS 'isforadult' 
                FROM 
                pms_products 
                INNER JOIN pms_products_offers ON (
                    pms_products._id = pms_products_offers.parent_id
                ) 
                INNER JOIN pms_channels ON (pms_products_offers.channelId = pms_channels._id)

                INNER JOIN pms_products_inventoryLevels_object ON(
                    pms_products._id = pms_products_inventoryLevels_object.parent_ID
                ) 
                FULL OUTER JOIN (
                    SELECT 
                    parent_id, 
                    indaco_general_productionarea, 
                    indaco_generalfood_biologic, 
                    indaco_generalfood_vegan, 
                    indaco_generalfood_biodynamic, 
                    indaco_generalfood_glutenfree, 
                    indaco_general_isforadult 
                    FROM 
                    (
                        SELECT 
                        parent_id, 
                        NAME, 
                        value 
                        FROM 
                        pms_products_offers_attributes
                    ) s PIVOT (
                        Max(value) FOR NAME IN (
                        indaco_general_productionarea, indaco_generalfood_biologic, 
                        indaco_generalfood_vegan, indaco_generalfood_biodynamic, 
                        indaco_generalfood_glutenfree, 
                        indaco_general_isforadult
                        )
                    ) AS p
                ) AS p ON (pms_products._id = p.parent_id) 
                WHERE 
                pms_products_offers.deleted = 0
            
            �production_areas���T)�inplace�_libraryzINDACO_collectionCodes.jsonF)�verbosecs<t|����vr �t|���St|�dkr8d|�d�SdS)Nr%zUnknown (code:�)�)�str�keys�
capitalize�int)Z	area_code��productionArea_codesrr�<lambda>�s
�
�z(DbService.get_products.<locals>.<lambda>)	rrZgetProductsr!�fillnar�joinr�apply)rZconsider_delatedProductsZconsider_unavailableProducts�productsr"�	file_path�_ZcollectionTypesrr/r�get_products8s
A

�zDbService.get_productscCsZ|jdkr|j�||�}n<|s2d|�d|�d�}nd|�d�}|�|�}|�d�d}|S)Nrz�

                    SELECT ID AS '_id',
                            sku
                        FROM pms_products_offers
                        WHERE sku = 'z+'
                        AND channelId = 'z'
                z�

                    SELECT _id,
                            sku
                        FROM pms_products
                        WHERE sku = '�recordsr)rrZ
getProductr!�to_dict)rZitem_sku�as_dict�channel�productr"rrr�
get_dBproduct�s
��
	�
zDbService.get_dBproductcCs*|jdkr|j�|�}nd}|�|�}|S)Nra.

             SELECT 
                pms_partners._id, 
                companyName, 
                email, 
                address, 
                pms_partners.phone, 
                pms_warehouses._id AS "warehouse_id", 
                vatNumber, 
                active, 
                pms_partners.createdAt, 
                pms_partners.updatedAt 
                FROM 
                pms_partners 
                INNER JOIN pms_warehouses ON (
                    pms_partners._id = pms_warehouses.partnerId
                )

            )rrZ
getSellersr!)rZsellerId�sellersr"rrr�get_sellers�s


zDbService.get_sellerscCs(|jdkr|j��}nd}|�|�}|S)Nra{

             SELECT _id,
                    name,
                    phone,
                    type,
                    size,
                    isIndaco,
                    isShared,
                    partnerId,
                    refrigerated,
                    createdAt,
                    updatedAt
                FROM pms_warehouses
            
            )rrZ
getWarehousesr!)r�
warehousesr"rrr�get_warehouses�s


zDbService.get_warehousescs`�jdkr�j��}nFd}��|�}��|d���|d��fdd��}|jdd|d�|S)	Nra�
              SELECT DISTINCT dbo.magento_sales_order.entity_id AS 'Transaction id',
                dbo.magento_sales_order.created_at AS 'timestamp',
                dbo.magento_customer_entity.email AS 'customer',
                name AS 'product_name',
                sku,
                qty_ordered AS 'quantity',
                consent4 as 'consenso_dati_particolari',
                adult as 'consenso_adult'
            FROM dbo.magento_sales_order
                        
                        
            INNER JOIN (SELECT email,consent2,consent4,adult, 
            MAX([timestamp]) AS most_recent_signin
            FROM dbo.iubenda_consent
            WHERE consent2 IS NOT NULL AND email IS NOT NULL
            GROUP BY email,consent2,consent4,adult) AS t_consensi
                        ON (dbo.magento_sales_order.customer_email = t_consensi.email)
                        INNER JOIN dbo.magento_customer_entity
                        ON (customer_id = dbo.magento_customer_entity.entity_id)
                        INNER JOIN dbo.magento_sales_order_item
                        ON (dbo.magento_sales_order.entity_id = dbo.magento_sales_order_item.order_id)
                        WHERE t_consensi.consent2 = 1

            �customercstj�j|S�N)r�anonymized_customers�_DbService__encrypted_customers)rC�rrrr1��z&DbService.get_orders.<locals>.<lambda>��customer_id)�column�value)rrZ	getOrdersr!�_DbService__encryptCustomers�uniquer4�insert)r�ordersr"�customer_idsrrGr�
get_orders�s


�zDbService.get_orderscCs@|jdkr|j�|�}n$d|�d�}|�|�}|�d�d}|S)Nrz{

                SELECT _id,
                    label
                FROM pms_categories
                WHERE label = 'z'
            r9r)rrZgetCategoryInfor!r:)rZ
category_nameZcategoryInfor"rrr�get_productTypeInfos
�
zDbService.get_productTypeInfocCs&|jdkr|j�|�}n
|�|�}|S�Nr)rr�decryptCustomers)rZuserIds�decryptedUsersrrr�get_decryptedUserss

zDbService.get_decryptedUserscCsBt|�}|j���}t�||�}Wd�n1s40Y|SrD)r	r�begin�pd�read_sql_query)rZ	query_strr"�connZtoRtnrrrr! s*zDbService.execute_queryc	Cs2td�\}}}}}t|||||�}|�||�dSrT)rr�writeNewDbItem)	r�	tableName�objectrrrrrrrrr�write_newDbItem&szDbService.write_newDbItemcCs0td�\}}}}}t|||||�}|�|�dSrT)rr�dropCollection)rr]rrrrrrrrr�drop_existingTable+szDbService.drop_existingTablec
Cs4td�\}}}}}t|||||�}	|	�|||�dSrT)rrZsetNewProductAttribute)
rr^�attribute_nameZattribute_valuerrrrrrrrr�update_attributeDbItem0sz DbService.update_attributeDbItemcCsTttj�}ttttj����}t�}|D]&}||��vr(|�	||��
�||<q(|SrD)r
r�ENCRYPTING_KEY�dict�map�reversedrE�itemsr,Zdecrypt�decode)rrQ�fernetZanonymity_reverseMappingrVrJrrrrU6s
zDbService.decryptCustomerscsZtjst��t_ttj���fdd�|D�}tt||��|_dd�t|j���D�t_	dS)Ncsg|]}��|����qSr)Zencrypt�encode)�.0rC�rjrr�
<listcomp>NrHz0DbService.__encryptCustomers.<locals>.<listcomp>cSsi|]\}}||d�qS)r
r)rl�idkZencrypted_customerrrr�
<dictcomp>Qs�z0DbService.__encryptCustomers.<locals>.<dictcomp>)
rrdr
Zgenerate_keyre�ziprF�	enumerate�valuesrE)rZunique_customersZencryptedCustomersrrmrZ__encryptCustomersFs

�zDbService.__encryptCustomersc
s�|j|ddd�}|j|dddd�}dd�|jd	d
�D��|d��fdd
��|d<dddddddddd�	�|d��}|j|dfj����fdd
��|j|df<d}|dj|d�|d<|djdd�|d<|jddgdd�|j	ddidd�t
|�t
|�k�rNt�|d�
�|d�
��}	tt
|	��d��td�tdd �t|	���t|j|d|kdf���}
t
|
�d!k�r�td"d#�td$t
|
��d%|�d&��td"d#�tdd �d'd(�t|
�D���|j	d)d*d+d,d-d.d/d0�dd�|d.�d1d
��|d2<t
�d3������fd4d
��|d*��fd5d
��|d6<|d/�t�|d/<|d+jdd�|d+<gd7�}||}|�d8d8d8d8d8d9d:��}|S);NZ	partnerId�_id)�left_on�right_on�leftZ
categoryId)�howrurvcSsi|]}|d|d�qS)rt�namer)rl�itemrrrrpYrHz2DbService.enhanced_products_df.<locals>.<dictcomp>r9)�orientZwarehouse_idcs�|SrDr)rA)�warehouse_namesrrr1[rHz0DbService.enhanced_products_df.<locals>.<lambda>rAZ	Formaggio)	zaffogato di sabbionaraucasolét val di solez
cuor di fassazfontal di cavalesez!mezzano trentino di alta montagnazprimiero frescozpuzzone di moena dopztrentingrana 1kgztrentingrana 250gr�categoryName�titlecs|���vr�|StjSrD)r,�np�nan)Zproduct_name)�manual_catMappingrrr1krHr*)rL�googleIdr%Z_id_yZisLeafT)�columnsr&Z_id_xzC products have been discarted due to an issue with the "categoryId"zK---------------------------------------------------------------------------z-->z
--> rzF----------------------------------------------------------------------zG
----------------------------------------------------------------------z9[WARNING] The attribute "categoryId" has not been set to z9 products. 
It has been filled with a category equal to "�"cSs(g|] \}}dt|d�d|�qS)�(r
z) )r+)rlrorzrrrrn�s�z2DbService.enhanced_products_df.<locals>.<listcomp>�Title�
indaco_sku�Vendor�Product Type�Type id�SellerZ	productId)r~�skuZbrandr}r�ZcompanyNamertcSs|dkrdSdS)NZVendi24TFr)ryrrrr1�rH�inTrentino_source�Transaction idcs"t�j�d|kdf����S)Nr�r�)�len�locrN�r�)�num_transactionsrPrrr1�rHcst��|�d�S)N�)r�roundr�)�normalizedFreq_funcrrr1�rH�	Frequency)r�r�r�r��refrigeratedzweight [grams]rAr�r$r�r�r��biologic�
isforadult�vegan�
biodinamic�gluten_freer<�int32r+)r�r�r�r�r�r<)�merger:r4�isnullr�r+�lowerr2�drop�renamer�r�	setdiff1d�to_numpyrr3�sorted�tolistrrrN�astype)rr5�
categoriesr?rArPZenhanced_dfZnanCondZemptyCategory_valueZdiscarted_productsZitem_w_unknownCategoryZrelevant_columnsr)r�r�r�rPr|r�enhanced_products_dfTs�
��
�
�
�

�
���zDbService.enhanced_products_df)FF)NF)N)�__name__�
__module__�__qualname__rdrrr#r8r>r@rBrRrerSrWr!r_rarcrUrMr�rrrrrs"U

)r)�osr�_library.io_toolkitrrrZcomponents.mongoDbServicer�pandasr�
sqlalchemyrr	rYZcryptography.fernetr
�numpyrrrrrr�<module>s