### Install NaloGO Python Package Source: https://context7.com/rusik636/nalogo/llms.txt Installs the NaloGO asynchronous Python library using pip. This is the primary method to get the library into your Python environment. ```bash pip install nalogo ``` -------------------------------- ### Create Multi-Item Receipt in Python Source: https://context7.com/rusik636/nalogo/llms.txt This example shows how to create a receipt with multiple service items using the nalogo Python SDK. It defines service items with specific amounts and quantities using `IncomeServiceItem`. It also demonstrates calculating the expected total and includes the UUID of the created receipt. It utilizes the Decimal type for precise monetary calculations. ```python import asyncio from decimal import Decimal from nalogo import Client from nalogo.dto.income import IncomeServiceItem async def create_multi_item_receipt(client: Client): income_api = client.income() # Define multiple service items with Decimal precision services = [ IncomeServiceItem( name="Website development", amount=Decimal("50000.00"), quantity=Decimal("1") ), IncomeServiceItem( name="Monthly maintenance", amount=Decimal("5000.00"), quantity=Decimal("3") # 3 months ), IncomeServiceItem( name="SEO optimization", amount=Decimal("15000.00"), quantity=Decimal("1") ) ] # Calculate expected total: 50000 + (5000 * 3) + 15000 = 80000 expected_total = sum(s.amount * s.quantity for s in services) print(f"Expected total: {expected_total}") result = await income_api.create_multiple_items(services) receipt_uuid = result["approvedReceiptUuid"] print(f"Multi-item receipt created: {receipt_uuid}") return receipt_uuid # asyncio.run(create_multi_item_receipt(authenticated_client)) ``` -------------------------------- ### Authenticate NaloGO Client with INN and Password in Python Source: https://context7.com/rusik636/nalogo/llms.txt Guides through authenticating the NaloGO client using INN and password. It involves two steps: creating an access token with credentials and then activating the client with the obtained token. Handles `UnauthorizedException` and `DomainException`. ```python import asyncio from nalogo import Client from nalogo.exceptions import UnauthorizedException, DomainException async def authenticate_with_credentials(): client = Client(storage_path="./tokens.json") try: # Step 1: Create access token with INN and password token_json = await client.create_new_access_token( username="123456789012", # Your 12-digit INN password="your_password" ) # Step 2: Activate the client with the token await client.authenticate(token_json) print("Authentication successful!") # Token is automatically saved to storage_path if configured current_token = await client.get_access_token() print(f"Token stored: {current_token is not None}") return client except UnauthorizedException as e: print(f"Invalid credentials: {e}") except DomainException as e: print(f"API error: {e}") if e.response: print(f"Status code: {e.response.status_code}") asyncio.run(authenticate_with_credentials()) ``` -------------------------------- ### Complete Workflow with Python nalogo Client Source: https://context7.com/rusik636/nalogo/llms.txt An end-to-end example showcasing the nalogo client's capabilities, including authentication with token persistence, creating single and multi-item receipts, retrieving receipt details, and fetching user and tax information. It handles potential `UnauthorizedException` and `DomainException` errors. ```python import asyncio from decimal import Decimal from nalogo import Client from nalogo.dto.income import IncomeClient, IncomeServiceItem, IncomeType from nalogo.exceptions import DomainException, UnauthorizedException async def complete_workflow(): # Initialize client with token persistence client = Client( storage_path="./nalogo_tokens.json", device_id="my-app-device-001" ) try: # Authenticate token = await client.create_new_access_token("123456789012", "password") await client.authenticate(token) print("Authenticated successfully") # Create a receipt for individual client income_api = client.income() result = await income_api.create( name="Freelance development", amount=Decimal("30000.00"), quantity=1 ) receipt_uuid = result["approvedReceiptUuid"] print(f"Receipt created: {receipt_uuid}") # Create multi-item receipt for legal entity services = [ IncomeServiceItem(name="Design", amount=Decimal("15000"), quantity=Decimal("1")), IncomeServiceItem(name="Development", amount=Decimal("45000"), quantity=Decimal("1")) ] legal_client = IncomeClient( display_name="Tech Corp LLC", income_type=IncomeType.FROM_LEGAL_ENTITY, inn="9876543210" ) result = await income_api.create_multiple_items(services, client=legal_client) print(f"Corporate receipt: {result['approvedReceiptUuid']}") # Get receipt details receipt_api = client.receipt() receipt_data = await receipt_api.json(receipt_uuid) print_url = receipt_api.print_url(receipt_uuid) print(f"Receipt total: {receipt_data.get('totalAmount')}") print(f"Print URL: {print_url}") # Get user and tax info user_data = await client.user().get() print(f"User: {user_data.get('displayName')}") tax_data = await client.tax().get() print(f"Tax info retrieved: {tax_data is not None}") # Get payment methods payment_types = await client.payment_type().table() print(f"Payment methods: {len(payment_types)}") except UnauthorizedException: print("Invalid credentials") except DomainException as e: print(f"API error: {e}") asyncio.run(complete_workflow()) ``` -------------------------------- ### Get Authenticated User Profile Information with Python Source: https://context7.com/rusik636/nalogo/llms.txt Retrieves the authenticated user's profile details, including INN, contact information, and registration status. Returns a dictionary containing user data. Requires an authenticated `nalogo.Client` instance. ```python import asyncio from nalogo import Client async def get_user_profile(client: Client): user_api = client.user() user_data = await user_api.get() # Available user profile fields: print(f"Display name: {user_data.get('displayName')}") print(f"INN: {user_data.get('inn')}") print(f"Phone: {user_data.get('phone')}") print(f"Email: {user_data.get('email', 'Not set')}") print(f"Registration date: {user_data.get('registrationDate')}") print(f"Status: {user_data.get('status')}") return user_data # asyncio.run(get_user_profile(authenticated_client)) ``` -------------------------------- ### Initialize NaloGO Client in Python Source: https://context7.com/rusik636/nalogo/llms.txt Demonstrates how to initialize the `Client` class, the main entry point for NaloGO. It shows basic initialization with defaults and a fully configured client with custom base URL, token storage path, device ID, and HTTP timeout. ```python import asyncio from nalogo import Client async def main(): # Basic initialization with defaults client = Client() # Full configuration client = Client( base_url="https://lknpd.nalog.ru/api", # API endpoint storage_path="./tokens.json", # Persist tokens to file device_id="my-unique-device-id", # Custom device identifier timeout=10.0 # HTTP timeout in seconds ) print(f"Client initialized with base URL: {client.base_url}") asyncio.run(main()) ``` -------------------------------- ### Create Legal Entity Receipt in Python Source: https://context7.com/rusik636/nalogo/llms.txt This code demonstrates how to create an income receipt for a legal entity using the nalogo Python SDK. It shows how to define the client information, including the contact phone, display name, income type, and INN using `IncomeClient` and `IncomeType`. The receipt creation uses the create method of the income_api and includes error handling. ```python import asyncio from decimal import Decimal from nalogo import Client from nalogo.dto.income import IncomeClient, IncomeType async def create_legal_entity_receipt(client: Client): income_api = client.income() # Define legal entity client information legal_client = IncomeClient( contact_phone="+79001234567", display_name="LLC 'Innovation Tech'", # Required for legal entities income_type=IncomeType.FROM_LEGAL_ENTITY, inn="1234567890" # 10-digit INN for legal entities ) # Available income types: # - IncomeType.FROM_INDIVIDUAL (default) # - IncomeType.FROM_LEGAL_ENTITY # - IncomeType.FROM_FOREIGN_AGENCY result = await income_api.create( name="Software development contract", amount=Decimal("250000.00"), quantity=1, client=legal_client ) print(f"Corporate receipt: {result['approvedReceiptUuid']}") return result # asyncio.run(create_legal_entity_receipt(authenticated_client)) ``` -------------------------------- ### Create Simple Income Receipt in Python Source: https://context7.com/rusik636/nalogo/llms.txt This code demonstrates how to create a simple income receipt for a single service item using the nalogo Python SDK. It shows how to specify the service name, amount, and quantity. It also handles automatic conversion of amounts to Decimal and provides error handling for validation and invalid input exceptions. The result includes the receipt UUID. ```python import asyncio from datetime import datetime, timezone from decimal import Decimal from nalogo import Client from nalogo.exceptions import ValidationException async def create_simple_receipt(client: Client): income_api = client.income() try: # Create receipt with automatic Decimal conversion result = await income_api.create( name="Consulting services", amount=5000.00, # Accepts float, int, str, or Decimal quantity=1, # Default is 1 operation_time=datetime.now(timezone.utc) # Optional, defaults to now ) receipt_uuid = result["approvedReceiptUuid"] print(f"Receipt created: {receipt_uuid}") # Expected response structure: # { # "approvedReceiptUuid": "abc123-...", # "processedAt": "2024-01-15T10:30:00Z" # } return receipt_uuid except ValidationException as e: print(f"Validation error: {e}") except ValueError as e: print(f"Invalid input: {e}") # Usage after authentication # receipt_uuid = asyncio.run(create_simple_receipt(authenticated_client)) ``` -------------------------------- ### Handle API Exceptions with Python Source: https://context7.com/rusik636/nalogo/llms.txt Demonstrates how to catch and handle specific exception types raised by the nalogo API for different error scenarios. It imports necessary modules, initializes a client, and uses a try-except block to manage potential `DomainException` subclasses. ```python import asyncio from nalogo import Client from nalogo.exceptions import ( DomainException, ValidationException, UnauthorizedException, ForbiddenException, NotFoundException, ClientException, PhoneException, ServerException, UnknownErrorException ) async def handle_api_errors(): client = Client() try: # Attempt authentication token = await client.create_new_access_token("invalid_inn", "wrong_password") await client.authenticate(token) # Attempt API operation income_api = client.income() await income_api.create("Service", 100.00, 1) except ValidationException as e: # HTTP 400 - Invalid input data print(f"Validation error: {e}") except UnauthorizedException as e: # HTTP 401 - Invalid credentials or expired token print(f"Authentication failed: {e}") except ForbiddenException as e: # HTTP 403 - Access denied print(f"Access forbidden: {e}") except NotFoundException as e: # HTTP 404 - Resource not found print(f"Not found: {e}") except ClientException as e: # HTTP 406 - Client error (wrong headers) print(f"Client error: {e}") except PhoneException as e: # HTTP 422 - SMS/phone verification error print(f"Phone verification error: {e}") except ServerException as e: # HTTP 500 - Server error print(f"Server error: {e}") except UnknownErrorException as e: # Other HTTP errors print(f"Unknown error: {e}") except DomainException as e: # Base exception - catches all API errors print(f"API error: {e}") if e.response: print(f"HTTP status: {e.response.status_code}") print(f"Response body: {e.response.text[:500]}") asyncio.run(handle_api_errors()) ``` -------------------------------- ### Create Simple Income Receipt Source: https://context7.com/rusik636/nalogo/llms.txt Creates a receipt for a single service item. The `create()` method automatically handles the conversion of amounts to `Decimal`. ```APIDOC ## POST /income/receipt ### Description Creates a receipt for a single service item. ### Method POST ### Endpoint /income/receipt ### Parameters #### Query Parameters - **operation_time** (datetime) - Optional - The time of the operation. Defaults to the current time in UTC. #### Request Body - **name** (string) - Required - The name of the service. - **amount** (number | string | Decimal) - Required - The amount of the service. Accepts float, int, str, or Decimal. - **quantity** (number | string | Decimal) - Optional - The quantity of the service. Defaults to 1. - **client** (object) - Optional - Client information. See `IncomeClient` DTO for details. ### Request Example ```json { "name": "Consulting services", "amount": 5000.00, "quantity": 1, "operation_time": "2024-01-15T10:30:00Z" } ``` ### Response #### Success Response (200) - **approvedReceiptUuid** (string) - The UUID of the approved receipt. - **processedAt** (string) - The timestamp when the receipt was processed. #### Response Example ```json { "approvedReceiptUuid": "abc123-...", "processedAt": "2024-01-15T10:30:00Z" } ``` #### Error Handling - **ValidationException**: Raised for validation errors. - **ValueError**: Raised for invalid input formats. ``` -------------------------------- ### Create Multi-Item Receipt Source: https://context7.com/rusik636/nalogo/llms.txt Creates a receipt with multiple service items using `IncomeServiceItem` objects for precise control over amounts and quantities. ```APIDOC ## POST /income/receipt/multiple ### Description Creates a receipt with multiple service items. ### Method POST ### Endpoint /income/receipt/multiple ### Parameters #### Request Body - **services** (array of objects) - Required - An array of `IncomeServiceItem` objects, each containing `name`, `amount`, and `quantity`. - **name** (string) - Required - The name of the service item. - **amount** (string | Decimal) - Required - The amount for the service item. - **quantity** (string | Decimal) - Required - The quantity for the service item. ### Request Example ```json { "services": [ { "name": "Website development", "amount": "50000.00", "quantity": "1" }, { "name": "Monthly maintenance", "amount": "5000.00", "quantity": "3" }, { "name": "SEO optimization", "amount": "15000.00", "quantity": "1" } ] } ``` ### Response #### Success Response (200) - **approvedReceiptUuid** (string) - The UUID of the approved receipt. - **processedAt** (string) - The timestamp when the receipt was processed. #### Response Example ```json { "approvedReceiptUuid": "def456-...", "processedAt": "2024-01-15T10:45:00Z" } ``` ``` -------------------------------- ### Create Receipt for Legal Entity Source: https://context7.com/rusik636/nalogo/llms.txt Creates a receipt for a corporate client (legal entity) with required INN and company name. ```APIDOC ## POST /income/receipt (with legal entity) ### Description Creates a receipt for a legal entity (corporate client). ### Method POST ### Endpoint /income/receipt ### Parameters #### Query Parameters - **operation_time** (datetime) - Optional - The time of the operation. Defaults to the current time in UTC. #### Request Body - **name** (string) - Required - The name of the service. - **amount** (number | string | Decimal) - Required - The amount of the service. - **quantity** (number | string | Decimal) - Optional - The quantity of the service. Defaults to 1. - **client** (object) - Required - Client information for a legal entity. - **contact_phone** (string) - Required - The client's contact phone number. - **display_name** (string) - Required - The legal entity's company name. - **income_type** (string) - Required - Must be `FROM_LEGAL_ENTITY`. - **inn** (string) - Required - The 10-digit INN for the legal entity. ### Request Example ```json { "name": "Software development contract", "amount": "250000.00", "quantity": 1, "client": { "contact_phone": "+79001234567", "display_name": "LLC 'Innovation Tech'", "income_type": "FROM_LEGAL_ENTITY", "inn": "1234567890" } } ``` ### Response #### Success Response (200) - **approvedReceiptUuid** (string) - The UUID of the approved receipt. - **processedAt** (string) - The timestamp when the receipt was processed. #### Response Example ```json { "approvedReceiptUuid": "ghi789-...", "processedAt": "2024-01-15T11:00:00Z" } ``` #### Error Handling - **ValidationException**: Raised for validation errors. - **ValueError**: Raised for invalid input formats. ``` -------------------------------- ### Retrieve Tax Information and History with Python Source: https://context7.com/rusik636/nalogo/llms.txt Fetches current tax summary data, historical tax information for a specified OKTMO region, and payment records (both all and only paid). Requires a `nalogo.Client` instance and an OKTMO code. ```python import asyncio from nalogo import Client async def get_tax_information(client: Client): tax_api = client.tax() # Get current tax summary tax_data = await tax_api.get() print(f"Current tax data: {tax_data}") # Get tax history for specific OKTMO region oktmo_code = "45000000" # Example OKTMO code (Moscow) history = await tax_api.history(oktmo=oktmo_code) print(f"Tax history: {history}") # Get payment records # only_paid=True returns only completed payments # only_paid=False returns all payment records all_payments = await tax_api.payments(oktmo=oktmo_code, only_paid=False) paid_only = await tax_api.payments(oktmo=oktmo_code, only_paid=True) print(f"All payments: {len(all_payments)} records") print(f"Paid payments: {len(paid_only)} records") return tax_data, history, paid_only # asyncio.run(get_tax_information(authenticated_client)) ``` -------------------------------- ### Retrieve Receipt Data and Generate Print URL with Python Source: https://context7.com/rusik636/nalogo/llms.txt Fetches complete receipt data in JSON format and generates a printable URL for a given receipt UUID. Handles 'not found' and 'invalid UUID' exceptions. Requires a `nalogo.Client` instance and a receipt UUID. ```python import asyncio from nalogo import Client from nalogo.exceptions import NotFoundException async def get_receipt_info(client: Client, receipt_uuid: str): receipt_api = client.receipt() try: # Get full receipt data as JSON receipt_data = await receipt_api.json(receipt_uuid) print(f"Total amount: {receipt_data.get('totalAmount')}") print(f"Operation time: {receipt_data.get('operationTime')}") print(f"Services: {receipt_data.get('services')}") # Generate print URL (synchronous, no API call) print_url = receipt_api.print_url(receipt_uuid) print(f"Print URL: {print_url}") # Example output: https://lknpd.nalog.ru/api/receipt/123456789012/abc-uuid-123/print return receipt_data, print_url except NotFoundException: print(f"Receipt not found: {receipt_uuid}") except ValueError as e: print(f"Invalid UUID: {e}") # asyncio.run(get_receipt_info(authenticated_client, "receipt-uuid")) ``` -------------------------------- ### Manage Payment Types and Find Favorite with Python Source: https://context7.com/rusik636/nalogo/llms.txt Lists all available payment methods associated with the user and identifies the default/favorite payment type. Returns a list of payment types and the favorite payment type if found. Requires a `nalogo.Client` instance. ```python import asyncio from nalogo import Client async def manage_payment_types(client: Client): payment_api = client.payment_type() # Get all payment types payment_types = await payment_api.table() print(f"Found {len(payment_types)} payment methods:") for pt in payment_types: print(f" - {pt.get('bankName')}: {pt.get('accountNumber')}") print(f" Favorite: {pt.get('favorite', False)}") # Get favorite payment type favorite = await payment_api.favorite() if favorite: print(f"\nDefault payment method: {favorite['bankName']}") else: print("\nNo favorite payment method configured") return payment_types, favorite # asyncio.run(manage_payment_types(authenticated_client)) ``` -------------------------------- ### Authenticate NaloGO Client via SMS in Python Source: https://context7.com/rusik636/nalogo/llms.txt Details the two-step SMS-based authentication process for the NaloGO client. It includes requesting an SMS challenge, obtaining the verification code from the user, and then verifying the code to activate the client. It handles `PhoneException` and `UnauthorizedException`. ```python import asyncio from nalogo import Client from nalogo.exceptions import PhoneException, UnauthorizedException async def authenticate_with_phone(): client = Client(storage_path="./tokens.json") try: phone = "79001234567" # Phone number without + prefix # Step 1: Request SMS challenge challenge = await client.create_phone_challenge(phone) print(f"SMS sent! Challenge token: {challenge['challengeToken']}") print(f"Code expires in: {challenge['expireIn']} seconds") # Step 2: Get SMS code from user sms_code = input("Enter the SMS code: ") # Step 3: Verify and get access token token_json = await client.create_new_access_token_by_phone( phone=phone, challenge_token=challenge['challengeToken'], verification_code=sms_code ) # Step 4: Activate the client await client.authenticate(token_json) print("Phone authentication successful!") return client except PhoneException as e: print(f"SMS verification error: {e}") except UnauthorizedException as e: print(f"Invalid verification code: {e}") asyncio.run(authenticate_with_phone()) ``` -------------------------------- ### Cancel Receipt Source: https://context7.com/rusik636/nalogo/llms.txt Cancels a previously created receipt with a valid cancellation reason. ```APIDOC ## POST /income/receipt/cancel ### Description Cancels a previously created receipt. ### Method POST ### Endpoint /income/receipt/cancel ### Parameters #### Request Body - **receipt_uuid** (string) - Required - The UUID of the receipt to cancel. - **comment** (string) - Required - The cancellation reason. Use one of the predefined `CancelCommentType` values (e.g., `CANCEL`, `REFUND`). - **operation_time** (datetime) - Required - The time of the cancellation operation. - **request_time** (datetime) - Required - The time the cancellation request was made. ### Request Example ```json { "receipt_uuid": "abc123-...", "comment": "CANCEL", "operation_time": "2024-01-15T11:15:00Z", "request_time": "2024-01-15T11:15:00Z" } ``` ### Response #### Success Response (200) - **status** (string) - The status of the cancellation (e.g., "cancelled"). - **message** (string) - A confirmation message. #### Response Example ```json { "status": "cancelled", "message": "Receipt abc123-... has been successfully cancelled." } ``` #### Error Handling - **ValidationException**: Raised if the receipt cannot be cancelled or if the UUID is invalid. - **ValueError**: Raised for invalid cancellation reasons. ``` -------------------------------- ### Cancel Receipt in Python Source: https://context7.com/rusik636/nalogo/llms.txt This code shows how to cancel a previously created receipt using the nalogo Python SDK. It takes the receipt UUID and a cancellation reason from `CancelCommentType` and includes error handling for validation and invalid input exceptions. ```python import asyncio from datetime import datetime, timezone from nalogo import Client from nalogo.dto.income import CancelCommentType from nalogo.exceptions import ValidationException async def cancel_receipt(client: Client, receipt_uuid: str): income_api = client.income() try: # Cancel with predefined reason result = await income_api.cancel( receipt_uuid=receipt_uuid, comment=CancelCommentType.CANCEL, # "Receipt created by mistake" operation_time=datetime.now(timezone.utc), request_time=datetime.now(timezone.utc) ) # Available cancellation reasons: # - CancelCommentType.CANCEL = "Чек сформирован ошибочно" (Receipt created by mistake) # - CancelCommentType.REFUND = "Возврат средств" (Refund) print(f"Receipt cancelled: {result}") return result except ValidationException as e: print(f"Cannot cancel receipt: {e}") except ValueError as e: print(f"Invalid cancellation reason: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.