napplib


Namenapplib JSON
Version 0.3.44 PyPI version JSON
download
home_pagehttps://bitbucket.org/nappsolutionsdev/napplib.git
SummarySmall lib with custom functions to handle with azure, napp hub and custom workflows
upload_time2021-02-23 17:07:24
maintainer
docs_urlNone
authorNapp Solutions
requires_python
licenseProprietary
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ## **NappLIB**

NappLib
https://pypi.org/project/napplib/

## **Sobre**

Nós criamos essa biblioteca para auxiliar na integração dos nosso serviços e parceiros:

- Serviços Azure
- Napp HUB
- FTP e Base de dados remotas
- Conexoes com Webservices
- Plataformas de Marketplace

## **Funções**

### **Construir**

Abra o arquivo **setup.py** e altere a versão, após a mudança basta executar o arquivo abaixo:

```
./build.sh
```

### **Instalação**

```
pip install napplib
```

### **Azure Storage**

```python
from napplib.azure.blob_storage import BlobStorage
```

Função para retornar os dados do ultimo arquivo blob

```python
BlobStorage.get_latest_blob(
    account_name='AZURE_ACCOUNT_NAME',
    account_key='AZURE_ACCOUNT_KEY',
    path='AZURE_BLOB_ROOT_CONTAINER',
    project='PROJECT_NAME',
    store_name='STORE_NAME')
```

**Obs:** Vocë poderá adicionar o parametro **custom_encoding** caso seja diferente de **utf8**

Função para retornar os dados de um arquivo blob específico.

```python
BlobStorage.get_blob(
    account_name='AZURE_ACCOUNT_NAME',
    account_key='AZURE_ACCOUNT_KEY',
    path='AZURE_BLOB_ROOT_CONTAINER',
    blob_path='project/store/2020/10/23/sample.csv')
```

**Obs:** Vocë poderá adicionar o parametro **custom_encoding** caso seja diferente de **utf8**

Função que envia um arquivo local para o azure blob storage utilizando o modelo Napp, Ex: *project/store/year/month/day/file*. Temos algumas *flags* importantes, **first_charge** altera o nome do arquivo para uma nomenclatura de primeira carga (utilizado quando precisamos enviar muitos dados). **is_sale** altera o nome do arquivo para uma nomenclatura de vendas. **is_stock** altera o nome do arquivo para uma nomenclatura de estoque. Também adicionamos o "prefix" que podera compor o nome do arquivo da maneira que preferir, ex: "LOJA1-" ou "LOJA1_"

```python
BlobStorage.upload_blob(
    account_name='AZURE_ACCOUNT_NAME',
    account_key='AZURE_ACCOUNT_KEY',
    path='AZURE_BLOB_ROOT_CONTAINER',
    project='PROJECT_NAME',
    store_name='STORE_NAME',
    output_file='./files/sample.csv',
    prefix='',
    first_charge=False,
    is_sale=False,
    is_stock=False)
```

Lista todos arquivos blob de um determinado "projeto/loja"

```python
BlobStorage.list_all_blobs(
    account_name='AZURE_ACCOUNT_NAME',
    account_key='AZURE_ACCOUNT_KEY',
    path='AZURE_BLOB_ROOT_CONTAINER',
    project='PROJECT_NAME',
    store_name='STORE_NAME')
```

Para "parsear" os dados, poderá usar o seguinte modelo

```python
delimiter = '|'
lines = content.split('\n')
for line in lines:
    rows = line.split(delimiter)
    try:
        # parse here, rows[0], rows[1] ...
    except:
        # invlid line (always has one line empty)
        pass
```

**Obs**: *O split devera ocorrer por linha devido ao retorno do arquivo*

### **Napp HUB**

Importar todos modelos e controles

```python
from napplib.hub.models.product import Product
from napplib.hub.models.product import StoreProduct
from napplib.hub.models.order import Order
from napplib.hub.models.order import OrderShipping
from napplib.hub.models.order import OrderShippingAddress
from napplib.hub.models.order import OrderShippingItem
from napplib.hub.models.order import OrderCustomer
from napplib.hub.models.order import OrderCustomerAddress
from napplib.hub.models.order import OrderPayment
from napplib.hub.models.order import OrderAddress
from napplib.hub.models.order import OrderProduct
from napplib.hub.models.order import Invoice
from napplib.hub.models.order import InvoiceItem
from napplib.hub.controller import HubController
```

Variáveis necessárias para usar este controle

```python
hub_store_id = 0
hub_username = ''
hub_password = ''
hub_url = ''
```

Esta função cria todos objetos no Napp HUB  responsáveis para integrar um produto. Será necessário criar todos modelos abaixo

- product
- store product
- categories
- brands
- attributes

Essa função possui alguns gatilhos que podem ser utilizados

- **update_product**:  Esse gatilho atualiza o produto (product) quando verdadeiro, quando falso o controle ira somente criar o produto e não atualiza-lo caso exista.
- **update_store_product****: Esse gatilho atualiza o estoque da loja (storeProduct) quando verdadeiro, quando falso o controle ira somente criar o inventário e não atualiza-lo caso exista.

**Função**

```python
HubController.create_products(
    server_url=hub_url,
    token=hub_token,
    store_id=hub_store_id,
    products=hub_products,
    use_sku=True,
    update_product=True,
    update_store_product=True)
```

**Modelo StoreProduct**

```python

store_product = StoreProduct(
    storeId=HUB_STORE_ID,
    stockQuantity=0,
    salePrice=0,
    active=True,
    productCode='',
    productEan='',
    erpCode='',
    height=1,
    width=1,
    length=1,
    weight=1,
    measurementUnit='')
```

**Modelo Product**

```python
hub_product = Product(
    name='',
    description='',
    active=True,
    mainImageURL='',
    productCode='',
    productEan='',
    skuErp='',
    storeId=HUB_STORE_ID,
    attributes=[],
    categories=[],
    productBrandId=0,
    storeProduct=store_product)
```

**Modelo Payments**

```python
payments = []
order_payment = OrderPayment(
    amount='TOTAL', 
    date='DATA PAGAMENTO', 
    status='STATUS DO PAGAMENTO'
    planId='QUANTIDADE DE PARCELA'
    methodId='METODO DE PAGAMENTO CADASTRADO NO HUB'
order_payment = order_payment.__dict__
payments.append(order_payment)
```

**Modelo OrderProduct**

```python
# order item
order_items = []
order_item = OrderProduct(
    quantity='QUANTIDADE',
    salePrice='PRECO DE VENDA (FLOAT)',
    listPrice='PRECO DE TABELA',
    productDescription='DESCRICAO DO PRODUTO',
    productCode='SKU OU CODIGO DO PRODUTO',
    giftWrap='TRUE FALSE GIFT CARD'
)  
order_item = order_item.__dict__   
order_items.append(order_item)
```

**Modelo Invoices / InvoiceItem**

```python
# invoice item
invoice_items = []
invoice_item = InvoiceItem(
    productName='NOME DO PRODUTO', 
    productCode='SKU OU CODIGO DO PRODUTO', 
    quantity='QUANTIDADE', 
    value='PRECO DE VENDA', 
    totalValue='PRECO PAGO APLICADO DESCONTO'
)
invoice_item = invoice_item.__dict__
invoice_items.append(invoice_item)

invoices = []
order_invoice = Invoice(
    key='CHAVE DA NOTA',
    number='NUMERO DA NOTA'
    issueDate='DATA DA NOTA',
    orderForeignId='ID DA VENDA NO PDV',
    storeId='HUB_STORE_ID',
    itens=invoice_items,
    totalItens='QUANTIDADE TOTAL DE ITENS', 
    totalValue='TOTAL DA NOTA'
)
order_invoice = order_invoice.__dict__
invoices.append(order_invoice)
```

**Modelo OrderCustomerAddress / OrderCustomer**

```python
# create customer address
customer_addresses = []
customer_address = OrderCustomerAddress(
    address='ENDERECO', 
    addressNumber='NUMERO',
    city='CIDADE',
    country='PAIS (USAR SEMPRE O CODIGO, EX: BR)',
    zipCode='CODIGO POSTAL',
    reference='REFERENCIA',
    neighborhood='VIZINHANCA'
)
customer_address = customer_address.__dict__
customer_addresses.append(customer_address)

# create customer
customer = OrderCustomer(
    document='CPF/CNPJ',
    mainNumber='TELEFONE 1',
    secundaryNumber='TELEFONE 2',
    name='NOME',
    gender='M (MASCULINO), F (FEMININO)',
    birthDate='DATA DE ANIVERSARIO',
    email='EMAIL',
    type='PJ OU PF',
    addresses=customer_addresses)
customer = customer.__dict__
```

**Modelo OederAddress**

```python
# create order address
order_address = OrderAddress(
    billingName='NOME DO CLIENTE NA COBRANCA', 
    billingPhoneNumber='TELEFONE 1', 
    billingAddress='ENDERECO',
    billingAddressNumber='NUMERO',
    billingNeighborhood='VIZINHANCA',
    billingCity='CIDADE',
    billingState='ESTADO (EX: SP)',
    billingZipCode='CODIGO POSTAL',
    billingCountry='CODIGO DO PAIS (EX: BR)',
    billingReference='REFERENCIA',
    deliveryName='NOME DO CLIENTE PARA ENTREGA',
    deliveryAddress='ENDERECO ENTREGA',
    deliveryAddressNumber='NUMERO',
    deliveryPhoneNumber='TELEFONE 1',
    deliveryNeighborhood='VIZINHANCA',
    deliveryCity='CIDADE',
    deliveryState='ESTADO (EX: SP)',
    deliveryZipCode='CODIGO POSTAL',
    deliveryCountry='CODIGO DO PAIS (EX: BR)',
    deliveryReference='REFERENCIA'
)
order_address = order_address.__dict__
```

**Modelo Shipping, ShippingAddress e ShippingItem**

```python
# create shipping address
shipping_address = OrderShippingAddress(
    deliveryName='',
    deliveryAddress='',
    deliveryAddressNumber='',
    deliveryPhoneNumber='',
    deliveryNeighborhood='',
    deliveryCity='',
    deliveryState='',
    deliveryZipCode='',
    deliveryCountry='',
    deliveryReference=''
)
shipping_address = shipping_address.__dict__

# create shipping items
shipping_items = []
item = OrderShippingItem(
    quantity='',
    salePrice='',
    productDescription='',
    giftWrap='',
    productCode=''
)
item = item.__dict__
shipping_items.append(item)

# create shippings
shippings = []
shipping = OrderShipping(
    method='',
    estimateDeliveryDate='',
    carrierName='',
    shippingDate='',
    address='',
    trackingCode='',
    trackingURL='',
    itens=shipping_items
)
shipping = shipping.__dict__
shippings.append(shipping)    

```

**Modelo Order**

```python
order = Order(
    id='',
    storeId='', 
    orderStatus='', 
    marketplaceId='', 
    purchasedAt='',
    approvedAt='',
    updatedAt='',
    estimatedDeliveryDate='',
    totalAmount='',
    totalFreight='',
    totalDiscount='',
    totalTax='',
    totalItens='',
    deliveredDate='',
    contactName='',
    contactTelephoneNumber='',
    orderForeignId='',
    channelOrigin='',
    products=order_items,
    invoices=invoices,
    payments=payments,
    shippings=shippings,
    customer=customer,
    orderAddress=order_address
)
order = order.__dict__
```

### Criar os objetos Shipping, Invoice e Payments

```python
HubController.create_order_shipping(
    server_url=hub_url,
    token=token,
    shipping=shipping
) 

HubController.create_order_invoice(
    server_url=hub_url,
    token=token,
    invoice=invoice
)

  HubController.create_order_payment(
      server_url=hub_url,
      token=token,
      payment=payment
  )
```

### Criar e Atualizar Pedidos / Vendas

```python
# return ID to check success
update_id = HubController.update_order(
    server_url=hub_url,
    token=token,
    order=order
)

# return id to update orderId on objects like invoices, payments and shipments.
create_id = HubController.create_order(
    server_url=hub_url,
    token=token,
    order=order
)
```

### Verificar se o pedido existe no Napp HUB

```python
# search order date, format dd/MM/yyyy, Ex: 01/01/2021
search_date = ''

hub_order = HubController.get_order_by_foreign_id(
    server_url='HUB URL',
    token='HUB TOKEN',
    orderForeignId='ORDER ID',
    storeId='HUB STORE ID',
    purchasedAt=search_date
)

# create some variables
update = False
orderId = 0

# check if oder ID is != 0
if int(hub_order.get('id')) != 0:
    # enable update
    update = True

    # get orderId to use on update objects
    orderId = hub_order.get('id')
```

### **Vtex**

Importar todos modelos e controles

```python
from napplib.vtex.models.product import VtexProduct
from napplib.vtex.models.product import VtexSku
from napplib.vtex.models.product import VtexPrice
from napplib.vtex.models.product import VtexInventory
from napplib.vtex.models.product import VtexImage
from napplib.vtex.controller import VtexController
```

Variáveis necessárias para usar este controle

```python
vtex_store = ''
vtex_url = f'https://{vtex_store}.vtexcommercestable.com.br/api'
vtex_price_url = f'https://api.vtex.com/{vtex_store}/pricing'
vtex_app_key = ''
vtex_app_token = ''
```

Função do controle que cria todos objetos de produto na Vtex, será necessário criar os respectivos modelos

- product
- sku
- price
- inventory
- image

**Função**

```python

VtexController.create_products(
    base_url=vtex_url,
    base_url_price=vtex_price_url,
    app_key=vtex_app_key,
    app_token=vtex_app_token,
    products=vtex_product)
```

**Modelo Price**

```python
vtex_price = VtexPrice(
    listPrice=0,
    costPrice=0)
```

**Modelo Inventory**

```python
vtex_inventory = VtexInventory(quantity=0)
```

**Modelo Image**

```python
vtex_image = VtexImage(
    IsMain=True,
    Label='',
    Name='',
    Url='',
    Text='')
```

**Modelo SKU**

```python
vtex_sku = VtexSku(
    IsActive=True,
    Name='',
    RefId='',
    CreationDate='',
    MeasurementUnit='',
    price=vtex_price,
    inventory=vtex_inventory,
    images=vtex_image)
```

**Modelo Product**

```python
vtex_product = VtexProduct(
    Name='',
    CategoryId=0,
    BrandId=0,
    RefId='',
    IsVisible=True,
    Description='',
    DescriptionShort='',
    ReleaseDate='',
    Title='',
    IsActive=True,
    skus=vtex_sku)
```

### **Shopify**
-- 
### **MPMS**
--
### **OpaBox**
--
### **Yami**
--
### **FTP**

Importar todos os modelos e controles

```python
from napplib.ftp.controller import FTPController
```
Responsável por realizar a transferência de arquivos que chegam no ambiente FTP para o diretório local selecionado. Abaixo segue um exemplo de utilização:

```python
def download_ftp_files():
    if not os.path.exists(f'{current_path}/files'):
        os.mkdir(f'{current_path}/files')

    ftp_files = FTPController.download_ftp(
        host="www.ftpserver.com", # Endereco do ambiente
        login="user", # Usuario criado
        password="password", # Senha do usuario
        port="21", # Porta
        download_path=f'{current_path}', # Pasta de download
        extension=['csv'], # Extensao do arquivo a ser baixado
        move_downloaded_files=True # Parametro para mover arquivo apos baixado
    )

download_ftp_files()
```

### **Gmail**

Importar todos modelos e controles

```python
from napplib.google.GetAttachments import GetAttachments
```

Responsavel por realizar o download de arquivos enviados para o gmail. Abaixo um exemplo de utilizacao:

```python
from napplib.google.GetAttachments import GetAttachments

get_attachments = GetAttachments(
    query="subject: teste from: (test@gmail.com)",
    amount=1,
    pattern=None,
    download_folder='files'
)
get_attachments()

#create Path for download_path
path = Path('files')

# get files with extension (.xls)
for file in path.glob('*.xls'):
    print(f"Reading file {file}")
```

## **Desenvolvedor**

```
Napp Brain 🧠
leandro@nappsolutions.com
```


            

Raw data

            {
    "_id": null,
    "home_page": "https://bitbucket.org/nappsolutionsdev/napplib.git",
    "name": "napplib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Napp Solutions",
    "author_email": "leandro@nappsolutions.com",
    "download_url": "https://files.pythonhosted.org/packages/2c/c3/2fea724410b26371c0e43d7aa3eefa19d32b814a2d997a4812c2590c5520/napplib-0.3.44.tar.gz",
    "platform": "",
    "description": "## **NappLIB**\n\nNappLib\nhttps://pypi.org/project/napplib/\n\n## **Sobre**\n\nN\u00f3s criamos essa biblioteca para auxiliar na integra\u00e7\u00e3o dos nosso servi\u00e7os e parceiros:\n\n- Servi\u00e7os Azure\n- Napp HUB\n- FTP e Base de dados remotas\n- Conexoes com Webservices\n- Plataformas de Marketplace\n\n## **Fun\u00e7\u00f5es**\n\n### **Construir**\n\nAbra o arquivo **setup.py** e altere a vers\u00e3o, ap\u00f3s a mudan\u00e7a basta executar o arquivo abaixo:\n\n```\n./build.sh\n```\n\n### **Instala\u00e7\u00e3o**\n\n```\npip install napplib\n```\n\n### **Azure Storage**\n\n```python\nfrom napplib.azure.blob_storage import BlobStorage\n```\n\nFun\u00e7\u00e3o para retornar os dados do ultimo arquivo blob\n\n```python\nBlobStorage.get_latest_blob(\n    account_name='AZURE_ACCOUNT_NAME',\n    account_key='AZURE_ACCOUNT_KEY',\n    path='AZURE_BLOB_ROOT_CONTAINER',\n    project='PROJECT_NAME',\n    store_name='STORE_NAME')\n```\n\n**Obs:** Voc\u00eb poder\u00e1 adicionar o parametro **custom_encoding** caso seja diferente de **utf8**\n\nFun\u00e7\u00e3o para retornar os dados de um arquivo blob espec\u00edfico.\n\n```python\nBlobStorage.get_blob(\n    account_name='AZURE_ACCOUNT_NAME',\n    account_key='AZURE_ACCOUNT_KEY',\n    path='AZURE_BLOB_ROOT_CONTAINER',\n    blob_path='project/store/2020/10/23/sample.csv')\n```\n\n**Obs:** Voc\u00eb poder\u00e1 adicionar o parametro **custom_encoding** caso seja diferente de **utf8**\n\nFun\u00e7\u00e3o que envia um arquivo local para o azure blob storage utilizando o modelo Napp, Ex: *project/store/year/month/day/file*. Temos algumas *flags* importantes, **first_charge** altera o nome do arquivo para uma nomenclatura de primeira carga (utilizado quando precisamos enviar muitos dados). **is_sale** altera o nome do arquivo para uma nomenclatura de vendas. **is_stock** altera o nome do arquivo para uma nomenclatura de estoque. Tamb\u00e9m adicionamos o \"prefix\" que podera compor o nome do arquivo da maneira que preferir, ex: \"LOJA1-\" ou \"LOJA1_\"\n\n```python\nBlobStorage.upload_blob(\n    account_name='AZURE_ACCOUNT_NAME',\n    account_key='AZURE_ACCOUNT_KEY',\n    path='AZURE_BLOB_ROOT_CONTAINER',\n    project='PROJECT_NAME',\n    store_name='STORE_NAME',\n    output_file='./files/sample.csv',\n    prefix='',\n    first_charge=False,\n    is_sale=False,\n    is_stock=False)\n```\n\nLista todos arquivos blob de um determinado \"projeto/loja\"\n\n```python\nBlobStorage.list_all_blobs(\n    account_name='AZURE_ACCOUNT_NAME',\n    account_key='AZURE_ACCOUNT_KEY',\n    path='AZURE_BLOB_ROOT_CONTAINER',\n    project='PROJECT_NAME',\n    store_name='STORE_NAME')\n```\n\nPara \"parsear\" os dados, poder\u00e1 usar o seguinte modelo\n\n```python\ndelimiter = '|'\nlines = content.split('\\n')\nfor line in lines:\n    rows = line.split(delimiter)\n    try:\n        # parse here, rows[0], rows[1] ...\n    except:\n        # invlid line (always has one line empty)\n        pass\n```\n\n**Obs**: *O split devera ocorrer por linha devido ao retorno do arquivo*\n\n### **Napp HUB**\n\nImportar todos modelos e controles\n\n```python\nfrom napplib.hub.models.product import Product\nfrom napplib.hub.models.product import StoreProduct\nfrom napplib.hub.models.order import Order\nfrom napplib.hub.models.order import OrderShipping\nfrom napplib.hub.models.order import OrderShippingAddress\nfrom napplib.hub.models.order import OrderShippingItem\nfrom napplib.hub.models.order import OrderCustomer\nfrom napplib.hub.models.order import OrderCustomerAddress\nfrom napplib.hub.models.order import OrderPayment\nfrom napplib.hub.models.order import OrderAddress\nfrom napplib.hub.models.order import OrderProduct\nfrom napplib.hub.models.order import Invoice\nfrom napplib.hub.models.order import InvoiceItem\nfrom napplib.hub.controller import HubController\n```\n\nVari\u00e1veis necess\u00e1rias para usar este controle\n\n```python\nhub_store_id = 0\nhub_username = ''\nhub_password = ''\nhub_url = ''\n```\n\nEsta fun\u00e7\u00e3o cria todos objetos no Napp HUB  respons\u00e1veis para integrar um produto. Ser\u00e1 necess\u00e1rio criar todos modelos abaixo\n\n- product\n- store product\n- categories\n- brands\n- attributes\n\nEssa fun\u00e7\u00e3o possui alguns gatilhos que podem ser utilizados\n\n- **update_product**:  Esse gatilho atualiza o produto (product) quando verdadeiro, quando falso o controle ira somente criar o produto e n\u00e3o atualiza-lo caso exista.\n- **update_store_product****: Esse gatilho atualiza o estoque da loja (storeProduct) quando verdadeiro, quando falso o controle ira somente criar o invent\u00e1rio e n\u00e3o atualiza-lo caso exista.\n\n**Fun\u00e7\u00e3o**\n\n```python\nHubController.create_products(\n    server_url=hub_url,\n    token=hub_token,\n    store_id=hub_store_id,\n    products=hub_products,\n    use_sku=True,\n    update_product=True,\n    update_store_product=True)\n```\n\n**Modelo StoreProduct**\n\n```python\n\nstore_product = StoreProduct(\n    storeId=HUB_STORE_ID,\n    stockQuantity=0,\n    salePrice=0,\n    active=True,\n    productCode='',\n    productEan='',\n    erpCode='',\n    height=1,\n    width=1,\n    length=1,\n    weight=1,\n    measurementUnit='')\n```\n\n**Modelo Product**\n\n```python\nhub_product = Product(\n    name='',\n    description='',\n    active=True,\n    mainImageURL='',\n    productCode='',\n    productEan='',\n    skuErp='',\n    storeId=HUB_STORE_ID,\n    attributes=[],\n    categories=[],\n    productBrandId=0,\n    storeProduct=store_product)\n```\n\n**Modelo Payments**\n\n```python\npayments = []\norder_payment = OrderPayment(\n    amount='TOTAL', \n    date='DATA PAGAMENTO', \n    status='STATUS DO PAGAMENTO'\n    planId='QUANTIDADE DE PARCELA'\n    methodId='METODO DE PAGAMENTO CADASTRADO NO HUB'\norder_payment = order_payment.__dict__\npayments.append(order_payment)\n```\n\n**Modelo OrderProduct**\n\n```python\n# order item\norder_items = []\norder_item = OrderProduct(\n    quantity='QUANTIDADE',\n    salePrice='PRECO DE VENDA (FLOAT)',\n    listPrice='PRECO DE TABELA',\n    productDescription='DESCRICAO DO PRODUTO',\n    productCode='SKU OU CODIGO DO PRODUTO',\n    giftWrap='TRUE FALSE GIFT CARD'\n)  \norder_item = order_item.__dict__   \norder_items.append(order_item)\n```\n\n**Modelo Invoices / InvoiceItem**\n\n```python\n# invoice item\ninvoice_items = []\ninvoice_item = InvoiceItem(\n    productName='NOME DO PRODUTO', \n    productCode='SKU OU CODIGO DO PRODUTO', \n    quantity='QUANTIDADE', \n    value='PRECO DE VENDA', \n    totalValue='PRECO PAGO APLICADO DESCONTO'\n)\ninvoice_item = invoice_item.__dict__\ninvoice_items.append(invoice_item)\n\ninvoices = []\norder_invoice = Invoice(\n    key='CHAVE DA NOTA',\n    number='NUMERO DA NOTA'\n    issueDate='DATA DA NOTA',\n    orderForeignId='ID DA VENDA NO PDV',\n    storeId='HUB_STORE_ID',\n    itens=invoice_items,\n    totalItens='QUANTIDADE TOTAL DE ITENS', \n    totalValue='TOTAL DA NOTA'\n)\norder_invoice = order_invoice.__dict__\ninvoices.append(order_invoice)\n```\n\n**Modelo OrderCustomerAddress / OrderCustomer**\n\n```python\n# create customer address\ncustomer_addresses = []\ncustomer_address = OrderCustomerAddress(\n    address='ENDERECO', \n    addressNumber='NUMERO',\n    city='CIDADE',\n    country='PAIS (USAR SEMPRE O CODIGO, EX: BR)',\n    zipCode='CODIGO POSTAL',\n    reference='REFERENCIA',\n    neighborhood='VIZINHANCA'\n)\ncustomer_address = customer_address.__dict__\ncustomer_addresses.append(customer_address)\n\n# create customer\ncustomer = OrderCustomer(\n    document='CPF/CNPJ',\n    mainNumber='TELEFONE 1',\n    secundaryNumber='TELEFONE 2',\n    name='NOME',\n    gender='M (MASCULINO), F (FEMININO)',\n    birthDate='DATA DE ANIVERSARIO',\n    email='EMAIL',\n    type='PJ OU PF',\n    addresses=customer_addresses)\ncustomer = customer.__dict__\n```\n\n**Modelo OederAddress**\n\n```python\n# create order address\norder_address = OrderAddress(\n    billingName='NOME DO CLIENTE NA COBRANCA', \n    billingPhoneNumber='TELEFONE 1', \n    billingAddress='ENDERECO',\n    billingAddressNumber='NUMERO',\n    billingNeighborhood='VIZINHANCA',\n    billingCity='CIDADE',\n    billingState='ESTADO (EX: SP)',\n    billingZipCode='CODIGO POSTAL',\n    billingCountry='CODIGO DO PAIS (EX: BR)',\n    billingReference='REFERENCIA',\n    deliveryName='NOME DO CLIENTE PARA ENTREGA',\n    deliveryAddress='ENDERECO ENTREGA',\n    deliveryAddressNumber='NUMERO',\n    deliveryPhoneNumber='TELEFONE 1',\n    deliveryNeighborhood='VIZINHANCA',\n    deliveryCity='CIDADE',\n    deliveryState='ESTADO (EX: SP)',\n    deliveryZipCode='CODIGO POSTAL',\n    deliveryCountry='CODIGO DO PAIS (EX: BR)',\n    deliveryReference='REFERENCIA'\n)\norder_address = order_address.__dict__\n```\n\n**Modelo Shipping, ShippingAddress e ShippingItem**\n\n```python\n# create shipping address\nshipping_address = OrderShippingAddress(\n    deliveryName='',\n    deliveryAddress='',\n    deliveryAddressNumber='',\n    deliveryPhoneNumber='',\n    deliveryNeighborhood='',\n    deliveryCity='',\n    deliveryState='',\n    deliveryZipCode='',\n    deliveryCountry='',\n    deliveryReference=''\n)\nshipping_address = shipping_address.__dict__\n\n# create shipping items\nshipping_items = []\nitem = OrderShippingItem(\n    quantity='',\n    salePrice='',\n    productDescription='',\n    giftWrap='',\n    productCode=''\n)\nitem = item.__dict__\nshipping_items.append(item)\n\n# create shippings\nshippings = []\nshipping = OrderShipping(\n    method='',\n    estimateDeliveryDate='',\n    carrierName='',\n    shippingDate='',\n    address='',\n    trackingCode='',\n    trackingURL='',\n    itens=shipping_items\n)\nshipping = shipping.__dict__\nshippings.append(shipping)    \n\n```\n\n**Modelo Order**\n\n```python\norder = Order(\n    id='',\n    storeId='', \n    orderStatus='', \n    marketplaceId='', \n    purchasedAt='',\n    approvedAt='',\n    updatedAt='',\n    estimatedDeliveryDate='',\n    totalAmount='',\n    totalFreight='',\n    totalDiscount='',\n    totalTax='',\n    totalItens='',\n    deliveredDate='',\n    contactName='',\n    contactTelephoneNumber='',\n    orderForeignId='',\n    channelOrigin='',\n    products=order_items,\n    invoices=invoices,\n    payments=payments,\n    shippings=shippings,\n    customer=customer,\n    orderAddress=order_address\n)\norder = order.__dict__\n```\n\n### Criar os objetos Shipping, Invoice e Payments\n\n```python\nHubController.create_order_shipping(\n    server_url=hub_url,\n    token=token,\n    shipping=shipping\n) \n\nHubController.create_order_invoice(\n    server_url=hub_url,\n    token=token,\n    invoice=invoice\n)\n\n  HubController.create_order_payment(\n      server_url=hub_url,\n      token=token,\n      payment=payment\n  )\n```\n\n### Criar e Atualizar Pedidos / Vendas\n\n```python\n# return ID to check success\nupdate_id = HubController.update_order(\n    server_url=hub_url,\n    token=token,\n    order=order\n)\n\n# return id to update orderId on objects like invoices, payments and shipments.\ncreate_id = HubController.create_order(\n    server_url=hub_url,\n    token=token,\n    order=order\n)\n```\n\n### Verificar se o pedido existe no Napp HUB\n\n```python\n# search order date, format dd/MM/yyyy, Ex: 01/01/2021\nsearch_date = ''\n\nhub_order = HubController.get_order_by_foreign_id(\n    server_url='HUB URL',\n    token='HUB TOKEN',\n    orderForeignId='ORDER ID',\n    storeId='HUB STORE ID',\n    purchasedAt=search_date\n)\n\n# create some variables\nupdate = False\norderId = 0\n\n# check if oder ID is != 0\nif int(hub_order.get('id')) != 0:\n    # enable update\n    update = True\n\n    # get orderId to use on update objects\n    orderId = hub_order.get('id')\n```\n\n### **Vtex**\n\nImportar todos modelos e controles\n\n```python\nfrom napplib.vtex.models.product import VtexProduct\nfrom napplib.vtex.models.product import VtexSku\nfrom napplib.vtex.models.product import VtexPrice\nfrom napplib.vtex.models.product import VtexInventory\nfrom napplib.vtex.models.product import VtexImage\nfrom napplib.vtex.controller import VtexController\n```\n\nVari\u00e1veis necess\u00e1rias para usar este controle\n\n```python\nvtex_store = ''\nvtex_url = f'https://{vtex_store}.vtexcommercestable.com.br/api'\nvtex_price_url = f'https://api.vtex.com/{vtex_store}/pricing'\nvtex_app_key = ''\nvtex_app_token = ''\n```\n\nFun\u00e7\u00e3o do controle que cria todos objetos de produto na Vtex, ser\u00e1 necess\u00e1rio criar os respectivos modelos\n\n- product\n- sku\n- price\n- inventory\n- image\n\n**Fun\u00e7\u00e3o**\n\n```python\n\nVtexController.create_products(\n    base_url=vtex_url,\n    base_url_price=vtex_price_url,\n    app_key=vtex_app_key,\n    app_token=vtex_app_token,\n    products=vtex_product)\n```\n\n**Modelo Price**\n\n```python\nvtex_price = VtexPrice(\n    listPrice=0,\n    costPrice=0)\n```\n\n**Modelo Inventory**\n\n```python\nvtex_inventory = VtexInventory(quantity=0)\n```\n\n**Modelo Image**\n\n```python\nvtex_image = VtexImage(\n    IsMain=True,\n    Label='',\n    Name='',\n    Url='',\n    Text='')\n```\n\n**Modelo SKU**\n\n```python\nvtex_sku = VtexSku(\n    IsActive=True,\n    Name='',\n    RefId='',\n    CreationDate='',\n    MeasurementUnit='',\n    price=vtex_price,\n    inventory=vtex_inventory,\n    images=vtex_image)\n```\n\n**Modelo Product**\n\n```python\nvtex_product = VtexProduct(\n    Name='',\n    CategoryId=0,\n    BrandId=0,\n    RefId='',\n    IsVisible=True,\n    Description='',\n    DescriptionShort='',\n    ReleaseDate='',\n    Title='',\n    IsActive=True,\n    skus=vtex_sku)\n```\n\n### **Shopify**\n-- \n### **MPMS**\n--\n### **OpaBox**\n--\n### **Yami**\n--\n### **FTP**\n\nImportar todos os modelos e controles\n\n```python\nfrom napplib.ftp.controller import FTPController\n```\nRespons\u00e1vel por realizar a transfer\u00eancia de arquivos que chegam no ambiente FTP para o diret\u00f3rio local selecionado. Abaixo segue um exemplo de utiliza\u00e7\u00e3o:\n\n```python\ndef download_ftp_files():\n    if not os.path.exists(f'{current_path}/files'):\n        os.mkdir(f'{current_path}/files')\n\n    ftp_files = FTPController.download_ftp(\n        host=\"www.ftpserver.com\", # Endereco do ambiente\n        login=\"user\", # Usuario criado\n        password=\"password\", # Senha do usuario\n        port=\"21\", # Porta\n        download_path=f'{current_path}', # Pasta de download\n        extension=['csv'], # Extensao do arquivo a ser baixado\n        move_downloaded_files=True # Parametro para mover arquivo apos baixado\n    )\n\ndownload_ftp_files()\n```\n\n### **Gmail**\n\nImportar todos modelos e controles\n\n```python\nfrom napplib.google.GetAttachments import GetAttachments\n```\n\nResponsavel por realizar o download de arquivos enviados para o gmail. Abaixo um exemplo de utilizacao:\n\n```python\nfrom napplib.google.GetAttachments import GetAttachments\n\nget_attachments = GetAttachments(\n    query=\"subject: teste from: (test@gmail.com)\",\n    amount=1,\n    pattern=None,\n    download_folder='files'\n)\nget_attachments()\n\n#create Path for download_path\npath = Path('files')\n\n# get files with extension (.xls)\nfor file in path.glob('*.xls'):\n    print(f\"Reading file {file}\")\n```\n\n## **Desenvolvedor**\n\n```\nNapp Brain \ud83e\udde0\nleandro@nappsolutions.com\n```\n\n",
    "bugtrack_url": null,
    "license": "Proprietary",
    "summary": "Small lib with custom functions to handle with azure, napp hub and custom workflows",
    "version": "0.3.44",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "5efc2589f5d8e1a963eed03034ebee28",
                "sha256": "aa63bf1919920d15702c453542f606c52f1a998e2cabec77b50a89095e4c453c"
            },
            "downloads": -1,
            "filename": "napplib-0.3.44-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5efc2589f5d8e1a963eed03034ebee28",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 46631,
            "upload_time": "2021-02-23T17:07:22",
            "upload_time_iso_8601": "2021-02-23T17:07:22.786708Z",
            "url": "https://files.pythonhosted.org/packages/da/cc/fceff5f2ee0c50d7940dd5af501ae2add6f86bfa88c8c5b9ab72cf724514/napplib-0.3.44-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "d8ab286c8cd93cce8e8f8ebdb0a0ffa1",
                "sha256": "ab1ff61c9b64a6de2db4f82f3350568b715eee20e293813db9141474e9e255d0"
            },
            "downloads": -1,
            "filename": "napplib-0.3.44.tar.gz",
            "has_sig": false,
            "md5_digest": "d8ab286c8cd93cce8e8f8ebdb0a0ffa1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 46024,
            "upload_time": "2021-02-23T17:07:24",
            "upload_time_iso_8601": "2021-02-23T17:07:24.654812Z",
            "url": "https://files.pythonhosted.org/packages/2c/c3/2fea724410b26371c0e43d7aa3eefa19d32b814a2d997a4812c2590c5520/napplib-0.3.44.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-02-23 17:07:24",
    "github": false,
    "gitlab": false,
    "bitbucket": true,
    "bitbucket_user": null,
    "bitbucket_project": "nappsolutionsdev",
    "lcname": "napplib"
}
        
Elapsed time: 0.20377s