Skip to main content

1C Interaction Library (oneCInteraction)

A modular Python library for interacting with «1C:Enterprise» databases via a COM connection (V83.COMConnector). It enables seamless integration of 1C with websites, Telegram bots, or other external services.

Features

  • Full COM Connection Support via win32com.
  • Nomenclature and Categories Management: retrieve group trees, batch load products, prices, and stock balances across warehouses.
  • Product Characteristics: read variant properties from information registers or parse text descriptions.
  • Product Properties (Metadata): read and write general metadata (properties) of Nomenclature items to/from information registers.
  • Images: download product images directly from the 1C database to the local disk.
  • Order Management: create customer orders, track statuses, and update document comments with customer contact details.
  • Smart Logging: automatically creates log files in the directory of the host project importing the library.

Installation

This library requires a Windows operating system with the 1C:Enterprise 8.3 platform installed and the pywin32 package.

Install the package:

pip install oneCInteraction.

Architecture Overview

The library is built on the principle of composition: the main Connection class initializes the COM connection and hosts specialized managers:

  • Connection.nomenclature (NomenclatureManager) — manages products and images.
  • Connection.groups (GroupsManager) — manages group hierarchy.
  • Connection.categories (CategoriesManager) — manages nomenclature categories.
  • Connection.characteristics (CharacteristicsManager) — reads properties of product variants.
  • Connection.orders (OrdersManager) — handles creation and updates of customer orders.
  • Connection.customers (CustomersManager) — manages customers/counterparties.
  • Connection.discounts (DiscountsManager) — manages discount groups and active nomenclature discounts.
  • Connection.properties (PropertiesManager) — manages reading and writing general product properties.

Detailed Class and Function Reference

1. Main Class Connection

The Connection class (located in connection.py) manages the COM connection to 1C and holds general settings.

Constructor:

def __init__(self, s_oneCDatabasePathIn: str, s_usernameIn: str, s_passwordIn: str)
  • s_oneCDatabasePathIn (str): Absolute path to the file-based 1C database on disk.
  • s_usernameIn (str): 1C username.
  • s_passwordIn (str): 1C password.

Key Attributes:

  • s_warehouse_code (str): 1C warehouse code for new orders.
  • s_organisation_code (str): 1C organization code for new orders.
  • sl_price_types (list): List of price type names to cache automatically (defaults to ["Розничная", "Оптовая", "Закупочная"]).
  • c_v8: The active 1C COM connection object (equals None if not connected).

Methods:

  • initiate_connection() -> None: Establishes the COM connection to 1C using V83.COMConnector and caches price type references.
  • close_connection() -> None: Closes the connection and releases COM resources.
  • get_price_type_ref(s_nameIn: str): Returns the 1C COM reference for a price type by its name.

2. Data Structures (structures.py)

All data models are defined in structures.py.

Nomenclature

Represents a product.

  • s_name (str): Product name.
  • s_article (str): Product article (SKU).
  • s_description (str): Product description.
  • l_variety (list of Variety): List of available variants/characteristics of the product.
  • s_unit (str): Unit of measurement (defaults to "шт.").
  • s_parent_uuid (str): UUID of the parent group/category.
  • s_uuid (str): Unique identifier (UUID) of the product in 1C.
  • s_code (str): 1C product code.
  • l_images (list): List of image UUIDs associated with the product in 1C.
  • dt_last_arrival (datetime): Date of the last physical arrival of the product to the warehouse from 1C.
  • l_properties (list of Property): List of general properties (metadata) of the product.

Price

Represents a price with its value, assignment date, and type.

  • n_value (float): Price value.
  • dt_assigned (datetime): Date and time when the price was set in 1C.
  • s_type (str): Price type name in Russian (e.g. "Розничная", "Оптовая", "Закупочная").

Variety

Represents a product variant with specific prices and stock levels.

  • c_priceRetail (Price): Retail price object for the variant.
  • c_priceOpt (Price): Wholesale price object for the variant.
  • c_pricePurchase (Price): Purchase price object for the variant.
  • d_count (dict): Stock balances by warehouse in the format {"Warehouse Name": quantity}.
  • l_characteristics (list of Characteristic): List of characteristics for the variant.

Characteristic

A key-value pair for a variant property.

  • s_name (str): Property name (e.g., "Color").
  • s_value (str): Property value (e.g., "Red").

Property

A key-value pair for a product property (metadata).

  • s_name (str): Property name (e.g., "Material").
  • s_value (str): Property value (e.g., "Cotton").

Group

A product group (category).

  • s_name (str): Group name.
  • l_subGroups (list of Group): List of subgroups.
  • l_nomenclatures (list of Nomenclature): List of products inside the group.
  • c_ref: COM reference to the group in 1C.
  • s_code (str): 1C group code.
  • s_uuid (str): UUID of the group in 1C.

Category

Represents a nomenclature category (e.g. ВидНоменклатуры / КатегорияНоменклатуры).

  • s_name (str): Category name.
  • l_nomenclatures (list of Nomenclature): List of products inside the category.
  • c_ref: COM reference to the category in 1C.
  • s_code (str): 1C category code.
  • s_uuid (str): UUID of the category in 1C.

Customer

Information about the buyer.

  • s_customerId (str): Unique customer identifier (e.g., Telegram ID).
  • s_customerName (str): First name.
  • s_customerSurname (str): Last name/surname.
  • s_customerPatronymic (str): Patronymic name.
  • s_customerPhone (str): Phone number.
  • s_customerAddress (str): Delivery address.
  • s_customerCode (str): Corresponding 1C counterparty code.

OrderItem

An item in the order.

  • s_productCode (str): Product 1C code.
  • c_variety (Variety): Selected variant/characteristic object (if any).
  • n_productCount (int): Quantity of items.

Order

A buyer's order.

  • c_orderCustomer (Customer): Customer details object.
  • l_orderItemsList (list of OrderItem): List of ordered items.
  • s_TTN (str): Waybill number (TTN).
  • s_status (str): Status of the order in 1C.
  • s_date (str): Order creation date (automatically generated).
  • n_orderCode (str / int): Order number in 1C.
  • s_price_type (str): Price type name used for the order (e.g. "Розничная", "Оптовая", "Закупочная").
  • s_comment (str): Additional comment/notes for the order (often parsed to extract Telegram ID).

Calling str(order_obj) returns a nicely formatted HTML string suitable for sending to a Telegram bot.

DiscountGroup

Represents a group of nomenclature discounts.

  • s_name (str): Discount group name or comment.
  • s_document_number (str): Number of the document that set the discount in 1C.
  • s_discount_type_code (str): Discount type code (e.g. "B2B").
  • n_discount_percent (float): Discount percentage.
  • l_nomenclatures (list of dict): List of products in the discount group (each product is a dict with keys "code", "name", "uuid", and "char_name").

3. Nomenclature Manager NomenclatureManager (Connection.nomenclature)

Defined in nomenclature.py.

  • get(s_articleIn: str = "", s_nameIn: str = "", s_codeIn: str = "") -> Nomenclature | None Searches for and returns a product by its article, name, or code. Fetches retail, wholesale, and purchase prices, stock balances by warehouses, characteristics, and the parent group's UUID (s_parent_uuid).
  • search(s_queryIn: str, s_searchByIn: str = "all") -> list Searches for nomenclature items by a query string matching the name, article, code, or all of them. Returns a list of Nomenclature objects (without full detailed price/stock breakdown, but containing basic fields).
  • get_images(c_productObjIn: Nomenclature, s_imageDirIn: str = None) -> list Downloads all attached images for a product from 1C. Saves them in the specified directory s_imageDirIn (defaults to data/images). Returns a list of the saved filenames (e.g., ["[uuid]_0.jpg"]).
  • get_by_group(c_groupRefIn) -> list Batch fetches all products within a specific 1C group. Using optimized COM queries, this method minimizes DB requests and operates significantly faster than calling get() sequentially in a loop.
  • get_by_category(c_categoryIn) -> list Batch fetches all products within a specific 1C category. c_categoryIn can be a COM reference object or a string representing the category name (searched within Справочник.КатегорииОбъектов).

4. Category Manager GroupsManager (Connection.groups)

Defined in groups.py.

  • get_tree(sl_ignoredCategoriesNamesIn: list) -> list Builds the hierarchical category tree from 1C. Branches whose names are listed in sl_ignoredCategoriesNamesIn are excluded along with all their subcategories.
  • get_by_name(s_nameIn: str) -> Group | None Finds a reference to a group by its exact name in 1C.
  • get_full_path(c_groupRefIn) -> str Builds the full text hierarchy path to a category, traversing up to the root parent (e.g., "Clothing > Men's > Shoes").

5. Categories Manager CategoriesManager (Connection.categories)

Defined in categories.py.

  • get(s_codeIn: str = "", s_nameIn: str = "") -> Category | None Finds a single Category by its code or name in the КатегорииОбъектов (Object Categories) catalog.
  • create(s_nameIn: str) -> Category | None Creates a new Category with the specified name in Справочник.КатегорииОбъектов and returns it.

6. Characteristics Manager CharacteristicsManager (Connection.characteristics)

Defined in characteristics.py.

  • parse_name(s_charNameIn: str) -> list (static method) Parses a characteristic name string (e.g., "Size: L" or "Color - Red") and returns a list of Characteristic objects.
  • get(c_charRefIn, s_charNameIn: str = "") -> list Queries characteristic properties from the ЗначенияСвойствОбъектов register. If no properties are found, falls back to parsing the name string via parse_name().
  • fetch_batch(l_charRefsIn: list) -> dict Batch fetches property values for a list of characteristic references.

7. Orders Manager OrdersManager (Connection.orders)

Defined in orders.py.

  • push(c_orderObjIn: Order) -> str Creates a new "Заказ покупателя" (Buyer's Order) document in 1C.
    • Automatically queries the warehouse, counteragent, and organization based on codes specified in the Connection object.
    • Sets the price type (defaulting to "Розничная" or using s_price_type from the order), document currency (Hryvnia, code "980"), and organization's primary bank account.
    • Adds products from the order, queries/compares the exact price for the specific characteristic selected (using s_price_type to determine retail, wholesale, or purchase price), and computes totals.
    • Attempts to post the document (Posting). If posting fails, it writes the document in draft/save mode (Write).
    • Returns the number of the created document in 1C (or an empty string on error).
  • get(s_codeIn: str) -> Order | None Retrieves a buyer's order by its 1C document number and parses it into an Order object. The comment field is parsed to retrieve the Telegram ID, and the price type is retrieved.
  • get_by_date(target_date: date | datetime, s_counteragent_code: str = "") -> list Returns a list of all posted orders (Проведен = TRUE) for a specific date (accepting datetime.date or datetime.datetime), optionally filtered by counteragent or counteragent group code.
  • update_info(c_orderObjIn: Order) -> bool Updates the comment field of the order in 1C. Writes a formatted string to the comment field: "[Full Name] [Phone] [Telegram ID] [Waybill/TTN] [Status]"


8. Customers Manager CustomersManager (Connection.customers)

Defined in customers.py.

  • create(c_customerIn: Customer) -> str Creates a new counterparty (Контрагент) record in 1C using details from the Customer structure, generates a default contract, and sets it as the main contract (ОсновнойДоговорКонтрагента). Returns the generated 1C counterparty code.
  • get(s_codeIn: str) -> Customer | None Retrieves a counterparty by its 1C code and parses it back into a Customer structure.
  • ensure_default_contract(c_clientRef) Verifies if the counterparty COM reference has a default contract. If not, automatically creates one and assigns it.

9. Discounts Manager DiscountsManager (Connection.discounts)

Defined in discounts.py.

  • get_active_groups(s_discount_type_codeIn: str = None) -> list Retrieves active discount groups and returns them as a list of DiscountGroup objects.
    • If s_discount_type_codeIn is specified, only returns groups matching that discount type code.
    • Queries active discounts from the СкидкиНаценкиНоменклатуры information register.
    • Only retrieves discounts where the percentage is greater than zero and the registrar document's end date (ДатаОкончания) is either not set or is greater than or equal to the current date.

10. Properties Manager PropertiesManager (Connection.properties)

Defined in properties.py.

  • write(self, c_productIn, s_propertyNameOrCodeIn: str, s_propertyValueIn: str) -> bool Writes or updates a single property value for a product (Nomenclature item).
  • write_batch(self, c_productIn, l_propertiesIn: list, b_forceIn: bool = False) -> list Writes/updates multiple properties for a product using a single 1C RecordSet. l_propertiesIn can be a list of Property objects or dicts {"name": "...", "value": "..."}.
  • get_assigned_properties(self, c_productIn) -> list Returns a list of Property objects assigned to the specified product.
  • delete(self, c_productIn, s_propertyNameOrCodeIn: str) -> bool Removes a specific property from a product in 1C register.
  • get_all_definitions(self) -> list Retrieves definitions of all active properties in 1C.

11. Logging (log.py)

Defined in log.py.

All actions are logged automatically. The library resolves the root directory of the project that imported it and stores log files in the relative path log/system/[calling_module_name].log.

  • log_sys(message, errorFlag = 0) — The main logging utility. If errorFlag=1, prepends an [ERROR] tag.

Usage Example

Complete Workflow (Fetching Products and Creating an Order)

from oneCInteraction import Connection, Customer, Order, OrderItem

# 1. Initialize Connection
c_conn = Connection(
    s_oneCDatabasePathIn="C:\\1C_Bases\\ShopDB",
    s_usernameIn="AdminBot",
    s_passwordIn="secure_password"
)

# 2. Configure 1C Default Codes
c_conn.s_warehouse_code = "000000001"  # Warehouse code
c_conn.s_organisation_code = "000000001"  # Organization code

# 3. Establish connection to 1C
c_conn.initiate_connection()

if c_conn.c_v8:
    try:
        # 4. Fetch Category Tree
        ignored_cats = ["Archive", "System"]
        categories = c_conn.groups.get_tree(ignored_cats)
        print(f"Loaded {len(categories)} root categories.")

        # 5. Get products from the first category
        first_group = categories[0]
        products = c_conn.nomenclature.get_by_group(first_group.c_ref)
        print(f"Found products in group {first_group.s_name}: {len(products)}")

        for p in products[:3]:
            print(f"Product: {p.s_name} | SKU: {p.s_article}")
            if p.l_variety:
                v = p.l_variety[0]
                s_date = v.c_priceRetail.dt_assigned.strftime("%d.%m.%Y") if v.c_priceRetail.dt_assigned else "N/A"
                print(f"  Price: {v.c_priceRetail.n_value} UAH (set on {s_date}) | Stocks: {v.d_count}")

            # Download product images
            images = c_conn.nomenclature.get_images(p, s_imageDirIn="static/images")
            print(f"  Downloaded images: {images}")

        # 6. Create a New Order
        customer = Customer(
            s_customerIdIn="123456789",
            s_customerNameIn="John",
            s_customerSurnameIn="Doe",
            s_customerPhoneIn="+380991112233",
            s_customerAddressIn="Kyiv, Nova Poshta Warehouse #1"
        )

        items = [
            OrderItem(
                s_productCodeIn="000000104",
                c_varietyIn=products[0].l_variety[0] if products and products[0].l_variety else None,
                n_productCountIn=2
            )
        ]

        new_order = Order(
            c_orderCustomerIn=customer,
            l_orderItemsListIn=items
        )

        # Submit the order to 1C
        order_number = c_conn.orders.push(new_order)
        if order_number:
            print(f"Order created successfully in 1C! Order Number: {order_number}")

            # Update TTN and status details
            new_order.n_orderCode = order_number
            new_order.s_TTN = "20450011223344"
            new_order.s_status = "Shipped"
            c_conn.orders.update_info(new_order)

            # Output order details formatted as HTML string
            print(str(new_order))

    finally:
        # Always clean up and close the connection
        c_conn.close_connection()
else:
    print("Failed to connect to 1C database.")

Release files for oneCInteraction 1.4.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for oneCInteraction 1.4.8
File Size Uploaded
onecinteraction-1.4.8.tar.gz 47.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for oneCInteraction 1.4.8
File Interpreter ABI Platform
onecinteraction-1.4.8-py3-none-any.whl Python 3 none any Details

Total release size: 91.2 kB

Release files / onecinteraction-1.4.8.tar.gz

Download URL onecinteraction-1.4.8.tar.gz
Size 47.2 kB
Tags Source
SHA-256 checksum
How to use checksums
59ead012262f4d91eacb0e11ae5b41cebab33c7ac5fe0d9d93e22f53744481e8
BLAKE2b-256 checksum
How to use checksums
fe0b8df3ef8d159b16e8598be1147fb6d2685ff7853ef32f2200c3adf9e6534e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release files / onecinteraction-1.4.8-py3-none-any.whl

Download URL onecinteraction-1.4.8-py3-none-any.whl
Size 44.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ced95d2a105548617da8252b70542cb3a511d6ca150103af3fe0cc088c2d6183
BLAKE2b-256 checksum
How to use checksums
e217dd10e785ec5af0b6db00061ee76a746f3403d7b2a9824261e9df1185f0a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.4.8 This release

2 release files

1.4.7

2 release files

1.4.6

2 release files

1.4.5

2 release files

1.4.4

2 release files

1.4.3

2 release files

1.4.2

2 release files

1.4.1

2 release files

1.4.0

2 release files

1.3.9

2 release files

1.3.8

2 release files

1.3.7

2 release files

1.3.6

2 release files

1.3.5

2 release files

1.3.4

2 release files

1.3.3

2 release files

1.3.2

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.9

2 release files

1.2.8

2 release files

1.2.7

2 release files

1.2.6

2 release files

1.2.5

2 release files

1.2.4

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.9

2 release files

1.1.8

2 release files

1.1.7

2 release files

1.1.6

2 release files

1.1.5

2 release files

1.1.4

2 release files

1.1.3

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page