
    u(i=                         d dl mZ d dlmZmZmZmZ ddlmZm	Z	 d dl
Z
d dlZd dlmZ  ej                  e      Z G d d      Zy)	    )Session)ListOptionalDictAny   )modelsschemasN)IntegrityErrorc                      e Zd ZdZdefdZdej                  dej                  fdZ
dej                  dej                  fdZd	ej                  dej                  fd
Zdej"                  dej$                  fdZdej(                  dej*                  fdZdededeej2                     fdZdededeej6                     fdZdej:                  dej                  fdZdej>                  de e!e"f   fdZ#de e!e"f   de e!e"f   fdZ$d#dedede%ej                     fdZ&dedeej                     fdZ'de%ej                     fdZ(de%ej                     fdZ)de%ej$                     fd Z*d#dedede%ej*                     fd!Z+y")$ProductServicez,Service class for product-related operationsdbc                     || _         y )N)r   )selfr   s     I/var/www/html/hubwallet-dev/src/smart_inventory/apps/products/services.py__init__zProductService.__init__   s	        product_datareturnc                    | j                   j                  t        j                        j	                  t        j                  j
                  |j
                  k(        j                         }|rl|j                  d      j                         D ]  \  }}t        |||        | j                   j                          | j                   j                  |       |S t        j                  di |j                         }| j                   j                  |       | j                   j                          | j                   j                  |       |S )z&Get existing product or create new oneTexclude_unset )r   queryr	   Productfilter
product_idfirst
model_dumpitemssetattrcommitrefreshadd)r   r   existing_productfieldvalue
db_products         r   get_or_create_productz$ProductService.get_or_create_product   s    77==8??NN%%)@)@@

%' 	  , 7 7d 7 K Q Q S 8u(%78GGNNGGOO,-##  D,*A*A*CDJGGKK
#GGNNGGOOJ'r   location_datac                    | j                   j                  t        j                        j	                  t        j                  j
                  |j
                  k(        j                         }|rl|j                  d      j                         D ]  \  }}t        |||        | j                   j                          | j                   j                  |       |S t        j                  di |j                         }| j                   j                  |       | j                   j                          | j                   j                  |       |S )z'Get existing location or create new oneTr   r   )r   r   r	   Locationr   location_idr   r   r    r!   r"   r#   r$   )r   r*   existing_locationr&   r'   db_locations         r   get_or_create_locationz%ProductService.get_or_create_location&        GGMM&//:AAOO''=+D+DD

%' 	  - 8 8t 8 L R R T 9u)5%89GGNNGGOO-.$$ !//GM,D,D,FGKGGKK$GGNNGGOOK(r   vendor_datac                    | j                   j                  t        j                        j	                  t        j                  j
                  |j
                  k(        j                         }|rl|j                  d      j                         D ]  \  }}t        |||        | j                   j                          | j                   j                  |       |S t        j                  di |j                         }| j                   j                  |       | j                   j                          | j                   j                  |       |S )z%Get existing vendor or create new oneTr   r   )r   r   r	   Vendorr   	vendor_idr   r   r    r!   r"   r#   r$   )r   r2   existing_vendorr&   r'   	db_vendors         r   get_or_create_vendorz#ProductService.get_or_create_vendor;   s    ''--6==MM##{'<'<<

%' 	  + 6 6T 6 J P P R 7u67GGNNGGOOO,"" A(>(>(@AIGGKK	"GGNNGGOOI&r   category_datac                    | j                   j                  t        j                        j	                  t        j                  j
                  |j
                  k(        j                         }|rl|j                  d      j                         D ]  \  }}t        |||        | j                   j                          | j                   j                  |       |S t        j                  di |j                         }| j                   j                  |       | j                   j                          | j                   j                  |       |S )z'Get existing category or create new oneTr   r   )r   r   r	   Categoryr   category_idr   r   r    r!   r"   r#   r$   )r   r9   existing_categoryr&   r'   db_categorys         r   get_or_create_categoryz%ProductService.get_or_create_categoryP   r1   r   
price_datac                    | j                   j                  t        j                        j	                  t        j                  j
                  |j
                  k(        j                         }|rl|j                  d      j                         D ]  \  }}t        |||        | j                   j                          | j                   j                  |       |S t        j                  di |j                         }| j                   j                  |       | j                   j                          | j                   j                  |       |S )z,Get existing product price or create new oneTr   r   )r   r   r	   ProductPricer   product_price_idr   r   r    r!   r"   r#   r$   )r   r@   existing_pricer&   r'   db_prices         r   get_or_create_product_pricez*ProductService.get_or_create_product_pricee   s    v':':;BB00J4O4OO

%' 	  * 5 5D 5 I O O Q 6uu56GGNNGGOON+!! **EZ-B-B-DEHGGKK!GGNNGGOOH%Or   r   r5   c                 `   | j                   j                  t        j                        j	                  t        j                  j
                  |k(  t        j                  j                  |k(        j                         }|sj	 t        j                  ||      }| j                   j                  |       | j                   j                          | j                   j                  |       |S |S # t        $ r8 | j                   j                          t        j                  d| d|        Y yw xY w)z1Create product-vendor mapping if it doesn't exist)r   r5   z'Product-Vendor mapping already exists: -N)r   r   r	   ProductVendorr   r   r5   r   r$   r"   r#   r   rollbackloggerwarning)r   r   r5   existing_mapping
db_mappings        r   create_product_vendor_mappingz,ProductService.create_product_vendor_mappingz   s    77==)=)=>EE  ++z9  **i7
 %' 	
  	#11ZS\]
J' 
+!!   "   "!HTUV_U`ab   A(C, ,>D-,D-r-   c                 `   | j                   j                  t        j                        j	                  t        j                  j
                  |k(  t        j                  j                  |k(        j                         }|sj	 t        j                  ||      }| j                   j                  |       | j                   j                          | j                   j                  |       |S |S # t        $ r8 | j                   j                          t        j                  d| d|        Y yw xY w)z3Create product-location mapping if it doesn't exist)r   r-   z)Product-Location mapping already exists: rH   N)r   r   r	   ProductLocationr   r   r-   r   r$   r"   r#   r   rJ   rK   rL   )r   r   r-   rM   rN   s        r   create_product_location_mappingz.ProductService.create_product_location_mapping   s    77==)?)?@GG""--;""..+=
 %' 	
  	#33zWbc
J' 
+!!   "   "!J:,VWXcWdefrP   api_productc                 Z   	 d}|j                   r1t        |j                         dkD  r|j                   d   j                  }|j                  rH|j                  r<t        j                  |j                  |j                        }| j                  |       t        j                  |j                  |j                  |j                  |j                  |j                  |j                  ||j                  |j                  |j                   
      }| j#                  |      }|j$                  rs|j$                  D ]d  }t        j&                  |j(                  |j*                        }| j-                  |       | j/                  |j                  |j(                         f |j0                  r|j0                  D ]  }| j2                  j5                  t6        j8                        j;                  t6        j8                  j<                  |j>                  k(        jA                         }	|	stB        jE                  d|j>                   d       t        j&                  |j>                  d|j>                         }
| j-                  |
       | j/                  |j                  |j>                         t        jF                  |jH                  |j                  |j>                  |jJ                  |jL                  |jN                  |jP                  |jR                  |jT                  |jV                  
      }| jY                  |        |jZ                  r~|jZ                  D ]o  }t        j\                  |j^                  |j`                  |jb                  	      }| je                  |       | jg                  |j                  |j^                         q |S # th        $ rN}tB        jk                  d
|j                   dtm        |              | j2                  jo                           d}~ww xY w)z@Process a single product from API response and store in databaseNr   )r<   category_name)
r   product_name
short_namedescription
brand_namefk_product_category_id
image_patheligible_for_returndisplay_on_posdisplay_on_online_store)r-   location_namez	Location z, not found, creating minimal location record)
rC   r   r-   cost_price_per_unitmarkup_valuemargin_valueretail_price_excl_taxcompare_at_pricemarkup_type_namemargin_type_name)r5   vendor_namevendor_codeError processing product : )8productImageslen	imagePathfkProductCategoryIdcategoryNamer
   CategoryCreater?   ProductCreate	productIdproductName	shortNamerY   	brandNameeligibleForReturndisplayOnPOSdisplayOnOnlineStorer)   	locationsLocationCreate
locationIdlocationNamer0   rS   pricesr   r   r	   r,   r   r-   fkLocationIdr   rK   rL   ProductPriceCreateproductPriceIdcostPricePerUnitmarkupValuemarginValueretailPriceExclTaxcompareAtPricemarkupTypeNamemarginTypeNamerF   vendorsVendorCreatevendorId
vendorName
vendorCoder8   rO   	ExceptionerrorstrrJ   )r   rT   r\   r9   r   r(   locationr*   pricer.   minimal_location_dataprice_data_itemvendorr2   es                  r   process_api_productz"ProductService.process_api_product   s   Z	J((S1J1J-Ka-O(66q9CC
 ..;3K3K ' 6 6 + ? ?"-":":! ++M: #00&00(44&00'33&00'2'F'F%$/$A$A*77(3(H(HL 33LAJ $$ + 5 5 eH$+$:$:$,$7$7&.&;&;%M //>889N9NPXPcPcde !!(// FE(,foo(F(M(M33u7I7II)eg & -53E3E2FFr'st070F0F(-(:(:,5e6H6H5I*J1- 334IJ<<[=R=RTYTfTfg '.&@&@).)=)=#.#8#8$)$6$6,1,B,B%*%6%6%*%6%6.3.F.F).)=)=).)=)=).)=)='O 44_E9F> "")11 _F")"6"6"(//$*$5$5$*$5$5#K
 --k:66{7L7Lfoo^_  	LL4[5J5J4K2cRSfXVWGG	s   OO 	P*A	P%%P*request_datac                 b   d}|j                   |j                  |j                  d}ddd}	 t        j                  |||d      }|j                          |j                         }t        j                  d|j                  d	d
              |S # t        j                  j                  $ r=}t        j                  dt        |              t        dt        |             d}~wt        $ r=}t        j                  dt        |              t        dt        |             d}~ww xY w)z Fetch products from external APIzLhttps://hubwalletdev-api.myteamconnector.com/api/AIIntegration/ProductSearch)	companyId
pageNumberpageSizez*/*zapplication/json)acceptzContent-Type<   )jsonheaderstimeoutzAPI response received: successFzAPI request failed: NzJSON decode error: zInvalid JSON response: )
company_idpage_number	page_sizerequestspostraise_for_statusr   rK   infoget
exceptionsRequestExceptionr   r   RuntimeError
ValueError)r   r   api_urlpayloadr   responseapi_responser   s           r   fetch_products_from_apiz&ProductService.fetch_products_from_api  s   ` &00&22$..
 .

	C}}W7GUWXH%%'#==?LKK1,2B2B9e2T1UVW""33 	@LL/Ax89!5c!fX>?? 	CLL.s1vh78!8QABB	Cs$   A"B D.-8C%%D.18D))D.r   c                    	 |j                  dd      s |j                  dd      }t        d|       |j                  di       }|j                  dg       }d}g }|D ].  }	 t        j                  di |}| j	                  |       |d	z  }0 dt        |      |t        |      |d}
|rd|
d<   |
S # t
        $ rQ}	d
|j                  dd       dt        |	       }t        j                  |       |j                  |       Y d}	~	d}	~	ww xY w# t
        $ rV}	t        j                  dt        |	              | j                  j                          dt        |	      ddd	dcY d}	~	S d}	~	ww xY w)z@Process the complete API response and store products in databaser   FerrorMessagezUnknown API errorzAPI returned error: datar    r   r   rj   rs   unknownrk   NT)r   total_itemsprocessed_counterror_counterrorszError processing API response: )r   r   r   r   r   r   )r   r   r
   
APIProductr   r   r   rK   r   appendrm   r   rJ   )r   r   	error_msgr   r    r   r   	item_datarT   r   results              r   process_api_responsez#ProductService.process_api_response"  s   +	##Iu5(,,^=PQ	 #7	{!CDD##FB/DHHWb)EOF" -	-")"4"4"Ay"AK,,[9#q(O	-  "5z#2"6{ F $)y!M! ! -";IMM+W`<a;bbdehijekdl mILL+MM),,-$  		LL:3q6(CDGG Q #$  		sJ   AD "+B2$D 2	D;ADD DD 	E.AE)#E.)E.skiplimitc                     | j                   j                  t        j                        j	                  |      j                  |      j                         S )zGet products with pagination)r   r   r	   r   offsetr   allr   r   r   s      r   get_productszProductService.get_productsQ  s8    ww}}V^^,33D9??FJJLLr   c                     | j                   j                  t        j                        j	                  t        j                  j
                  |k(        j                         S )z"Get product by external product ID)r   r   r	   r   r   r   r   )r   r   s     r   get_product_by_idz ProductService.get_product_by_idU  s=    ww}}V^^,33FNN4M4MQ[4[\bbddr   c                 p    | j                   j                  t        j                        j	                         S )zGet all locations)r   r   r	   r,   r   r   s    r   get_locationszProductService.get_locationsY  "    ww}}V__-1133r   c                 p    | j                   j                  t        j                        j	                         S )zGet all vendors)r   r   r	   r4   r   r   s    r   get_vendorszProductService.get_vendors]  s"    ww}}V]]+//11r   c                 p    | j                   j                  t        j                        j	                         S )zGet all categories)r   r   r	   r;   r   r   s    r   get_categorieszProductService.get_categoriesa  r   r   c                     | j                   j                  t        j                        j	                  |      j                  |      j                         S )zGet all prices with pagination)r   r   r	   rB   r   r   r   r   s      r   get_all_priceszProductService.get_all_pricese  s:    ww}}V00188>DDUKOOQQr   N)r   d   ),__name__
__module____qualname____doc__r   r   r
   rr   r	   r   r)   r{   r,   r0   r   r4   r8   rq   r;   r?   r   rB   rF   intr   rI   rO   rR   rS   r   r   ProductFetchRequestr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s   67 '2G2G FNN *G4J4J v *0D0D  *G4J4J v *g6P6P U[UhUh *     PXY_YmYmPn  * #  C  T\]c]s]sTt  *\w/A/A \fnn \|CG4O4O CTXY\^aYaTb C@-c3h -DcN -^M M MtFNN?S MeC eHV^^4L e4tFOO4 42T&--0 24V__ 5 4R3 R3 RfFYFYAZ Rr   r   )sqlalchemy.ormr   typingr   r   r   r    r	   r
   r   loggingsqlalchemy.excr   	getLoggerr   rK   r   r   r   r   <module>r      s:    " , ,    )			8	$\R \Rr   