domain Package

domain Package

Stoq domain classes, the business logic of Stoq.

This package contain a set of domain classes that abstracts the database business logic into a high-level python syntax that can be used by the rest of the application.

An Object Relational Mapper (ORM) is used to translate the PostgreSQL query statements to and from Python syntax. We are currently using the Storm ORM.

Starting point for the domain classes:

account

This module contains classes centered around account, banks and transactions between accounts.

The main class is an Account holds a set of AccountTransaction.

For accounts that are banks there’s a BankAccount class for the bank specific state and for bill generation there’s also BillOption.

Finally there’s a AccountTransactionView that is used by the financial application to efficiently display a ledger.

class stoqlib.domain.account.BillOption(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

List of values for bill (boleto) generation

See also: schema

option

column: Unicode

option name, such as nosso_numero

value

column: Unicode

value of the option

bank_account

reference to: BankAccount

the bank account this option belongs to

class stoqlib.domain.account.BankAccount(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Information specific to a bank

See also: schema

account

reference to: Account

the account for this bank account

bank_number

column: Int

an identify for the bank type of this account,

bank_branch

column: Unicode

an identifier for the bank branch/agency which is responsible for this

bank_account

column: Unicode

an identifier for this bank account

options

Get the bill options for this bank account :returns: a list of BillOption

class stoqlib.domain.account.Account(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An account, a collection of account transactions that may be controlled by a bank.

See also: schema, manual

TYPE_BANK = u'bank'

Bank

TYPE_CASH = u'cash'

Cash/Till

TYPE_ASSET = u'asset'

Assets, like investement account

TYPE_CREDIT = u'credit'

Credit

TYPE_INCOME = u'income'

Income/Salary

TYPE_EXPENSE = u'expense'

Expenses

TYPE_EQUITY = u'equity'

Equity, like unbalanced

description

column: Unicode

name of the account

code

column: Unicode

code which identifies the account

parent_id

column: UUIDCol

parent account id, can be None

parent

reference to: Account

parent account

station

reference to: BranchStation

the branch station tied to this account, mainly for TYPE_CASH accounts

account_type

column: EnumCol

kind of account, one of the TYPE_* defines in this class

bank

reference to: BankAccount

bank account for this account, used by TYPE_BANK accounts

classmethod get_by_station(store, station)[source]

Fetch the account assoicated with a station

Parameters:
Returns:

the account

classmethod get_children_for(store, parent)[source]

Get a list of child accounts for

Parameters:
  • store
  • parent (account) – parent account
Returns:

the child accounts

Return type:

resultset

classmethod get_accounts(store)[source]

Get a list of all accounts

Parameters:store – a store

:returns all accounts :rtype: resultset

long_description

Get a long description, including all the parent accounts, such as Tills:cotovia

transactions

Returns a list of transactions to this account.

Returns:list of account transaction
get_total_for_interval(start, end)[source]

Fetch total value for a given interval

Parameters:
  • start (datetime) – beginning of interval
  • end (datetime) – of interval
Returns:

total value or one

can_remove()[source]

If the account can be removed. Not all accounts can be removed, some are internal to Stoq and cannot be removed

remove(store)[source]

Remove the current account. This updates all transactions which refers to this account and removes them.

Parameters:store – a store
has_child_accounts()[source]

If this account has child accounts

Returns:True if any other accounts has this account as a parent
get_type_label(out)[source]

Returns the label to show for the increases/decreases for transactions of this account. See account_labels

Parameters:out – if the transaction is going out
matches(account_id)[source]

Check if this account or it’s parent account is the same as another account id.

Parameters:account_id – the account id to compare with
Returns:if the accounts matches.
class stoqlib.domain.account.AccountTransaction(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Transaction between two accounts.

A transaction is a transfer of money from the source_account to the account.

It removes a negative amount of money from the source and increases the account by the same amount. There’s only one value, but depending on the view it’s either negative or positive, it can never be zero though. A transaction can optionally be tied to a payment

See also: schema manual

account

reference to: Account

destination account

source_account

reference to: Account

source account

description

column: Unicode

short human readable summary of the transaction

code

column: Unicode

identifier of this transaction within a account

value

column: PriceCol

value transfered

date

column: DateTimeCol

date the transaction was done

payment

reference to: Payment

payment this transaction relates to, can also be None

operation_type

column: EnumCol

operation_type represents the type of transaction (debit/credit)

classmethod get_inverted_operation_type(operation_type)[source]

Get the inverted operation_type (IN->OUT / OUT->IN)

Parameters:operation_type – the type of transaction
Returns:the inverted transaction type
classmethod create_from_payment(payment, code=None, source_account=None, destination_account=None)[source]

Create a new transaction based on a payment. It’s normally used when creating a transaction which represents a payment, for instance when you receive a bill or a check from a client which will enter a bank account.

Parameters:
  • payment – the payment to create the transaction for.
  • code – the code for the transaction. If not provided, the payment identifier will be used by default
  • source_account – the source account for the transaction.
  • destination_account – the destination account for the transaction.
Returns:

the transaction

create_reverse()[source]

Reverse this transaction, this happens when a payment is set as not paid.

Returns:the newly created account transaction representing the reversal
invert_transaction_type()[source]

Invert source/destination accounts and operation_type

When change a incoming transaction to outgoing or vice-versa. The source and destination accounts must be inverted. Thus, the outgoing value always will belong to the source account.

get_other_account(account)[source]

Get the other end of a transaction

Parameters:account – an account
Returns:the other end
set_other_account(other, account)[source]

Set the other end of a transaction

Parameters:
  • other – an account which we do not want to set
  • account – the account to set
class stoqlib.domain.account.AccountTransactionView[source]

Bases: stoqlib.database.viewable.Viewable

AccountTransactionView provides a fast view of the transactions tied to a specific account.

It’s mainly used to show a ledger.

transaction

alias of AccountTransaction

classmethod get_for_account(account, store)[source]

Get all transactions for this account, see Account.transaction

get_account_description(account)[source]

Get description of the other account, eg. the one which is transfered to/from.

get_value(account)[source]

Gets the transaction value according to an account.

If this account is the source, the value returned will be negative. Representing a outgoing transaction.

get_value_by_type()[source]

Returns the transaction value, based on operation type.

address

This module contains classes centered around physical addresses.

There are two classes, Address and CityLocation.

CityLocation contains the city, state and country, Address contains street, district, postal code and a reference to a person.

class stoqlib.domain.address.CityLocation(store=None, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

CityLocation is a class that contains the location of a city and it’s state/country. There are also codes for the city and states.

The country is expected to be one of the countries returned from stoqlib.lib.countries.get_countries().

See also: schema

Note

the city and state codes are currently Brazil specific and refers to a unique identifier which is the same as NFe (Nota Fiscal Eletronico) requires.

city

column: Unicode

the city

state

column: Unicode

the state

country

column: Unicode

the country, iso-3166 localized using iso-codes

city_code

column: Int

code of the city

state_code

column: Int

code of the state

classmethod get_default(store)[source]

Get the default city location according to the database parameters. The is usually the same city as main branch.

Returns:the default city location
classmethod get_or_create(store, city, state, country)[source]

Get or create a city location. City locations are created lazily, so this is used when registering new addresses.

Parameters:
  • store – a store
  • city (unicode) – a city
  • state (unicode) – a state
  • country (unicode) – a country
Returns:

the city location or None

classmethod get_cities_by(store, state=None, country=None)[source]

Fetch a list of cities given a state and a country.

Parameters:
  • store – a store
  • state – state or None
  • country – country or None
Returns:

a list of cities

Return type:

string

class stoqlib.domain.address.Address(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An Address is a class that stores a physical street location for a person.

A Person can have many addresses. The city, state and country is found in city location.

See also: schema

street

column: Unicode

street of the address, something like "Wall street"

streetnumber

column: Int

streetnumber, eg 100

district

column: Unicode

district, eg "Manhattan"

postal_code

column: Unicode

postal code, eg "12345-678"

complement

column: Unicode

complement, eg "apartment 35"

is_main_address

column: Bool

If this is the primary address for the person, this is set when you register a person for the first time.

person

reference to: Person

the person who resides at this address

city_location

reference to: CityLocation

the city location this address is in

get_description()[source]

See IDescribable.get_description()

is_valid_model()[source]

Verifies if this model is properly filled in, that there’s a street, district and valid city location set.

Returns:True if this address is filled in.
get_city()[source]

Get the city for this address. It’s fetched from the city location.

Returns:the city
get_country()[source]

Get the country for this address. It’s fetched from the city location.

Returns:the country
get_state()[source]

Get the state for this address. It’s fetched from the city location.

Returns:the state
get_postal_code_number()[source]

Get the postal code without any non-numeric characters.

Returns:the postal code as a number
get_address_string()[source]

Formats the address as a string

Returns:the formatted address
get_details_string()[source]

Returns a string like postal_code - city - state. If city or state are missing, return only postal_code; and if postal_code is missing, return city - state, otherwise, return an empty string

Returns:the detailed string

attachment

Attachment domain class

Allows other tables to have any kinds of attachments.

base

The base Domain class for Stoq.

class stoqlib.domain.base.Domain(*args, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

The base domain for Stoq.

This builds on top of stoqlib.database.properties.ORMObject and adds:

  • created and modified transaction entry, a log which is mainly used by database synchonization, it allows us to find out what has been modified and created within a specific time frame.
  • create/update/modify hooks, which some domain objects implement to fire of events that can be used to find out when a specific domain event is triggered, eg a sale is created, a product is modified. etc.
  • cloning of domains, when you want to create a new similar domain
  • function to check if an value of a column is unique within a domain.

Not all domain objects need to subclass Domain, some, such as stoqlib.domain.system.SystemTable inherit from ORMObject.

repr_fields = []

A list of fields from this object that should de added on the representation of this object (when calling repr())

id

column: UUIDCol

id of this domain class, it’s usually the primary key. it will automatically update when a new insert is created. Note that there might be holes in the sequence numbers, which happens due to aborted transactions

te

reference to: TransactionEntry

a transaction entry for when the domain object was created and last modified

serialize()[source]

Returns the object as a dictionary

on_create()[source]

Called when self is about to be created on the database

This hook can be overridden on child classes for improved functionality.

A trick you may want to use: Use ORMObject.get_store() to get the store in which self lives and do your modifications in it.

on_update()[source]

Called when self is about to be updated on the database

This hook can be overridden on child classes for improved functionality.

A trick you may want to use: Use ORMObject.get_store() to get the store in which self lives and do your modifications in it.

on_delete()[source]

Called when self is about to be removed from the database

This hook can be overridden on child classes for improved functionality.

A trick you may want to use: Use ORMObject.get_store() to get the store in which self lives and use it to do a cleanup in other objects for instance, so if the store is rolled back, your cleanup will be rolled back too.

Note that modifying self doesn’t make sense since it will soon be removed from the database.

on_object_changed(attr, old_value, value)[source]

Hook for when an attribute of this object changes.

This is called when any property of the object has the value changed. This will only be called when the value is known (ie, not AutoReload) and the value comes from python, not from the database, and the value has actually changed from the previous value.

clone()[source]

Get a persistent copy of an existent object. Remember that we can not use copy because this approach will not activate ORMObject methods which allow creating persitent objects. We also always need a new id for each copied object.

Returns:the copy of ourselves
check_unique_value_exists(attribute, value, case_sensitive=True)[source]

Check database for attribute/value precense

Check if we already the given attribute/value pair in the database, but ignoring this object’s ones.

Parameters:
  • attribute – the attribute that should be unique
  • value – value that we will check if exists in the database
  • case_sensitive – If the checking should be case sensitive or not.
Returns:

the existing object or None

check_unique_tuple_exists(values, case_sensitive=True)[source]

Check database for values presence

Check if we already the given attributes and values in the database, but ignoring this object’s ones.

Parameters:
  • values – dictionary of attributes:values that we will check if exists in the database.
  • case_sensitive – If the checking should be case sensitive or not.
Returns:

the existing object or None

merge_with(other, skip=None, copy_empty_values=True)[source]

Does automatic references updating when merging two objects.

This will update all tables that reference the other object and make them reference self instead.

After this it should be safe to remove the other object. Since there is no one referencing it anymore.

Parameters:
  • skip – A set of (table, column) that should be skiped by the automatic update. This are normally tables that require a special treatment, like when there are constraints.
  • copy_empty_values – If True, attributes that are either null or an empty string in self will be updated with the value from the other object (given that the other attribute is not empty as well)
copy_empty_values(other)[source]

Copies the values from other object if missing in self

This will copy all values from the other object that are missing from this one.

can_remove(skip=None)[source]

Check if this object can be removed from the database

This will check if there’s any object referencing self

Parameters:skip – an itarable containing the (table, column) to skip the check. Use this to avoid false positives when you will delete those skipped by hand before self.
classmethod get_temporary_identifier(store)[source]

Returns a temporary negative identifier

This should be used when working with syncronized databases and a purchase order is being created in a branch different than the destination branch.

The sincronizer will be responsible for setting the definitive identifier once the order arives at the destination

classmethod find_distinct_values(store, attr, exclude_empty=True)[source]

Find distinct values for a given attr

Parameters:
  • store – a store
  • attr – the attr we are going to get distinct values for
  • exclude_empty – if True, empty results (None or empty strings) will be removed from the results
Returns:

an iterator of the results

classmethod get_max_value(store, attr, validate_attr=True, query=Undef)[source]

Get the maximum value for a given attr

On text columns, trying to find the max value for them using MAX() on postgres would result in some problems, like ‘9’ being considered greater than ‘10’ (because the comparison is done from left to right).

This will 0-“pad” the values for the comparison, making it compare the way we want. Note that because of that, in the example above, it would return ‘09’ instead of ‘9’

Para store:a store
Parameters:attr – the attribute to find the max value for
Returns:the maximum value for the attr
classmethod get_or_create(store, **kwargs)[source]

Get the object from the database that matches the given criteria, and if it doesn’t exist, create a new object, with the properties given already set.

The properties given ideally should be the primary key, or a candidate key (unique values).

Returns:an object matching the query or a newly created one if a matching one couldn’t be found.
classmethod validate_attr(attr, expected_type=None)[source]

Make sure attr belongs to cls and has the expected type

Parameters:
  • attr – the attr we will check if it is on cls
  • expected_type – the expected type for the attr to be an instance of. If None will default to Property
Raises:

TypeError if the attr is not an instance of expected_type

Raises:

ValueError if the attr does not belong to this class

classmethod validate_batch(batch, sellable, storable=None)[source]

Verifies if the given batch is valid for the given sellable.

Parameters:
  • batch – A |storablebatch| that is being validated
  • sellable – A sellable that we should use to validate against the batch
  • storable – If provided, the corresponding storable for the given batch, to avoid unecessary queries.

certificate

commission

Commission management

class stoqlib.domain.commission.CommissionSource(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Commission Source object implementation

A CommissionSource is tied to a sellable category or sellable, it’s used to determine the value of a commission for a certain item which is sold. There are two different commission values defined here, one which is used when the item is sold directly, eg one installment and another one which is used when the item is sold in installments.

The category and the sellable should not exist when sellable exists and the opposite is true.

See also: schema,

direct_value

column: PercentCol

the commission value to be used in a sale with one installment

installments_value

column: PercentCol

the commission value to be used in a sale with multiple installments

category

reference to: SellableCategory

the sellable category

sellable

reference to: Sellable

the sellable

class stoqlib.domain.commission.Commission(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Commission object implementation

A Commission is the commission received by a salesperson for a specific payment made by a sale.

There is one Commission for each payment of a sale.

See also: schema,

DIRECT = 0

use direct commission to calculate the commission amount

INSTALLMENTS = 1

use installments commission to calculate the commission amount

value

column: PriceCol

The commission amount

sale

reference to: Sale

the sale this commission applies to

payment

reference to: Payment

the payment this commission applies to

class stoqlib.domain.commission.CommissionView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about commissions and it’s related sale and payment.

branch

the branch this commission was generated

alias of Branch

payment

alias of Payment

sale

alias of Sale

costcenter

Domain implementation for Cost Centers

class stoqlib.domain.costcenter.CostCenter(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A cost center holds a set of cost center entry objects.

cost center entry are created when a resource from the company is spent. Right now, these resources are:

  • Money used to pay an lonely out payment
  • Products removed from the stock (not all situations).

Entries are not created for out payment related to a purchase, stock decrease or any other operation that changes the stock, since those costs will be accounted when the stock is actually decreased.

Also, entries are only created for stock removal when the products are actually destined for a final usage. For instance, transfer and loan should not generate cost entries.

As of this writing, the only stock operations that should trigger a cost entry creation are:

name

column: Unicode

the name of the cost center

description

column: Unicode

a description for the cost center

budget

column: PriceCol

The budget available for this cost center

is_active

column: Bool

indicates whether it’s still possible to add entries to this cost center.

get_stock_decreases()[source]

This method fetches all the stock decreases related to this cost center.

get_sales()[source]

This method fetches all the sales related to this cost center

get_payments()[source]

Returns all payments registred in this cost center

get_entries()[source]

This method gets all the cost center entry related to this cost center.

add_stock_transaction(stock_transaction)[source]

This method is called to create a cost center entry when a product is removed from stock and this is being related to this cost center.

add_lonely_payment(lonely_payment)[source]

This method is called to create a cost center entry when a lonely payment is confirmed and being related to this cost center.

class stoqlib.domain.costcenter.CostCenterEntry(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A operation that generated some cost in a cost center.

A cost can be generated when a lonely out payment is paid or when some operations on the stock are performed.

cost_center

reference to: CostCenter

The cost center this entry belongs to

payment

reference to: Payment

The payment that generated this cost.

stock_transaction

reference to: StockTransactionHistory

The stock movement transaction that generated this cost.

devices

Domain classes related to stoqdrivers package.

class stoqlib.domain.devices.FiscalDayTax(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This represents the information that needs to be used to generate a Sintegra file of type 60M.

code

column: Unicode

four bytes, either the percental of the tax, 1800 for 18% or one of:

  • I: Isento
  • F: Substitucao
  • N: Nao tributado
  • ISS: ISS
  • CANC: Cancelled
  • DESC: Discount
class stoqlib.domain.devices.FiscalDayHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This represents the information that needs to be used to generate a Sintegra file of type 60A.

event

Logging of events.

class stoqlib.domain.event.Event(store=None, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

An event represent something that happened in Stoq that should be logged and access at a later point.

See also: schema

TYPE_SYSTEM = u'system'

System related messages

TYPE_USER = u'user'

login user events, logging in and logging out

TYPE_ORDER = u'order'

purchase events

TYPE_SALE = u'sale'

sale events

TYPE_PAYMENT = u'payment'

payment events

date

column: DateTimeCol

the date the event was created

event_type

column: EnumCol

type of this event, one of TYPE_* variables of this class

description

column: Unicode

description of the event

classmethod log(store, event_type, description)[source]

Create a new event message.

Parameters:
  • store – a store
  • event_type – the event type of this message
  • description – the message description
classmethod log_sale_item_discount(store, sale_number, user_name, discount_value, product, original_price, new_price)[source]

Log the discount authorized by an user

This will log on the event system when a user authorizes a discount greater than what is allowed on a sale item

Parameters:
  • store – a store
  • sale_number – the sale’s id that the discount was applied
  • user_name – the user that authorized the discount
  • discount_value – the percentage of discount applied
  • product – the name of product that received the discount
  • original_price – the original price of product
  • new_price – the price of product after discount
classmethod log_sale_discount(store, sale_number, user_name, discount_value, original_price, new_price)[source]

Log the discount authorized by an user

This will log on the event system when a user authorizes a discount greater than what is allowed on a sale

Parameters:
  • store – a store
  • sale_number – the sale’s id that the discount was applied
  • user_name – the user that authorized the discount
  • discount_value – the percentage of discount applied
  • original_price – the original price of product
  • new_price – the price of product after discount

events

Events used in the domain code

class stoqlib.domain.events.DomainMergeEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted two domain objects are being merged

Parameters:
  • obj – the main object that is being merged with (the one that will be kept)
  • other – the object that is being merged. This is the one that will have the references fixed
class stoqlib.domain.events.ProductCreateEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a product is created.

Parameters:product – the created product
class stoqlib.domain.events.ProductEditEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a product is edited.

Parameters:product – the edited product
class stoqlib.domain.events.ProductRemoveEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a product is about to be removed.

Parameters:product – the removed product
class stoqlib.domain.events.ProductStockUpdateEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a product stock is in/decreased.

Parameters:
  • product – the product that had it’s stock modified
  • branch – the branch on which the stock was modified
  • old_quantity – the old product stock quantity
  • new_quantity – the new product stock quantity
class stoqlib.domain.events.SellableCheckTaxesEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to check the sellable fiscal data.

If the tax is not valid, one should raise TaxError just like sellable.check_tax_validity does.

Parameters:sellable – the sellable that will be checked
class stoqlib.domain.events.ServiceCreateEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a service is created.

Parameters:service – the created service
class stoqlib.domain.events.ServiceEditEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a service is edited.

Parameters:service – the edited service
class stoqlib.domain.events.ServiceRemoveEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a service is about to be removed.

Parameters:product – the removed service
class stoqlib.domain.events.CategoryCreateEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a category is created.

Parameters:category – the created category
class stoqlib.domain.events.CategoryEditEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a category is edited.

Parameters:category – the edited category
class stoqlib.domain.events.ImageCreateEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when an image is created.

Parameters:image – the created image
class stoqlib.domain.events.ImageEditEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when an image is edited.

Parameters:image – the edited image
class stoqlib.domain.events.ImageRemoveEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when an image is removed.

Parameters:image – the removed image
class stoqlib.domain.events.SaleStatusChangedEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a sale is has it’s status changed

Parameters:
  • sale – the sale which had it’s status changed
  • old_status – the old sale status
class stoqlib.domain.events.SaleCanCancelEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to check if a sale can be cancelled

The expected return should be True if the sale can be canceled, or False if it can’t.

Parameters:sale – the sale that is going to be cancelled
class stoqlib.domain.events.SaleIsExternalEvent[source]

Bases: stoqlib.lib.event.Event

Emitted to check if a sale is external.

External sales are the ones done outside of the commercial establishment.

The expected return value should be True if the sale is to be considered as external or False otherwise.

Parameters:sale – The sale that we want to check
class stoqlib.domain.events.SaleItemBeforeDecreaseStockEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a sale item is about to decrease the stock

This is usually called at the beginning of stoqlib.domain.sale.SaleItem.sell()

Parameters:sale_item – the sale item object
class stoqlib.domain.events.SaleItemBeforeIncreaseStockEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a sale item is about to increase the stock

This is usually called at the beginning of stoqlib.domain.sale.SaleItem.cancel()

Parameters:sale_item – the sale item object
class stoqlib.domain.events.SaleItemAfterSetBatchesEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted after a sale item set it’s batches

This is called at the end of stoqlib.domain.sale.SaleItem.set_batches()

Parameters:
  • sale_item – the sale item object
  • new_sale_items – a list of the new sale items created when setting the batches
class stoqlib.domain.events.DeliveryStatusChangedEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a delivery has it’s status changed

Parameters:
  • delivery – the delivery which had it’s status changed
  • old_status – the old delivery status
class stoqlib.domain.events.SaleAvoidCancelEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to compare the last sale with the last document in ECF.

Parameters:
  • salesale that will be compared.
  • new_status – Indicates what the new status of the sale would become. This status can be Sale.STATUS_RETURNED and Sale.STATUS_CANCELLED
Returns:

True if the cancellation should be avoided or ``False` otherwise

class stoqlib.domain.events.PaymentGroupGetOrderEvent[source]

Bases: stoqlib.lib.event.Event

Get the order of a payment group.

Parameters:
  • group – the payment group that we want the related order
  • store – a store
class stoqlib.domain.events.CreatePaymentEvent[source]

Bases: stoqlib.lib.event.Event

This event is emmited when a payment is about to be created and should be used to ‘intercept’ that payment creation.

return value should be one of enum.CreatePaymentStatus

Parameters:
  • payment_method – The selected payment method.
  • sale – The sale the payment should belong to
returnclass

alias of CreatePaymentStatus

class stoqlib.domain.events.CardPaymentReceiptPrepareEvent[source]

Bases: stoqlib.lib.event.Event

This will be emmited when a card payment receipt should be printed.

Expected return value is a string to be printed

Parameters:
  • payment – the receipt of this payment
  • supports_duplicate – if the printer being used supports duplicate receipts
class stoqlib.domain.events.CardPaymentReceiptPrintedEvent[source]

Bases: stoqlib.lib.event.Event

This gets emmited after a card payment receipt is successfully printed.

Parameters:payment – the receipt of this payment
class stoqlib.domain.events.CancelPendingPaymentsEvent[source]

Bases: stoqlib.lib.event.Event

This gets emmited if a card payment receipt fails to be printed, meaning that all payments should be cancelled

class stoqlib.domain.events.GerencialReportPrintEvent[source]

Bases: stoqlib.lib.event.Event

This is emitted when the user requests a gerencial report for fiscal printers.

class stoqlib.domain.events.GerencialReportCancelEvent[source]

Bases: stoqlib.lib.event.Event

This is emitted when the user cancels a gerencial report for fiscal printers.

class stoqlib.domain.events.CheckECFStateEvent[source]

Bases: stoqlib.lib.event.Event

After the TEF has initialized, we must check if the printer is responding. TEF plugin will emit this event for the ECF plugin

class stoqlib.domain.events.TillOpenEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a till is opened

Parameters:till – the opened till
class stoqlib.domain.events.TillCloseEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a till is closed

Parameters:
  • till – the closed till
  • previous_day – if the till wasn’t closed previously
class stoqlib.domain.events.HasPendingReduceZ[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a has pending ‘reduce z’ in ecf.

class stoqlib.domain.events.TillAddCashEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when cash is added to a till

Parameters:
  • till – the closed till
  • value – amount added to the till
class stoqlib.domain.events.TillRemoveCashEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when cash is removed from a till

Parameters:
  • till – the closed till
  • value – amount remove from the till
class stoqlib.domain.events.TillAddTillEntryEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when:

  • cash is added to a till
  • cash is removed from a till
Parameters:
class stoqlib.domain.events.HasOpenCouponEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to check for opened coupon.

class stoqlib.domain.events.StockOperationConfirmedEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted when a stock operation is confirmed, such as sales, transfers, stock decreases, loans and sale returns

Parameters:
  • model – the model whose stock operation was confirmed
  • reason – the reason the model is being cancelled
  • old_status – the old status of the model if the confirmation includes a status change
class stoqlib.domain.events.StockOperationTryFiscalCancelEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to try to cancel a operation with sefaz.

Parameters:operation – the operation to be tried to cancel
Returns:True if the cancellation is successfull, False otherwise.
class stoqlib.domain.events.ECFGetPrinterUserNumberEvent[source]

Bases: stoqlib.lib.event.Event

This event is emitted to get the active ECFPrinter user number.

exampledata

fiscal

Domain classes to manage fiscal informations.

Note that this whole module is Brazil-specific.

class stoqlib.domain.fiscal.CfopData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A Brazil-specific class wich defines a fiscal code of operations. In Brazil it means ‘Codigo Fiscal de Operacoes e Prestacoes’

Canonical list of C.F.O.Ps can be found here

See also: schema

code

column: Unicode

fiscal code, for example. 1.102

description

column: Unicode

description, for example “Compra para comercialização”

class stoqlib.domain.fiscal.Invoice(**kw)[source]

Bases: stoqlib.domain.base.Domain

Stores information about invoices

invoice_number

column: Int

the invoice number

operation_nature

column: Unicode

the operation nature

invoice_type

column: EnumCol

the invoice type, representing an IN/OUT operation

series

column: Int

the invoice series

mode

column: EnumCol

the invoice mode

key

column: Unicode

the key generated by NF-e plugin

cnf

column: Unicode

numeric code randomly generated for each NF-e

branch

reference to: Branch

the branch where this invoice was generated

classmethod get_last_invoice_number(store, series=None, mode=None)[source]

Returns the last invoice number. If there is not an invoice number used, the returned value will be zero.

Parameters:store – a store
Returns:an integer representing the last sale invoice number
save_nfe_info(cnf, key)[source]

Save the CNF and KEY generated in NF-e.

check_unique_invoice_number_by_branch(invoice_number, branch, mode, series=None)[source]

Check if the invoice_number is used in determined branch

Parameters:
  • invoice_number – the invoice number we want to check
  • branch – the branch of the invoice
  • mode – one of the Invoice.mode
  • series – the series of the invoice
check_invoice_info_consistency()[source]

If the invoice number is set, series and mode should also be.

We should have a database constraint for this, but since these three data isn’t saved at once, the constraint would brake every time.

class stoqlib.domain.fiscal.IcmsIpiView[source]

Bases: stoqlib.domain.fiscal._FiscalBookEntryView

Stores information about the taxes (ICMS and IPI) related to a certain product. This view is used to query the product tax information.

Parameters:
  • id – the id of the fiscal_book_entry
  • icms_value – the total value of icms
  • ipi_value – the total value of ipi
  • date – the date when the entry was created
  • invoice_number – the invoice number
  • cfop_data_id – the cfop
  • cfop_code – the code of the cfop
  • drawee_name – the drawee name
  • drawee_id – the person
  • branch_id – the branch
  • payment_group_id – the payment group
class stoqlib.domain.fiscal.IssView[source]

Bases: stoqlib.domain.fiscal._FiscalBookEntryView

Stores information related to a service tax (ISS). This view is used to query the service tax information.

Parameters:
  • id – the id of the fiscal_book_entry
  • iss_value – the total value of ipi
  • date – the date when the entry was created
  • invoice_number – the invoice number
  • cfop_data_id – the if of the cfop_data table
  • cfop_code – the code of the cfop
  • drawee_name – the drawee name
  • drawee_id – the person
  • branch_id – the branch
  • payment_group_id – the payment group

image

Images domains

class stoqlib.domain.image.Image(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class responsible for storing images and it’s description

See also: schema

image

column: RawStr

the image itself in a bin format

thumbnail

column: RawStr

the image thumbnail in a bin format

description

column: Unicode

the image description

filename

column: Unicode

The image filename

create_date

column: DateTimeCol

The date that this image was uploaded to the database

notes

column: Unicode

Some notes about the image

is_main

column: Bool

If this is the main image. Only makes sense if sellable is not None

internal_use

column: Bool

If this image is only for internal use (i.e. it won’t be synchronized to any e-commerce website to be displayed publicly)

sellable

reference to: Sellable

The sellable that this image belongs to

interfaces

Interfaces definition for all domain classes

interface stoqlib.domain.interfaces.IActive[source]

Bases: zope.interface.Interface

It defines if a certain object can be active or not

is_active = <zope.interface.interface.Attribute object>

This attribute defines if the object is active

inactivate()

Inactivate an active object

activate()

Activate an inactive object

get_status_string()

Active or Inactive in the specific locale

interface stoqlib.domain.interfaces.IContainer[source]

Bases: zope.interface.Interface

An objects that holds other objects or items

add_item(item)

Add a persistent or non-persistent item associated with this model.

get_items()

Get all the items in the container. The result value could be a simple python list or an instance which maps to SQL statement.

remove_item(item)

Remove from the list or database the item desired.

interface stoqlib.domain.interfaces.IDescribable[source]

Bases: zope.interface.Interface

It defines that a object can be described through get_description method.

get_description()

Returns a description that identifies the object

interface stoqlib.domain.interfaces.IReversal[source]

Bases: zope.interface.Interface

A financial entry which support reversal operations

reverse_entry(invoice_number)

Takes a financial entry and reverse it, creating a new instance with an oposite value

interface stoqlib.domain.interfaces.IInvoice[source]

Bases: zope.interface.Interface

Information relating to operations (e.g. sale, transfer, loan) that generate NF-e

comments = <zope.interface.interface.Attribute object>

Operation comments

discount_value = <zope.interface.interface.Attribute object>

Discount value

identifier = <zope.interface.interface.Attribute object>

Identifier of performed operation

invoice_subtotal = <zope.interface.interface.Attribute object>

Operation subtotal

invoice_total = <zope.interface.interface.Attribute object>

Operation total

payments = <zope.interface.interface.Attribute object>

Payments generated by the operation

recipient = <zope.interface.interface.Attribute object>

Operation recipient

transporter = <zope.interface.interface.Attribute object>

Operation transporter

interface stoqlib.domain.interfaces.IInvoiceItem[source]

Bases: zope.interface.Interface

Information of NF-e items

parent = <zope.interface.interface.Attribute object>

The parent operation

base_price = <zope.interface.interface.Attribute object>

Base price

cfop_code = <zope.interface.interface.Attribute object>

C.F.O.P code

item_discount = <zope.interface.interface.Attribute object>

The discount applied in item

icms_info = <zope.interface.interface.Attribute object>

ICMS info object

ipi_info = <zope.interface.interface.Attribute object>

IPI info object

pis_info = <zope.interface.interface.Attribute object>

PIS info object

cofins_info = <zope.interface.interface.Attribute object>

Cofins info object

inventory

Inventory object and related objects implementation

class stoqlib.domain.inventory.InventoryItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An inventory item

It contains the recorded quantity and the actual quantity related to a specific product.

If those quantities are not identitical, it will also contain a reason and a cfop describing that.

See also: schema

product

reference to: Product

the item

batch

reference to: StorableBatch

If the product is a storable, the batch of the product that is being inventored

recorded_quantity

column: QuantityCol

the recorded quantity of the product, that is, the product’s quantity in stock at the time the inventory process started.

counted_quantity

column: QuantityCol

the counted quantity of the product, that is, a quantity counted by someone looking at the real physical stock

actual_quantity

column: QuantityCol

the actual quantity of the product, that will be used to increase/decrease stock using adjust(). Normally this will be the same as counted_quantity, but it can be different if, for instance, the count was done wrong. In cases like that, be sure to mention the reason for the difference on reason

product_cost

column: PriceCol

the product’s cost when the product was adjusted.

reason

column: Unicode

the reason of why this item has been adjusted

is_adjusted

column: Bool

if this inventory’s stock difference was adjusted

cfop_data

reference to: CfopData

the cfop used to adjust this item, this is only set when an adjustment is done

inventory

reference to: Inventory

the inventory process that contains this item

difference

The difference between the recorded and the counted quantities

This is the same as:

:obj:`.counted_quantity` - :obj:`.recorded_quantity`

Note that, if counted_quantity is None, this will also be None.

unit_description

Returns the product unit description or None if it’s not set

adjust(invoice_number)[source]

Create an entry in fiscal book registering the adjustment with the related cfop data and change the product quantity available in stock.

Parameters:invoice_number – invoice number to register
get_code()[source]

Get the product code of this item

Returns:the product code
get_description()[source]

Returns the product description

get_fiscal_description()[source]

Returns a description of the product tax constant

get_total_cost()[source]

Returns the total cost of this item, the actual quantity multiplied by the product cost in the moment it was adjusted. If the item was not adjusted yet, the total cost will be zero.

class stoqlib.domain.inventory.Inventory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

The Inventory handles the logic related to creating inventories for the available product (or a group of) in a certain branch.

It has the following states:

  • STATUS_OPEN: an inventory is opened, at this point the products which are going to be counted (and eventually adjusted) are selected. And then, the inventory items are available for counting and adjustment.
  • STATUS_CLOSED: all the inventory items have been counted (and eventually) adjusted.
  • STATUS_CANCELLED: the process was cancelled before being finished, this can only happen before any items are adjusted.

digraph inventory_status {
  STATUS_OPEN -> STATUS_CLOSED;
  STATUS_OPEN -> STATUS_CANCELLED;
}

STATUS_OPEN = u'open'

The inventory process is open

STATUS_CLOSED = u'closed'

The inventory process is closed

STATUS_CANCELLED = u'cancelled'

The inventory process was cancelled, eg never finished

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status of the inventory, either STATUS_OPEN, STATUS_CLOSED or STATUS_CANCELLED

invoice_number

column: Int

number of the invoice if this inventory generated an adjustment

open_date

column: DateTimeCol

the date inventory process was started

close_date

column: DateTimeCol

the date inventory process was closed

cancel_date

column: DateTimeCol

the date the inventory was cancelled

cancel_reason

column: Unicode

the reason the inventory was cancelled

responsible

reference to: LoginUser

the responsible for this inventory. At the moment, the login user that opened the inventory

branch

reference to: Branch

branch where the inventory process was done

cancel_responsible

reference to: LoginUser

The responsible for cancelling this inventory. At the moment, the login user that cancelled the inventory

inventory_items

the inventory items of this inventory

branch_name

The branch name for this inventory

responsible_name

The responsible for this inventory

add_storable(storable, quantity, batch_number=None, batch=None)[source]

Add a storable to this inventory.

The parameters product, storable and batch are passed here to avoid future queries, increase the performance when opening the inventory

Parameters:
  • storable – the storable to be added
  • quantity – the current quantity of the product in stock
  • batch_number – a batch number representing a batch for the given sellable. It’s used like that instead of getting the batch directly since we may be adding an item not registered before
  • batch – the corresponding batch to the batch_number
is_open()[source]

Checks if this inventory is opened

Returns:True if the inventory process is open, False otherwise
close()[source]

Closes the inventory process

Raises:AssertionError if the inventory is already closed
all_items_counted()[source]

Checks if all items of this inventory were counted

Returns:True if all inventory items are counted, False otherwise.
get_items()[source]

Returns all the inventory items related to this inventory

Returns:items
Return type:a sequence of InventoryItem
classmethod has_open(store, branch)[source]

Returns if there is an inventory opened at the moment or not.

Returns:The open inventory, if there is one. None otherwise.
get_items_for_adjustment()[source]

Gets all the inventory items that needs adjustment

An item needing adjustment is any InventoryItem with InventoryItem.recorded_quantity different from InventoryItem.counted_quantity.

Returns:items
Return type:a sequence of InventoryItem
has_adjusted_items()[source]

Returns if we already have an item adjusted or not.

Returns:True if there is one or more items adjusted, False otherwise.
cancel()[source]

Cancel this inventory

Note that you can only cancel an inventory as long as you haven’t adjusted any InventoryItem

Raises:AssertionError if the inventory is not open or if any item was already adjusted
get_inventory_data()[source]

Returns a generator with the details of the Inventory

Each item contains:

classmethod get_sellables_for_inventory(store, branch, extra_query=None)[source]

Returns a generator with the necessary data about the stock to open an Inventory

Parameters:
  • store – The store to fetch data from
  • branch – The branch that is being inventoried
  • query – A query that should be used to restrict the storables for the inventory. This can filter based on categories or other aspects of the product.
Returns:

a generator of the following objects: (Sellable, Product, Storable, StorableBatch, ProductStockItem)

classmethod create_inventory(store, branch, responsible, query=None)[source]

Create a inventory with products that match the given query

Parameters:
  • store – A store to open the inventory in
  • query – A query to restrict the products that should be in the inventory.
class stoqlib.domain.inventory.InventoryItemsView[source]

Bases: stoqlib.database.viewable.Viewable

Holds information about inventory items

This is used to get the most information of an inventory item without doing lots of database queries.

It’s best used with find_by_product()

inventory_item

the inventory item

alias of InventoryItem

inventory

the inventory

alias of Inventory

sellable

the sellable

alias of Sellable

batch

The |StorableBatch|

alias of StorableBatch

branch

alias of Branch

responsible_name

column: PropertyColumn

The name of the person that performed the inventory

code

column: PropertyColumn

The code of the sellable

description

column: PropertyColumn

The description of the product

batch_number = <storm.expr.Coalesce object>

The number of the batch that was adjusted

classmethod find_by_inventory(store, inventory)[source]

find results for this view that are related to the given inventory

Parameters:
  • store – the store that will be used to find the results
  • inventory – the inventory that should be filtered
Returns:

the matching views

Return type:

a sequence of InventoryItemView

classmethod find_by_product(store, product)[source]

find results for this view that references product

Parameters:
  • store – the store that will be used to find the results
  • product – the product used to filter the results
Returns:

the matching views

Return type:

a sequence of InventoryItemView

class stoqlib.domain.inventory.InventoryView[source]

Bases: stoqlib.database.viewable.Viewable

Stores general information’s about inventories

inventory

alias of Inventory

id

column: PropertyColumn

Inventory Id

identifier

column: PropertyColumn

Inventory Identifier

identifier_str = <storm.expr.Cast object>

Inventory Identifier ToString

invoice_number

column: PropertyColumn

Invoice number

open_date

column: PropertyColumn

Date of open operation

close_date

column: PropertyColumn

Date of close operation

status

column: PropertyColumn

Status of Inventory

branch_id

column: PropertyColumn

Id of referenced Branch

classmethod find_by_branch(store, branch=None)[source]

find results for this Inventory View that refenrences Branch

Parameters:
  • store – the store that will be used for find the results
  • branch – the branch used to filter the results
Returns:

the matching views

invoice

Invoice domain classes; field, layout and printer

class stoqlib.domain.invoice.InvoicePrinter(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An invoice printer is a representation of a physical printer connected to a branch station. It has a layout assigned which will be used to format the data sent to the printer

device_name

column: Unicode

a operating system specific identifier for the device used to send the printer job, /dev/lpX on unix

description

column: Unicode

a human friendly description of the printer, this will appear in interfaces

station_id

column: UUIDCol

the station this printer is connected to

layout_id

column: UUIDCol

the layout used to format the invoices

get_description()[source]

Gets the description of the printer. :returns: description

classmethod get_by_station(station, store)[source]

Gets the printer given a station. If there’s no invoice printer configured for this station, return None.

Parameters:
  • station – the station
  • store – a store
Returns:

an InvoiceLayout or None

class stoqlib.domain.invoice.InvoiceLayout(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A layout of an invoice.

description

column: Unicode

description of the layout, this is human friendly string which is displayed in interfaces.

width

column: Int

the width in units of the layout

height

column: Int

the height in units of the layout

continuous_page

column: Bool

Indicates the type of paper used to print the layout

fields

Fetches all the fields tied to this layout

Returns:a sequence of InvoiceField
get_description()[source]

Gets the description of the field

Returns:description.
class stoqlib.domain.invoice.InvoiceField(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Represents a field in an InvoiceLayout.

x

column: Int

x position of the upper left corner of the field

y

column: Int

y position of the upper left corner of the field

width

column: Int

the width of the field, must be larger than 0

height

column: Int

the height of the field, must be larger than 0

field_name

column: Unicode

the name of the field, this is used to identify and fetch the data when printing the invoice

content

column: Unicode

the free text of the field

layout_id

column: UUIDCol

the layout this field belongs to

loan

This module contains classes for working with loans.

The main class is Loan which can hold a set of LoanItem.

class stoqlib.domain.loan.LoanItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An item in a loan

Note that when changing quantity, return_quantity or sale_quantity you will need to call sync_stock() to synchronize the stock (increase or decrease it).

Also note that objects of this type should never be created manually, only by calling Loan.add_sellable()

See also: schema

quantity

column: QuantityCol

The total quantity that was loaned. The product stock for this will be decreased when the loan stock is synchonized

sale_quantity

column: QuantityCol

The loadned quantity that was sold. Will increase stock so it’s decreased correctly when the sale is confirmed

return_quantity

column: QuantityCol

The loaned quantity that was returned. Will increase stock

price

column: PriceCol

price to use for this sellable when creating a sale

base_price

column: PriceCol

original price of a sellable

sellable

reference to: Sellable

sellable that is loaned cannot be None

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was returned in

loan

reference to: Loan

loan this item belongs to

icms_info

reference to: InvoiceItemIcms

the stoqlib.domain.taxes.InvoiceItemIcms tax for self

ipi_info

reference to: InvoiceItemIpi

the stoqlib.domain.taxes.InvoiceItemIpi tax for self

pis_info

reference to: InvoiceItemPis

the stoqlib.domain.taxes.InvoiceItemPis tax for self

cofins_info

reference to: InvoiceItemCofins

the stoqlib.domain.taxes.InvoiceItemCofins tax for self

sync_stock()[source]

Synchronizes the stock, increasing/decreasing it accordingly. Using the stored values when this object is created/loaded, compute how much we should increase or decrease the stock quantity.

When setting quantity, return_quantity or sale_quantity be sure to call this to properly synchronize the stock (increase or decrease it). That counts for object creation too.

get_remaining_quantity()[source]

The remaining quantity that wasn’t returned/sold yet

This is the same as quantity - sale_quantity - return_quantity

set_discount(discount)[source]

Apply discount on this item

Note that the discount will be applied based on base_price and then substitute price, making any previous discount/surcharge being lost

Parameters:discount (decimal.Decimal) – the discount to be applied as a percentage, e.g. 10.0, 22.5
class stoqlib.domain.loan.Loan(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A loan is a collection of sellable that is being loaned to a client, the items are expected to be either be returned to stock or sold via a sale.

A loan that can hold a set of loan items

See also: schema manual

STATUS_OPEN = u'open'

The request for a loan has been added to the system, we know which of the items the client wishes to loan, it’s not defined if the client has actually picked up the items.

STATUS_CLOSED = u'closed'

All the products or other sellable items have been returned and are available in stock.

STATUS_CANCELLED = u'cancelled'

The loan is cancelled and all the products or other sellable items have been returned and are available in stock.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status of the loan

notes

column: Unicode

notes related to this loan.

open_date

column: DateTimeCol

date loan was opened

close_date

column: DateTimeCol

date loan was closed

expire_date

column: DateTimeCol

loan expires on this date, we expect the items to to be returned by this date

cancel_date

column: DateTimeCol

the date the loan was cancelled

cancel_reason

column: Unicode

the reason the loan was cancelled

branch_id

column: UUIDCol

branch where the loan was done

responsible_id

column: UUIDCol

user of the system that made the loan

client_id

column: UUIDCol

client that loaned the items

client_category

reference to: ClientCategory

the client category used for price determination.

loaned_items

a list of all items loaned in this loan

payments = None

payments generated by this loan

transporter = None

transporter used in loan

invoice

reference to: Invoice

The |invoice| generated by the loan

cancel_responsible_id

column: UUIDCol

The responsible for cancelling the loan. At the moment, the login user that cancelled the loan

add_sellable(sellable, quantity=1, price=None, batch=None)[source]

Adds a new sellable item to a loan

Parameters:
  • sellable – the sellable
  • quantity – quantity to add, defaults to 1
  • price – optional, the price, it not set the price from the sellable will be used
  • batch – the batch this sellable comes from if the sellable is a storable. Should be None if it is not a storable or if the storable does not have batches.
get_available_discount_for_items(user=None, exclude_item=None)[source]

Get available discount for items in this loan

The available items discount is the total discount not used by items in this sale. For instance, if we have 2 products with a price of 100 and they can have 10% of discount, we have 20 of discount available. If one of those products price is set to 98, that is, using 2 of it’s discount, the available discount is now 18.

Parameters:
  • user – passed to stoqlib.domain.sellable.Sellable.get_maximum_discount() together with client_category to check for the max discount for sellables on this sale
  • exclude_item – a sale item to exclude from the calculations. Useful if you are trying to get some extra discount for that item and you don’t want it’s discount to be considered here
Returns:

the available discount

set_items_discount(discount)[source]

Apply discount on this sale’s items

Parameters:discount (decimal.Decimal) – the discount to be applied as a percentage, e.g. 10.0, 22.5
get_total_amount()[source]

Fetches the total value of the loan, that is to be paid by the client.

It can be calculated as:

Sale total = Sum(product and service prices) + surcharge +
                 interest - discount
Returns:the total value
sync_stock()[source]

Synchronizes the stock of self‘s loan items

Just a shortcut to call LoanItem.sync_stock() of all of self‘s loan items instead of having to do that one by one.

can_close()[source]

Checks if the loan can be closed. A loan can be closed if it is opened and all the items have been returned or sold. :returns: True if the loan can be closed, False otherwise.

get_sale_base_subtotal()[source]

Get the base subtotal of items

Just a helper that, unlike get_sale_subtotal(), will return the total based on item’s base price.

Returns:the base subtotal
close()[source]

Closes the loan. At this point, all the loan items have been returned to stock or sold.

parameter

Domain classes for handling parameters

class stoqlib.domain.parameter.ParameterData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class to store system parameters.

See also: schema

field_name

column: Unicode

name of the parameter we want to query on

field_value

column: Unicode

current result(or value) of this parameter

is_editable

column: Bool

the item can’t be edited through an editor.

payment.card

This module contains all related classes to the credit card payment method. This includes:

class stoqlib.domain.payment.card.CreditProvider(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A credit provider

This is the institution that provides the credit to the client, for instance: American Express, Visanet, Redecard, etc...

short_name

column: Unicode

A short description of this provider

provider_id

column: Unicode

An identification for this provider

max_installments

column: Int

the maximum number of installments for a sale using this credit provider.

default_device

reference to: CardPaymentDevice

The default device for this credit provider. This will be suggested to the user when he selects this provider in the checkout dialog

open_contract_date

column: DateTimeCol

The date when we start working with this provider

classmethod get_provider_by_provider_id(provider_id, store)[source]

Get a provider given a provider id string :param provider_id: a string representing the provider :param store: a database store

classmethod get_card_providers(store)[source]

Get a list of all credit card providers. :param store: a database store

classmethod has_card_provider(store)[source]

Find out if there is a card provider :param store: a database store :returns: if there is a card provider

class stoqlib.domain.payment.card.CardPaymentDevice(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An eletronic device used to charge the client.

Each device may have different costs for the company, depending on the contract between them.

These costs should be configured using card operation cost

monthly_cost

column: PriceCol

How much the it costs the shop per month to have this device

description

column: Unicode

user-defined description of the device, like “Mastercard reader”

supplier_id

column: UUIDCol

The supplier id for this device

classmethod delete(id, store)[source]

Removes a device from the database.

Since devices may be referenced by card operation cost and credit card data objects, this method will also:

class stoqlib.domain.payment.card.CardOperationCost(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

The cost of a given operation on the card payment device

The cost of an operation depend on the following parameters:

device

reference to: CardPaymentDevice

The card device used to charge the client

provider

reference to: CreditProvider

The credit provider of the card

installment_start

column: Int

When paid in installments, this fee and fare will only apply if the installments number is in the range defined by installment_start and installment_end

installment_end

column: Int

See installment_start

payment_days

column: Int

How many days the credit provider takes to transfer the shop the money for one payment

fee

column: PercentCol

The percentage of each payment value that will be charged by the credit provider

fare

column: PriceCol

This is a fixed currency value that is charged for each payment

installment_range_as_string

A string representation of the installments range

classmethod validate_installment_range(device, provider, card_type, start, end, store, ignore=None)[source]

Checks if a given range is not conflicting with any other operation cost

Parameters:
  • device – the card payment device that will be used
  • provider – the credit provider related to the cost
  • card_type – the car type (credit, debit, etc...)
  • start – the start of the installment range
  • end – the end of the installment range
  • ignore – if not None, should be an id of a card operation cost that should be ignored in the query (ie, the object currently being edited).
Returns:

True the range is valid for the given parameters. A valid range means that for every possible installment value in the given range, there are no other card operation cost objects that matches the installment value.

class stoqlib.domain.payment.card.CreditCardData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Stores CreditCard specific state related to a payment

This state include:

TYPE_CREDIT = u'credit'

Credit card payment, single installment

TYPE_DEBIT = u'debit'

Debit card payment

TYPE_CREDIT_INSTALLMENTS_STORE = u'credit-inst-store'

Credit card payment with two or more installments. In this case, the shop is responsible for the installments, and will receive one payment each month

TYPE_CREDIT_INSTALLMENTS_PROVIDER = u'credit-inst-provider'

Credit card payment with two or more installments. In this case, the credit provider is responsible for the installments and the shop will receive the value in only one payment

TYPE_DEBIT_PRE_DATED = u'debit-pre-dated'

This is a debit card payment, but will be charged on a pre-defined future date. Not completely supported in Stoq yet

payment

reference to: Payment

the payment this information is about

provider

reference to: CreditProvider

the credit provider for this class

device

reference to: CardPaymentDevice

the card payment device used for the payment If the card payment device is excluded in the future, this value will be set to null.

fare

column: PriceCol

the fixed value that will be charged for the related payment

fee

column: PercentCol

the percentage of the value that will be charged for the related payment

fee_value

column: PriceCol

the fee that will be charged based on the fee

nsu

column: Int

this is used by the tef plugin.

auth

column: Int

The authorization number returned by the payment device. This will be returned automatically by the tef plugin, but needs to be manually informed if not using the plugin.

installments

column: Int

the number of installments, used by the tef plugin

entrance_value

column: PriceCol

the value of the first installment (when installments > 1), used by the tef plugin

update_card_data(device, provider, card_type, installments)[source]

Creates a new card operation cost based on card payment device, credit provider, card_type and installments to update credit card data.

Parameters:
  • device – the payment device
  • provider – the credit provider
  • card_type – the type of card, may be either credit or debit
  • installments – the number of installments

payment.category

Payment category, user defined grouping of payments

class stoqlib.domain.payment.category.PaymentCategory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

I am a payment category. I contain a name and a color

TYPE_PAYABLE = u'payable'

for outgoing payments (payable application)

TYPE_RECEIVABLE = u'receivable'

for incoming payments (receivable application)

name

column: Unicode

category name

color

column: Unicode

category color, like #ff0000 for red.

category_type

column: EnumCol

category type, payable or receivable

classmethod get_by_type(store, category_type)[source]

Fetches a list of PaymentCategories given a category type

Parameters:
  • store – a store
  • category_type – TYPE_PAYABLE or TYPE_RECEIVABLE
Rseturns:

a sequence of PaymentCategory ordered by name

payment.comment

Payment comment implementations.

payment.dailymovement

Views related to Daily Movement Reports

payment.group

Payment groups, a set of payments

The five use cases for payment groups are:

  • Sale
  • Purchase
  • Renegotiation
  • Stockdecreae
  • Lonely payments

All of them contains a set of payments and they behaves slightly differently

class stoqlib.domain.payment.group.PaymentGroup(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A set of payments, all related to the same sale, purchase, payment renegotiation or stock decrease. The set of payments can also be lonely, eg not associated with one of objects mentioned above.

A payer is paying the recipient who’s receiving the payments.

payer

reference to: Person

the person who is paying this group

recipient

reference to: Person

the person who is receiving this group

renegotiation

reference to: PaymentRenegotiation

the payment renegotation this group belongs to

sale

reference to: Sale

The sale if this group is part of one

purchase

reference to: PurchaseOrder

The purchase if this group is part of one

stock_decrease

reference to: StockDecrease

The stock decrease if this group is part of one

payments

Returns all payments of this group

Returns:a list of payments
installments_number

The number of installments(payments) that are part of this group.

get_order_object()[source]

Get the order object related to this payment group

confirm()[source]

Confirms all payments in this group

Confirming the payment group means that the customer has confirmed the payments. All individual payments are set to pending.

pay()[source]

Pay all payments in this group

pay_method_payments(method_name)[source]

Pay all payments of a method in this group

Parameters:method_name – the method of the payments to be paid
cancel()[source]

Cancel all pending payments in this group

get_total_paid()[source]

Returns the sum of all paid payment values within this group.

Returns:the total paid value
get_total_value()[source]

Returns the sum of all payment values.

This will consider all payments ignoring just the cancelled ones.

If you want to ignore preview payments too, use get_total_confirmed_value() instead

Returns:the total payment value or zero.
get_total_to_pay()[source]

Returns the total amount to be paid to have the group fully paid.

get_total_confirmed_value()[source]

Returns the sum of all confirmed payments values

This will consider all payments ignoring cancelled and preview ones, that is, if a payment is confirmed/reviewing/paid it will be summed.

If you want to consider the preview ones too, use get_total_value() instead

Returns:the total confirmed payments value
clear_unused()[source]

Delete payments of preview status associated to the current payment_group. It can happen if user open and cancel this wizard.

get_description()[source]

Returns a small description for the payment group which will be used in payment descriptions

Returns:the description
get_pending_payments()[source]

Returns a list of pending payments :returns: list of payments

get_parent()[source]

Return the sale, purchase, payment renegotiation or stock decrease this group is part of.

Returns:the object this group is part of or None
get_total_discount()[source]

Returns the sum of all payment discounts.

Returns:the total payment discount or zero.
get_total_interest()[source]

Returns the sum of all payment interests.

Returns:the total payment interest or zero.
get_total_penalty()[source]

Returns the sum of all payment penalties.

Returns:the total payment penalty or zero.
get_valid_payments()[source]

Returns all payments that are not cancelled.

Returns:list of payments
get_payments_by_method_name(method_name)[source]

Returns all payments of a specific payment method within this group.

Parameters:method_name (unicode) – the name of the method
Returns:list of payments

payment.method

Payment methods

class stoqlib.domain.payment.method.CheckData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Stores check informations and also a history of possible devolutions.

payment

reference to: Payment

the payment

bank_account

reference to: BankAccount

the bank account

class stoqlib.domain.payment.method.PaymentMethod(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A PaymentMethod controls how a payments is paid. Example of payment methods are:

* money
* bill
* check
* credit card

This class consists of the persistent part of a payment method. The logic itself for the various different methods are in the PaymentMethodOperation classes. Each PaymentMethod has a PaymentMethodOperation associated.

penalty

column: PercentCol

a value for the penalty. It must always be in the format:

0 <= penalty <= 100
payment_day

column: Int

which day in the month is the credit provider going to pay the store? Usually they pay in the same day every month.

closing_day

column: Int

which day the credit provider stoq counting sales to pay in the payment_day? Sales after this day will be paid only in the next month.

operation

Get the operation for this method. The operation contains method specific logic when creating/deleting a payment.

Returns:the operation associated with the method
Return type:object implementing IPaymentOperation
create_payment(payment_type, payment_group, branch, value, due_date=None, description=None, base_value=None, payment_number=None, identifier=None)[source]

Creates a new payment according to a payment method interface

Parameters:
  • payment_type – the kind of payment, in or out
  • payment_group – a PaymentGroup subclass
  • branch – the branch associated with the payment, for incoming payments this is the branch receiving the payment and for outgoing payments this is the branch sending the payment.
  • value – value of payment
  • due_date – optional, due date of payment
  • details – optional
  • description – optional, description of the payment
  • base_value – optional
  • payment_number – optional
Returns:

a payment

create_payments(payment_type, group, branch, value, due_dates)[source]

Creates new payments The values of the individual payments are calculated by taking the value and dividing it by the number of payments. The number of payments is determined by the length of the due_dates sequence.

Parameters:
  • payment_type – the kind of payment, in or out
  • payment_group – a payment group
  • branch – the branch associated with the payments, for incoming payments this is the branch receiving the payment and for outgoing payments this is the branch sending the payment.
  • value – total value of all payments
  • due_dates – a list of datetime objects
Returns:

a list of payments

describe_payment(payment_group, installment=1, installments=1)[source]

Returns a string describing payment, in the following format: current_installment/total_of_installments payment_description for payment_group_description

Parameters:
  • payment_group – a PaymentGroup
  • installment – current installment
  • installments – total installments
Returns:

a payment description

classmethod get_active_methods(store)[source]

Returns a list of active payment methods

classmethod get_by_name(store, name)[source]

Returns the Payment method associated by the nmae

Parameters:name – name of a payment method
Returns:a payment methods
classmethod get_by_account(store, account)[source]

Returns the Payment method associated with an account

Parameters:accountaccount for which the payment methods are associated with
Returns:a sequence payment methods
classmethod get_creatable_methods(store, payment_type, separate)[source]

Gets a list of methods that are creatable. Eg, you can use them to create new payments.

Returns:a list of payment methods
classmethod get_editable_methods(store)[source]

Gets a list of methods that are editable Eg, you can change the details such as maximum installments etc.

Returns:a list of payment methods
selectable()[source]

Finds out if the method is selectable, eg if the user can select it when doing a sale.

Returns:True if selectable

payment.operation

Payment operations

This file contains payment operations, a payment operation is responsible for the logic needed by a payment method. Such as storing the kind of credit card or associate a check with a bank account.

stoqlib.domain.payment.operation.payment_operation(method_name=None, fallback=False)[source]

A class decorator to register a payment operation which contains some of the business logic for a certain payment method.

Parameters:
  • method_name – name of the method or None
  • fallback – if True, will be registered as a fallback
stoqlib.domain.payment.operation.get_payment_operation_manager()[source]

Returns the payment operation manager

stoqlib.domain.payment.operation.get_payment_operation(method_name)[source]

Returns the payment operation for method_name

Parameters:method_name – the method name
class stoqlib.domain.payment.operation.CreditPaymentOperation[source]

Bases: object

This payment method is used to register deposits (inpayments) and withdrawals (outpayments) in a client’s credit account.

When returning a sale, the store or the client can choose whether they want to return in cash or if the account is deposited as credit so the client can use it in the future.

class stoqlib.domain.payment.operation.InvalidPaymentOperation[source]

Bases: object

This operation will be used as a fallback for methods that wore removed from stoq, but may still exist in the database (they cannot be removed, since payments may have been created using that method).

payment.payment

Payment management implementations.

This module is centered around payments.

The main payment class is payment which is a transfer of money, to or from a branch.

Certain changes to a payment is saved in PaymentChangeHistory

class stoqlib.domain.payment.payment.Payment(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

Payment, a transfer of money between a branch and client or a supplier.

Payments between:

Payments are sometimes referred to as installments.

Sales and purchase orders can be accessed via the payment group

Status Can be set to
STATUS_PREVIEW STATUS_PENDING
STATUS_PENDING STATUS_PAID, STATUS_CANCELLED
STATUS_PAID STATUS_PENDING, STATUS_CANCELLED
STATUS_CANCELLED None

digraph status {
  STATUS_PREVIEW -> STATUS_PENDING;
  STATUS_PENDING -> STATUS_PAID;
  STATUS_PENDING -> STATUS_CANCELLED;
  STATUS_PAID -> STATUS_PENDING;
  STATUS_PAID -> STATUS_CANCELLED;
}

Simple sale workflow:

See also: schema

TYPE_IN = u'in'

incoming to the company, accounts receivable, payment from a client to a branch

TYPE_OUT = u'out'

outgoing from the company, accounts payable, a payment from branch to a supplier

STATUS_PREVIEW = u'preview'

payment group this payment belongs to hasn’t been confirmed,

STATUS_PENDING = u'pending'

payment group has been confirmed and the payment has not been received

STATUS_PAID = u'paid'

the payment has been received

STATUS_REVIEWING = u'reviewing'

Unused.

STATUS_CONFIRMED = u'confirmed'

Unused.

STATUS_CANCELLED = u'cancelled'

payment was cancelled, for instance the payments of the group was changed, or the group was cancelled.

payment_type

column: EnumCol

type of payment TYPE_IN or TYPE_OUT

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status, see payment for more information.

description

column: Unicode

description payment, usually something like “1/3 Money for Sale 1234”

open_date

column: DateTimeCol

when this payment was opened

due_date

column: DateTimeCol

when this payment is due

paid_date

column: DateTimeCol

when this payment was paid

cancel_date

column: DateTimeCol

when this payment was cancelled

base_value

column: PriceCol

base value

value

column: PriceCol

value of the payment

paid_value

column: PriceCol

the actual amount that was paid, including penalties, interest, discount etc.

interest

column: PriceCol

interest of this payment

discount

column: PriceCol

discount, an absolute value with the difference between the sales price and value

penalty

column: PriceCol

penalty of the payment

payment_number

column: Unicode

number of the payment

branch

reference to: Branch

branch associated with this payment. For a TYPE_IN payment, this is the branch that will receive the money. For a TYPE_IN payment, this is the branch that will make the payment

method

reference to: PaymentMethod

payment method for this payment payment

group

reference to: PaymentGroup

payment group for this payment

category

reference to: PaymentCategory

category this payment belongs to, can be None

comments

list of comments for this payment

check_data

reference to: CheckData

check data for this payment

transaction

reference to: AccountTransaction

account transaction for this payment

bill_received

column: Bool

indicates if a bill has been received. They are usually delivered by mail before the due date. This is not indicating whether the payment has been paid, just that the receiver has notified the payer somehow.

attachment

reference to: Attachment

attachment for this payment

classmethod create_repeated(store, payment, repeat_type, start_date, end_date)[source]

Create a set of repeated payments. Given a type of interval (repeat_type), a start date and an end_date, this creates a list of payments for that interval.

Note, this will also update the description of the payment that’s passed in. :param store: a store :param payment: the payment to repeat :param repeat_type: the kind of repetition (weekly, monthly etc) :param start_date: the date to start this repetition :param end_date: the date to end this repetition :returns: a list of repeated payments

comments_number

The number of payment comments for this payment

bank_account_number

For check payments, the bank account number

status_str

The Payment.status as a translated string

get_days_late()[source]

For due payments, the number of days late this payment is

Returns:the number of days late
set_pending()[source]

Set a STATUS_PREVIEW payment as STATUS_PENDING. This also means that this is valid payment and its owner actually can charge it

set_not_paid(change_entry)[source]

Set a STATUS_PAID payment as STATUS_PENDING. This requires clearing paid_date and paid_value

Parameters:change_entry – a PaymentChangeHistory object, that will hold the changes information
pay(paid_date=None, paid_value=None, source_account=None, destination_account=None, account_transaction_number=None)[source]

Pay the current payment set its status as STATUS_PAID

If this payment belongs to a sale, and all other payments from the sale are paid then the sale will be set as paid.

cancel(change_entry=None)[source]

Cancel the payment, set it’s status to STATUS_CANCELLED

change_due_date(new_due_date)[source]

Changes the payment due date. :param new_due_date: The new due date for the payment. :rtype: datetime.date

update_value(new_value)[source]

Update the payment value.

get_payable_value()[source]

Returns the calculated payment value with the daily interest.

Note that the payment group daily_interest must be between 0 and 100.

Returns:the payable value
get_penalty(date=None)[source]

Calculate the penalty in an absolute value

Parameters:date – date of payment
Returns:penalty
Return type:kiwi.currency.currency
get_interest(date=None, pay_penalty=True)[source]

Calculate the interest in an absolute value

Parameters:date – date of payment
Returns:interest
Return type:kiwi.currency.currency
has_commission()[source]

Check if this payment already has a commission

is_paid()[source]

Check if the payment is paid.

Returns:True if the payment is paid
is_pending()[source]

Check if the payment is pending.

Returns:True if the payment is pending
is_preview()[source]

Check if the payment is in preview state

Returns:True if the payment is paid
is_cancelled()[source]

Check if the payment was cancelled.

Returns:True if the payment was cancelled
get_paid_date_string()[source]

Get a paid date string

Returns:the paid date string or PAID DATE if the payment isn’t paid
get_open_date_string()[source]

Get a open date string

Returns:the open date string or empty string
is_inpayment()[source]

Find out if a payment is incoming

Returns:True if it’s incoming
is_outpayment()[source]

Find out if a payment is outgoing

Returns:True if it’s outgoing
is_separate_payment()[source]

Find out if this payment is created separately from a sale, purchase or renegotiation :returns: True if it’s separate.

is_of_method(method_name)[source]

Find out if the payment was made with a certain method

Returns:True if it’s a payment of that method
class stoqlib.domain.payment.payment.PaymentChangeHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A class to hold information about changes to a payment.

Only one tuple (last_due_date, new_due_date) or (last_status, new_status) should be non-null at a time.

See also: schema

payment

reference to: Payment

the changed payment

change_reason

column: Unicode

the reason of the change

change_date

column: DateTimeCol

when the changed happened

last_due_date

column: DateTimeCol

the due date that was set before the changed

new_due_date

column: DateTimeCol

the due date that was set after changed

last_status

column: EnumCol

status before the change

new_status

column: EnumCol

status after change

payment.renegotiation

Domain classes for renegotiation management

class stoqlib.domain.payment.renegotiation.PaymentRenegotiation(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class for payments renegotiations

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

can_set_renegotiated()[source]

Only sales with status confirmed can be renegotiated. :returns: True if the sale can be renegotiated, False otherwise.

set_renegotiated()[source]

Set the sale as renegotiated. The sale payments have been renegotiated and the operations will be done in other payment group.

payment.views

class stoqlib.domain.payment.views.CardPaymentView[source]

Bases: stoqlib.database.viewable.Viewable

A view for credit providers.

payment

alias of Payment

credit_card_data

alias of CreditCardData

branch

the branch this payment was created on

alias of Branch

class stoqlib.domain.payment.views.InCheckPaymentView[source]

Bases: stoqlib.domain.payment.views._BillandCheckPaymentView

Stores information about bill and check receivings.

class stoqlib.domain.payment.views.OutCheckPaymentView[source]

Bases: stoqlib.domain.payment.views._BillandCheckPaymentView

Stores information about bill and check payments.

class stoqlib.domain.payment.views.PaymentChangeHistoryView[source]

Bases: stoqlib.database.viewable.Viewable

Holds information about changes to a payment.

changed_field

Return the name of the changed field.

person

Person domain classes

The Person domain classes in Stoqlib are special since the Person class is small and additional functionality is provided through facets.

There are currently the following person facets available:

To create a new person, just issue the following:

>>> from stoqlib.database.runtime import new_store
>>> store = new_store()

>>> person = Person(name=u"A new person", store=store)

Then to add a client, you can will do:

>>> client = Client(person=person, store=store)
class stoqlib.domain.person.EmployeeRole(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Base class to store the employee roles.

has_other_role(name)[source]

Check if there is another role with the same name

Parameters:name – name of the role to check
Returns:True if it exists, otherwise False
class stoqlib.domain.person.WorkPermitData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Work permit data for an employee.

Note

This is Brazil-specific information.

pis_number

column: Unicode

number of PIS (“Programa de Integracao Social”)

pis_bank

column: Unicode

bank PIS (“Programa de Integracao Social”)

pis_registry_date

column: DateTimeCol

registry date of PIS (“Programa de Integracao Social”)

class stoqlib.domain.person.MilitaryData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Military data for an employee.

Note

This is Brazil-specific information.

class stoqlib.domain.person.VoterData(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Voter data for an employee.

Note

This is Brazil-specific information.

class stoqlib.domain.person.ContactInfo(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class to store the person’s contact information. This can be used to store:

  • phone numbers (land lines and mobile)
  • email addresses
  • web sites (corporate, home, Facebook, Google Plus)
  • IM contact information
  • contact of other people inside an organization
description

column: Unicode

describes what the contact information is, e.g. Home Phone Number

contact_info

column: Unicode

the contact information itself, e.g. 1234-5678, user@example.com, ...

person

reference to: Person

the person

class stoqlib.domain.person.CreditCheckHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Client credit check history

This stores credit information about a client.

From time to time, a store may contact some ‘credit protection agency’ that will inform the status of a certain client, for instance, if the client has active debt with other companies.

STATUS_INCLUDED = u'included'

if a client has debt

STATUS_NOT_INCLUDED = u'not-included'

if a client does not have debt

creation_date

column: DateTimeCol

when this check was created

check_date

column: DateTimeCol

when the check was made

identifier

column: Unicode

an unique identifier created by the agency

status

column: EnumCol

the client status given the options above

notes

column: Unicode

notes about the credit check history created by the user

client

reference to: Client

the client

user

reference to: LoginUser

the user that created this entry

class stoqlib.domain.person.Calls(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Person’s calls information.

Calls are information associated to a person (client, supplier, employee, etc) that can be financial problems registries, collection letters information, some problems with a product delivered, etc.

person

reference to: Person

the person

class stoqlib.domain.person.Person(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A Person, an entity that can be contacted (via phone, email). It usually has an address.

name

column: Unicode

name of the person, depending on the facets, it can either be something like “John Doe” or “Microsoft Corporation”

phone_number

column: Unicode

phone number for this person

mobile_number

column: Unicode

cell/mobile number for this person

fax_number

column: Unicode

fax number for this person

email

column: Unicode

email address

notes

column: Unicode

notes about the person

contact_infos

all contact information <ContactInfo> related to this person

addresses

list of addresses

calls

all calls <Calls> made to this person

branch

reference to: Branch

the branch facet for this person

client

reference to: Client

the client facet for this person

company

reference to: Company

the company facet for this person

employee

reference to: Employee

employee facet for this person

individual

reference to: Individual

individual for this person

login_user

reference to: LoginUser

login user facet for this person

sales_person

reference to: SalesPerson

the sales person facet for this person

supplier

reference to: Supplier

the supplier facet for this person

transporter

reference to: Transporter

the transporter facet for this person

merged_with_id

column: UUIDCol

The id of the person this person has been merged into. When a person is merged into another one. All references to that person (and its facets) are updated to the other person.

address

The address for this person

classmethod get_by_document(store, document)[source]

Returns a person given a specific document.

Parameters:
  • store – a database store
  • document – a document can be a cpf from a individual

or a cnpj from a company (Brazil standard) :returns: person

get_main_address()[source]

The primary address for this person. It is normally set when you register the client for the first time.

get_total_addresses()[source]

The total number of addresses for this person.

Returns:the number of addresses
get_address_string()[source]

The primary address for this person formatted as a string.

Returns:the address
get_phone_number_number()[source]

Returns the phone number without any non-numeric characters

Returns:the phone number as a number
get_fax_number_number()[source]

Returns the fax number without any non-numeric characters

Returns:the fax number as a number
get_formatted_phone_number()[source]
Returns:a dash-separated phone number or an empty string
get_formatted_fax_number()[source]
Returns:a dash-separated fax number or an empty string
get_formatted_mobile_number()[source]
Returns:a dash-separated fax number or an empty string
classmethod get_items(store, query)[source]

Return a list of items (name, id)

Parameters:store – a store
Returns:the items
get_cnpj_or_cpf()[source]

Returns this person cnpf or cpf

If the person is a company, return its cnpj, otherwise, return its cpf.

merge_with(other, copy_empty_values=True)[source]

Merges this person with other objects

This will fix all references that point to the other person, and make them point to this person.

class stoqlib.domain.person.Individual(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Being or characteristic of a single person, concerning one person exclusively

person

reference to: Person

the person

cpf

column: Unicode

the national document used to identify this person.

rg_number

column: Unicode

A Brazilian government register which identify an individual

birth_date

column: DateTimeCol

when this individual was born

occupation

column: Unicode

current job

marital_status

column: EnumCol

martial status, single, married, widow etc

father_name

column: Unicode

Name of this individuals father

mother_name

column: Unicode

Name of this individuals mother

rg_expedition_date

column: DateTimeCol

When the rg number was issued

rg_expedition_local

column: Unicode

Where the rg number was issued

gender

column: EnumCol

unregistered/male/female

spouse_name

column: Unicode

the name of the spouse individual’s partner in marriage

birth_location

reference to: CityLocation

the location where individual was born

get_cpf_number()[source]

Returns the cpf number without any non-numeric characters

Returns:the cpf number as a number
check_cpf_exists(cpf)[source]

Returns True if we already have a Individual with the given CPF in the database.

get_raw_cpf()[source]

Returns the cpf without non-numeric characters as a string.

classmethod get_birthday_query(start, end=None)[source]

Get a database query suitable to use in a SearchColumn.search_func callback. This can either be searching for a birthday in a date or an interval of dates.

Parameters:
  • start – start date
  • end – for intervals, an end date, use None for single days
Returns:

the database query

class stoqlib.domain.person.Company(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An institution created to conduct business

person

reference to: Person

the person

cnpj

column: Unicode

a number identifing the company

fancy_name

column: Unicode

Doing business as (dba) name for this company, a secondary, non-legal name of the company.

state_registry

column: Unicode

Brazilian register number associated with a certain state

city_registry

column: Unicode

Brazilian register number associated with a certain city

get_cnpj_number()[source]

Returns the cnpj number without any non-numeric characters

Returns:the cnpj number as a number
get_state_registry_number()[source]

Returns the state registry number without any non-numeric characters

Returns:the state registry number as a number or zero if there is no state registry.
check_cnpj_exists(cnpj)[source]

Returns True if we already have a Company with the given CNPJ in the database.

get_raw_cnpj()[source]

Returns the cnpj without non-numeric characters as a string.

class stoqlib.domain.person.ClientCategory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

I am a client category.

name

column: Unicode

name of the category

max_discount

column: PercentCol

max discount for clients of this category

can_remove()[source]

Check if the client category is used in some product.

remove()[source]

Remove this client category from the database.

class stoqlib.domain.person.Client(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An individual or a company who pays for goods or services

person

reference to: Person

the person

status

column: EnumCol

ok, indebted, insolvent, inactive

days_late

column: Int

How many days is this client indebted

credit_limit

column: PriceCol

How much the user can spend on store credit, this is not related to credit given when returning a sale. It’s basically how much this client can buy before having to pay.

category

reference to: ClientCategory

the client category for this client

sales

all the sales to this client

classmethod get_active_items(store)[source]

Return a list of active items (name, id)

Parameters:store – a store
Returns:the items
get_name()[source]

Name of the client

classmethod get_active_clients(store)[source]

Return a list of active clients. An active client is a person who are authorized to make new sales

classmethod update_credit_limit(percent, store)[source]

Updates clients credit limit acordingly to the new percent informed.

This perecentage is aplied to the client salary to calculate the credit limit.

Only clients with an informed salary will have the credit limit updated.

Parameters:percent – The percentage value that will be used to calculate the new credit limit.
get_client_sales()[source]

Returns a list of sale views tied with the current client

get_client_returned_sales()[source]

Returns a list of returned sales tied with the current client

get_client_services()[source]

Returns a list of sold service views stoqlib.domain.sale.SoldServicesView> with services consumed by this client

get_client_work_orders()[source]

Returns the :class:’stoqlib.domain.WorkOrderView’ associated with a client :returns: a sequence of :class:’stoqlib.domain.WorkOrderView’

get_client_products(with_children=True)[source]

Returns a list of products from SoldProductsView with products sold to the client

get_client_payments()[source]

Returns a list of payment from InPaymentView with client’s payments

get_last_purchase_date()[source]

Fetch the date of the last purchased item by this client. None is returned if there are no sales yet made by the client

Returns:the date of the last purchased item
get_credit_transactions()[source]

Returns all credit payments (in and out) associated with a client’s credit account.

Returns:a list of Settables representing payments.
credit_account_balance

Returns a client’s credit balance.

Returns:The client’s credit balance.
can_purchase(method, total_amount)[source]

This method checks the following to see if the client can purchase:

- The parameter LATE_PAYMENTS_POLICY,
- The payment method to be used,
- The total amount of the |payment|,
- The :obj:`.remaining_store_credit` of this client, when necessary.
Parameters:
  • method – an payment method.
  • total_amount – the value of the payment that should be created for this client.
Returns:

True if user is allowed. Raises an SellError if user is not allowed to purchase.

class stoqlib.domain.person.Supplier(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A company or an individual that produces, provides, or furnishes an item or service

person

reference to: Person

the person

status

column: EnumCol

active/inactive/blocked

product_desc

column: Unicode

A short description telling which products this supplier produces

get_name()[source]
Returns:the supplier’s name
classmethod get_active_items(store)[source]

Return a list of active items (name, id)

Parameters:store – a store
Returns:the items
get_supplier_purchases()[source]

Gets a list of PurchaseOrderViews representing all purchases done from this supplier. :returns: a list of PurchaseOrderViews.

get_last_purchase_date()[source]

Fetch the date of the last purchased item by this supplier. None is returned if there are no sales yet made by the client.

Returns:the date of the last purchased item
Return type:datetime.date or None
class stoqlib.domain.person.Employee(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An individual who performs work for an employer under a verbal or written understanding where the employer gives direction as to what tasks are done

status

column: EnumCol

normal/away/vacation/off

person

reference to: Person

the person

salary

column: PriceCol

salary for this employee

admission_date

column: DateTimeCol

when this employeer started working for the branch

expire_vacation

column: DateTimeCol

when the vaction expires for this employee

role

reference to: EmployeeRole

A reference to an employee role object

branch

reference to: Branch

The branch this employee works on

classmethod get_active_employees(store)[source]

Return a list of active employees.

class stoqlib.domain.person.LoginUser(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

A user that us able to login to the system

person

reference to: Person

the person

username

column: Unicode

username, used to login it to the system

pw_hash

column: Unicode

a hash (md5) for the user password

profile

reference to: UserProfile

A profile represents a colection of information which represents what this user can do in the system

classmethod hash(password)[source]
Returns:the hash of a password.
classmethod authenticate(store, username, pw_hash, current_branch)[source]

Authenticates a user against the credentials passed. :returns: A login user if a user is found, else returns None.

status_str

Returns the status description of a user

classmethod get_active_users(store)[source]

Returns a list of all active login users

get_associated_branches()[source]

Returns all the branches which the user has access

has_access_to(branch)[source]

Checks if the user has access to the given branch.

If the user has access to Administrative App, he has access to any branch.

set_password(password)[source]

Changes the user password.

class stoqlib.domain.person.Branch(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An administrative division of some larger or more complex organization

person

reference to: Person

the person

manager

reference to: Employee

An employee which is in charge of this branch

crt

column: Int

Brazil specific, “Código de Regime Tributário”, one of:

  • Simples Nacional
  • Simples Nacional – excesso de sublimite da receita bruta
  • Regime Normal
acronym

column: Unicode

An acronym that uniquely describes a branch

can_execute_foreign_work_orders

column: Bool

if this branch can execute work orders that belongs to other branches

set_acronym(value)[source]

Sets the branch acronym.

Parameters:value – The new acronym for this branch. If an empty string is used, it will be changed to None.
check_acronym_exists(acronym)[source]

Returns True if we already have a Company with the given acronym in the database.

is_from_same_company(other_branch)[source]

Receives a branch and checks, using this and the other branch’s cnpj, whether they are from the same company

Parameters:other_branch – an branch
Returns:true if they are from same company, false otherwise
classmethod get_active_remote_branches(store)[source]

Find all active branches excluding the current one

Parameters:store – the store to be used to find the branches
Returns:a sequence of active branches
classmethod get_active_items(store)[source]

Return a list of active items (name, id)

Parameters:store – a store
Returns:the items
class stoqlib.domain.person.SalesPerson(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An employee in charge of making sales

person

reference to: Person

the person

comission

column: PercentCol

The percentege of commission the company must pay for this salesman

comission_type

column: Int

A rule used to calculate the amount of commission. This is a reference to another object

classmethod get_active_salespersons(store)[source]

Get a list of all active salespersons

When the salesperson is also a user in the system, only the users that have access to the current branch will be returned

This will returna list of sales person ready to be used with a combo.prefill method

classmethod get_active_items(store)[source]

Return a list of active items (name, id)

When the salesperson is also a user in the system, only the users that have access to the current branch will be returned

Parameters:store – a store
Returns:the items
class stoqlib.domain.person.Transporter(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An individual or company engaged in the transportation

person

reference to: Person

the person

open_contract_date

column: DateTimeCol

The date when we start working with this transporter

freight_percentage

column: PercentCol

The percentage amount of freight charged by this transporter

classmethod get_active_transporters(store)[source]

Get a list of all available transporters

classmethod get_active_items(store)[source]

Return a list of active items (name, id)

Parameters:store – a store
Returns:the items
class stoqlib.domain.person.EmployeeRoleHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Base class to store the employee role history.

class stoqlib.domain.person.ClientSalaryHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A class to keep track of all the salaries a client has had

date

column: DateTimeCol

date when salary has been updated

new_salary

column: PriceCol

value of the updated salary

old_salary

column: PriceCol

value of the previous salary

client

reference to: Client

the client whose salary is being stored

user

reference to: LoginUser

the login user who updated the salary

class stoqlib.domain.person.UserBranchAccess(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class associates a login user to a branch.

Users will only be able to login into Stoq if it is associated with the computer’s branch.

user

reference to: LoginUser

the login user

branch

reference to: Branch

the branch

classmethod has_access(store, user, branch)[source]

Checks if the given user has access to the given branch

class stoqlib.domain.person.ClientView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about clients.

Available fields are: :attribute id: id of the client table :attribute name: client name :attribute status: client financial status :attribute cpf: brazil-specific cpf attribute :attribute rg: brazil-specific rg_number attribute :attribute phone_number: client phone_number :attribute mobile_number: client mobile_number

client

alias of Client

person

alias of Person

category

alias of ClientCategory

classmethod get_active_clients(store)[source]

Return a list of active clients. An active client is a person who are authorized to make new sales

class stoqlib.domain.person.TransporterView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about transporters

Variables:
transporter

alias of Transporter

class stoqlib.domain.person.UserView[source]

Bases: stoqlib.database.viewable.Viewable

Retrieves information about user in the system.

Variables:
  • id – the id of user table
  • name – the user full name
  • is_active – the current status of the transporter
  • username – the username (login)
  • person_id – the id of person table
  • profile_id – the id of the user profile
  • profile_name – the name of the user profile (eg: Salesperson)
user

alias of LoginUser

class stoqlib.domain.person.CreditCheckHistoryView[source]

Bases: stoqlib.database.viewable.Viewable

A view that displays client credit history

check_history

alias of CreditCheckHistory

class stoqlib.domain.person.CallsView[source]

Bases: stoqlib.database.viewable.Viewable

Store information about the realized calls to client.

call

alias of Calls

person

alias of Person

class stoqlib.domain.person.ClientSalaryHistoryView[source]

Bases: stoqlib.database.viewable.Viewable

Store information about a client’s salary history

class stoqlib.domain.person.ClientsWithCreditView[source]

Bases: stoqlib.database.viewable.Viewable

A view that displays client with credit

plugin

class stoqlib.domain.plugin.InstalledPlugin(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This object represent an installed and activated plugin.

Variables:
  • plugin_name – name of the plugin
  • plugin_version – version of the plugin, if the version is None, it means that the plugin still need to be enabled later.
classmethod get_plugin_names(store)[source]

Fetchs a list of installed plugin names :param store: a store :returns: list of strings

classmethod create(store, plugin_name)[source]

Add a valid InstalledPlugin into the database

This method sets plugin_version to 0 if a there is a Pre-Installed Plugin on the database, or creates a InstalledPlugin with plugin_version set to 0 if None is available.

classmethod get_pre_plugin_names(store)[source]

Returns a list of pre enabled plugin names :param store: a store :returns: names of the pre enabled plugins

class stoqlib.domain.plugin.PluginEgg(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A cache for plugins eggs

product

Product, a physical goods that can be purchased, stored and sold. It’s purchased by a supplier and sold to client.

Imports that will be used in this doctest:

>>> from stoqlib.database.runtime import new_store, get_current_branch
>>> from stoqlib.domain.product import Product, ProductStockItem, Storable
>>> from stoqlib.domain.product import StockTransactionHistory

Create a new store

>>> store = new_store()

Create a branch we can use:

>>> from stoqlib.domain.exampledata import ExampleCreator
>>> branch = ExampleCreator.create(store, 'Branch')

Create a sellable we can use:

>>> from stoqlib.domain.exampledata import ExampleCreator
>>> sellable = ExampleCreator.create(store, 'Sellable')

The ExampleCreator already creates a Product for us. Now lets attach it a storable facet.

>>> product = sellable.product
>>> storable = Storable(product=product, store=store)

The storable needs to have it’s stock created, let’s do so. Note that a reason is always required when changing the stock quantity

>>> storable.increase_stock(10, branch, StockTransactionHistory.TYPE_INITIAL, None)

A stock item should now be available for the storable:

>>> stock_item = storable.get_stock_item(branch, batch=None)

The branch and storable should be set properly

>>> stock_item.branch == branch
True
>>> stock_item.storable == storable
True

Fetch the stock item for the current branch and verify that the stock_items are unique:

>>> current_branch = get_current_branch(store)
>>> stock_item2 = storable.get_stock_item(current_branch, batch=None)
>>> stock_item != stock_item2
True
>>> store.close()
class stoqlib.domain.product.ProductSupplierInfo(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Supplier information for a product.

Each product can has more than one supplier.

See also: schema

base_cost

column: PriceCol

the cost which helps the purchaser to define the main cost of a certain product. Each product can have multiple suppliers and for each supplier a base_cost is available. The purchaser in this case must decide how to define the main cost based in the base cost avarage of all suppliers.

is_main_supplier

column: Bool

if this object stores information for the main supplier.

lead_time

column: Int

the number of days needed to deliver the product to purchaser.

minimum_purchase

column: QuantityCol

the minimum amount that we can buy from this supplier.

icms

column: PercentCol

a Brazil-specific attribute that means ‘Imposto sobre circulacao de mercadorias e prestacao de servicos’

supplier

reference to: Supplier

the supplier

product

reference to: Product

the product

supplier_code

column: Unicode

the product code in the supplier

class stoqlib.domain.product.Product(**kwargs)[source]

Bases: stoqlib.domain.base.Domain

A Product is a thing that can be:

A manufactured product can have several components, which are parts that when combined create the product.

A consigned product is borrowed from a supplier. You can also loan out your own products via loan.

If the product does not use stock managment, it will be possible to sell items, even if it was never purchased.

See also: schema

sellable

reference to: Sellable

sellable for this product

consignment

column: Bool

if this product is loaned from the supplier

is_composed

column: Bool

True if this product has components. This is stored on Product to avoid a join to find out if there is any components or not.

is_grid

column: Bool

True if this product is parent of another product. This is also an indication that this product will have other products “attached” to itself

parent_id

column: UUIDCol

id of his parent

parent

reference to: Product

Indicates the parent of this product.

manage_stock

column: Bool

If this product will use stock management. When this is set to True, a corresponding storable should be created. For False a storable will not be created and the quantity currently in stock will not be known, e.g. |purchases| will not increase the stock

location

column: Unicode

physical location of this product, like a drawer or shelf number

manufacturer

reference to: ProductManufacturer

name of the manufacturer for this product, eg “General Motors”

brand

column: Unicode

name of the brand, eg “Chevrolet” or “Opel”

family

column: Unicode

name of the family, eg “Cobalt” or “Astra”

model

column: Unicode

name of the model, eg “2.2 L Ecotec L61 I4” or “2.0 8V/ CD 2.0 Hatchback 5p Aut”

part_number

column: Unicode

a number representing this part

width

column: Decimal

physical width of this product, unit not enforced

height

column: Decimal

physical height of this product, unit not enforced

depth

column: Decimal

depth in this product, unit not enforced

weight

column: Decimal

physical weight of this product, unit not enforced

production_time

column: Int

The time in days it takes to manufacter this product

ncm

column: Unicode

Brazil specific: NFE: nomenclature comon do mercuosol

ex_tipi

column: Unicode

NFE: see ncm

genero

column: Unicode

NFE: see ncm

icms_template_id

column: UUIDCol

Id of ICMS tax in product tax template

icms_template

reference to: ProductIcmsTemplate

the stoqlib.domain.taxes.ProductIcmsTemplate tax for self

ipi_template_id

column: UUIDCol

Id of IPI tax in product tax template

ipi_template

reference to: ProductIpiTemplate

the stoqlib.domain.taxes.ProductIpiTemplate tax for self

pis_template_id

column: UUIDCol

Id of PIS tax in product tax template

pis_template

reference to: ProductPisTemplate

the stoqlib.domain.taxes.ProductPisTemplate tax for self

cofins_template_id

column: UUIDCol

Id of COFINS tax in product tax template

cofins_template

reference to: ProductCofinsTemplate

the stoqlib.domain.taxes.ProductCofinsTemplate tax for self

quality_tests

Used for composed products only

suppliers

list of suppliers that sells this product

children

list of product that is child of this product

attributes

list of |product_attribute| of this product

grid_options

list of |grid_option| of this product

storable

reference to: Storable

the storable for this product

internal_use

column: Bool

This indicaters if this product is only used internally by the store. This means this product can be bought but cannot be sold

is_package

column: Bool

Indicates if the product is a of TYPE_PACKAGE

yield_quantity

column: QuantityCol

If this is a composed product, this indicates how much the production process yields of this product. For instance, certain recipe could yield 2.5Kgs of some food.

set_as_storable_product(quantity=0, branch=None, cost=None)[source]

Change a product without storable to a product with stock control.

Parameters:quantity – The current product quantity in stock.
remove()[source]

Deletes this product from the database.

can_remove_children()[source]

Checks if this product’s children can be removed

can_remove()[source]

Whether we can delete this product and it’s sellable from the database.

False if the product was sold, received or used in a production. True otherwise.

can_close_children()[source]

Checks if this product’s children can be closed

Called by |self| to check if it’s children can be closed or not. A product child can be closed if it doesn’t have any stock left

can_close()[source]

Checks if this product can be closed

Called by sellable to check if it can be closed or not. A product can be closed if it doesn’t have any stock left

close()[source]

Closes the product’s children

get_manufacture_time(quantity, branch)[source]

Returns the estimated time in days to manufacture a product

If the components don’t have enough stock, the estimated time to obtain missing components will also be considered (using the max lead time from the suppliers)

Parameters:
  • quantity
  • branch – the branch
get_max_lead_time(quantity, branch)[source]

Returns the longest lead time for this product.

If this is a composed product, the lead time will be the time to manufacture the product plus the time to obtain all the missing components

If its a regular product this will be the longest lead time for a supplier to deliver the product (considering the worst case).

quantity and branch are used only when the product is composed

get_main_supplier_info()[source]

Gets a list of main suppliers for a Product, the main supplier is the most recently selected supplier.

Returns:main supplier info
Return type:ProductSupplierInfo or None if a product lacks a main suppliers
get_suppliers_info()[source]

Returns a list of suppliers for this product

Returns:a list of suppliers
Return type:list of ProductSupplierInfo
get_product_supplier_info(supplier)[source]

Returns the product information for the specified supplier.

Parameters:supplier – the supplier
Returns:The supplier’s product information
Return type::class:’ProductSupplierInfo’
get_components()[source]

Returns the products which are our components.

Returns:a sequence of components
has_components()[source]

Returns if this product has a component or not.

Returns:True if this product has components, False otherwise.
get_component(sellable)[source]

Returns the ProductComponent of a given sellable

get_production_cost()[source]

Return the production cost of one unit of the product.

Returns:the production cost
update_production_cost(cost=None)[source]

Update the production cost of this product and its parents

This will update the production cost of this product, and of all the products that use this as a component.

Parameters:cost – When provided, the components cost will not be calculated.
is_supplied_by(supplier)[source]

If this product is supplied by the given supplier, returns the object with the supplier information. Returns None otherwise

is_composed_by(product)[source]

Returns if we are composed by a given product or not.

Parameters:product – a possible component of this product
Returns:True if the given product is one of our component or a component of our components, otherwise False.
child_exists(options)[source]

Check if the child already exists

Parameters:options – a list of |grid_option| that the child should match
Returns:True if the child exists, otherwise False
add_grid_child(options)[source]

Create a new product, child of self

Parameters:options – a list of |grid_option| that the child may have
update_children_description()[source]

Update a grid product’s children descriptions.

This method updates all the this product’s children description by appending the parent description with each grid option description.

update_children_info()[source]

Update a grid product’s children informations.

This will update all the children of this product, copying all the sellable attributes except from the description, which is updated by calling the update_children_description method.

copy_product(target=None)[source]

This method copies self to another product.

If the product target is None, a new product is created. The copy is made by copying all the sellable attributes and some of the product attributes.

Parameters:target – The product target for the copy.

returns: a product similar to self.

update_sellable_price()[source]

Update the sellable price

Summarize the |product_component| price to set the package price

class stoqlib.domain.product.GridGroup(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Attributes Group for product grid

description

column: Unicode

group description

is_active

column: Bool

Indicates if grid_group is active

class stoqlib.domain.product.GridAttribute(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Product Attributes for product grid

description

column: Unicode

description of self

is_active

column: Bool

Indicates if grid_group is active

group_id

column: UUIDCol

GridGroup id

has_active_options()[source]

Check if the grid_attribute have active |grid_option|

Returns:True if self is referenced on any |grid_option|,

otherwise False

class stoqlib.domain.product.GridOption(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Attribute options for product grid

description

column: Unicode

description of self

is_active

column: Bool

Indicates if grid_group is active

option_order

column: Int

Order that the option will be shown

attribute_id

column: UUIDCol

Attribute id for that option

can_remove()[source]

Check if we can remove the attribute_option from database

class stoqlib.domain.product.ProductAttribute(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Tells what attributes that product have

product_id

column: UUIDCol

id of the product

attribute_id

column: UUIDCol

id of the attribute

options

a list of |grid_option| of the grid_attribute

class stoqlib.domain.product.ProductOptionMap(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class is used to map attribute and options to the product

class stoqlib.domain.product.ProductManufacturer(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Product manufacturer.

See also: schema

name

column: Unicode

manufacturer’s name

code

column: Unicode

code of the manufacturer

remove()[source]

Remove this registry from the database.

class stoqlib.domain.product.ProductHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Stores product history, such as sold (via sale), received (via receive), transfered (via transfer) and decreased quantities.

See also: schema

Note

We keep a reference to sellable instead of product because we want to display the sellable id in the interface instead of the product id for consistency with interfaces that display both.

branch

reference to: Branch

the branch

sellable

reference to: Sellable

the sellable

classmethod add_sold_item(store, branch, product_sellable_item)[source]

Adds a sale item to the history. product_sale_item is an item that was created during a sale.

Parameters:
classmethod add_received_item(store, branch, receiving_order_item)[source]

Adds a received item, populates the ProductHistory table using a receiving_order_item created during a purchase

Parameters:
  • store – a store
  • branch – the branch
  • receiving_order_item – the item received for purchase
classmethod add_transfered_item(store, branch, transfer_order_item)[source]

Adds a transfered_item, populates the ProductHistory table using a transfered_order_item created during a transfer.

Parameters:
  • store – a store
  • branch – the source branch
  • transfer_order_item – the item transfered from source branch
classmethod add_consumed_item(store, branch, consumed_item)[source]

Adds a consumed_item, populates the ProductHistory table using a production_material item that was used in a production.

Parameters:
  • store – a store
  • branch – the source branch
  • retained_item – a ProductionMaterial instance
classmethod add_produced_item(store, branch, produced_item)[source]

Adds a produced_item, populates the ProductHistory table using a production_item that was produced in a production order.

Parameters:
  • store – a store
  • branch – the source branch
  • retained_item – a ProductionItem instance
classmethod add_lost_item(store, branch, lost_item)[source]

Adds a lost_item, populates the ProductHistory table using a production_item/product_material that was lost in a production order.

Parameters:
  • store – a store
  • branch – the source branch
  • lost_item – a ProductionItem or ProductionMaterial instance
classmethod add_decreased_item(store, branch, item)[source]

Adds a decreased item, populates the ProductHistory table informing how many items wore manually decreased from stock.

Parameters:
  • store – a store
  • branch – the source branch
  • item – a StockDecreaseItem instance
class stoqlib.domain.product.ProductStockItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class that makes a reference to the product stock of a certain branch.

See also: schema

stock_cost

column: PriceCol

the average stock price, will be updated as new stock items are received.

quantity

column: QuantityCol

number of storables in the stock item

branch

reference to: Branch

the branch this stock item belongs to

storable

reference to: Storable

the storable the stock item refers to

batch

reference to: StorableBatch

The batch that the storable is in.

class stoqlib.domain.product.Storable(**kwargs)[source]

Bases: stoqlib.domain.base.Domain

Storable represents the stock of a product.

The actual stock of an item is in ProductStockItem.

See also: schema

product

reference to: Product

the product the stock represents

is_batch

column: Bool

If this storable should have a finer grain control by batches. When this is true, stock for this storable will also require a batch information. This will allow us to control from what batch a sale item came from, and it will also let us know from what purchase this batch came from.

minimum_quantity

column: QuantityCol

minimum quantity of stock items allowed

maximum_quantity

column: QuantityCol

maximum quantity of stock items allowed

classmethod get_initial_stock_data(store, branch)[source]

Get data about storable without a product stock item

This will get all sellables, products and storables that dont have a product stock item on the given branch.

Parameters:
  • store – the store used to query the storables
  • branch – the branch used to check for the stock item existence
Returns:

a result set of sellable, product and storable

increase_stock(quantity, branch, type, object_id, unit_cost=None, batch=None)[source]

When receiving a product, update the stock reference for this new item on a specific branch.

Parameters:
  • quantity – amount to increase
  • branchbranch that stores the stock
  • type – the type of the stock increase. One of the StockTransactionHistory.types
  • object_id – the id of the object responsible for the transaction
  • unit_cost – unit cost of the new stock or None
  • batch – The batch of the storable. Should be not None if self.is_batch is True
decrease_stock(quantity, branch, type, object_id, cost_center=None, batch=None)[source]

When receiving a product, update the stock reference for the sold item this on a specific branch. Returns the stock item that was decreased.

Parameters:
  • quantity – amount to decrease
  • branch – a branch
  • type – the type of the stock increase. One of the StockTransactionHistory.types
  • object_id – the id of the object responsible for the transaction
  • cost_center – the cost center to which this stock decrease is related, if any
  • batch – The batch of the storable. Should be not None if self.is_batch is True
register_initial_stock(quantity, branch, unit_cost, batch_number=None)[source]

Register initial stock, by increasing the amount of this storable, for the given quantity and branch

Parameters:
  • quantity – The inital stock quantity for this storable
  • branch – The branch where the given quantity is avaiable for this storable
  • unit_cost – The unitary cost for the initial stock
  • batch_number – a batch number that will be used to get or create a batch it will be get from the item’s pending quantity. Must be None if the is_batch is False.
update_stock_cost(stock_cost, branch, batch=None)[source]

Update the stock cost

Parameters:
  • stock_cost – The new stock cost
  • branch – The branch where the stock cost will be updated
  • batch – The batch of the storable self.is_batch is True
get_total_balance()[source]

Return the stock balance for the product in all branches

Returns:the amount of stock available in all branches
get_balance_for_branch(branch)[source]

Return the stock balance for the product in a branch. If this storable have batches, the balance for all batches will be returned.

If you want the balance for a specific batch, the

Parameters:branch – the branch to get the stock balance for
Returns:the amount of stock available in the branch
get_stock_items()[source]

Fetches the stock items available for all branches.

Returns:a sequence of stock items
get_stock_item(branch, batch)[source]

Fetches the stock item for the given branch, batch and this storable.

Parameters:
  • branch – the branch to get the stock item for
  • batch – the batch to get the stock item for
Returns:

a stock item

get_available_batches(branch)[source]

Return all batches that have some stock left in the given branch

Parameters:branch – the branch that we are getting the avaiable batches
Returns:all batches available for this storable in the given branch
class stoqlib.domain.product.StorableBatch(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Batch information for storables.

A batch is a colection of products (storable) that were produced at the same time and thus they have some common information, such as expiration date.

This information is useful since sometimes its necessary to make decisions based on the batch like a special promotion for older batches (if it is close to the expiration date, for instance) or if a batch is somehow defective and we need to contact the clients that purchased items from this batch.

batch_number

column: Unicode

The sequence number for this batch. Should be unique for a given storable

create_date

column: DateTimeCol

The date this batch was created

expire_date

column: DateTimeCol

An expiration date, specially for perishable products, like milk and food in general

notes

column: Unicode

Some space for the users to add notes to this batch.

storable

reference to: Storable

The storable that is in this batch

classmethod is_batch_number_available(store, batch_number, exclude_storable=None)[source]

Test if batch_number is available

Useful to find if a batch number is available to be used on a new batch.

If you are increasing the stock of a storable, you probably want to allow an existing batch number for it, in this case, you can use exclude_storable param for that.

Parameters:
  • store – a store
  • batch_number – the batch number to check for availability
  • exclude_storable – if not None, the storable to exclude from the test
get_balance_for_branch(branch)[source]

Return the stock balance for this batch in a branch.

Parameters:branch – the branch to get the stock balance for
Returns:the amount of stock available in the branch
class stoqlib.domain.product.StockTransactionHistory(**kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class stores information about all transactions made in the stock

Everytime a storable has its stock increased or decreased, an object of this class will be created, registering the quantity, cost, responsible and reason for the transaction

TYPE_INITIAL = u'initial'

the transaction is an initial stock adustment. Note that with this transaction, there is no related object.

TYPE_SELL = u'sell'

the transaction is a sale

TYPE_RETURNED_SALE = u'returned-sale'

the transaction is a return of a sale

TYPE_UNDO_RETURNED_SALE = u'undo-returned-sale'

the transaction is an undo of a returned sale

TYPE_CANCELED_SALE = u'cancelled-sale'

the transaction is the cancellation of a sale

TYPE_RECEIVED_PURCHASE = u'received-purchase'

the transaction is the receival of a purchase

TYPE_RETURNED_LOAN = u'returned-loan'

the transaction is the return of a loan

TYPE_LOANED = u'loan'

the transaction is a loan

TYPE_CANCELLED_LOAN = u'cancelled-loan'

the transaction is the cancellation of a loan

TYPE_PRODUCTION_ALLOCATED = u'production-allocated'

the transaction is the allocation of a product to a production

TYPE_PRODUCTION_PRODUCED = u'production-produced'

the transaction is the production of a product

TYPE_PRODUCTION_RETURNED = u'production-returned'

the transaction is the return of an item from a production

TYPE_STOCK_DECREASE = u'stock-decrease'

the transaction is a stock decrease

TYPE_CANCELLED_STOCK_DECREASE = u'cancelled-stock-decrease'

the transaction is the cancellation of a stock decrease

TYPE_TRANSFER_FROM = u'transfer-from'

the transaction is a transfer from a branch

TYPE_TRANSFER_TO = u'transfer-to'

the transaction is a transfer to a branch

TYPE_INVENTORY_ADJUST = u'inventory-adjust'

the transaction is the adjustment of an inventory

TYPE_CANCELLED_INVENTORY_ADJUST = u'cancelled-inventory-adjust'

the transaction is the cancellation of the adjustment of an inventory

TYPE_PRODUCTION_SENT = u'production-sent'

the transaction is the production of a product that didn’t enter stock right after its creation

TYPE_IMPORTED = u'imported'

this transaction was created automatically by an upgrade from a previous version of Stoq, when this history didn’t exist.

TYPE_CONSIGNMENT_RETURNED = u'consignment-returned'

the transaction is the return of a product to another company (ie, this shop is giving the product back to the other company).

TYPE_WORK_ORDER_USED = u'wo-used'

the transaction is the utilization of a product on a work order item

TYPE_WORK_ORDER_RETURN_TO_STOCK = u'wo-returned-to-stock'

the transaction is the return of a product on a work order item to the stock

TYPE_SALE_RESERVED = u'sale-reserved'

the transaction is a reserved product from a sale

TYPE_SALE_RETURN_TO_STOCK = u'sale-return-to-stock'

the transaction is a reserved product from a sale

TYPE_MANUAL_ADJUST = u'manual-adjust'

the transaction is a manual adjust done on the database

TYPE_UPDATE_STOCK_COST = u'update-stock-cost'

the transaction is an adjustment on the stock cost with no update on the stock itself

date

column: DateTimeCol

the date and time the transaction was made

stock_cost

column: PriceCol

the stock cost of the transaction on the time it was made

quantity

column: QuantityCol

The quantity that was removed or added to the stock. Positive value if the value was increased, negative if decreased.

responsible

reference to: LoginUser

the login user responsible for the transaction

object_id

column: UUIDCol

the id of the object who altered the stock

type

column: EnumCol

the type of the transaction

get_description()[source]

Based on the type of the transaction, returns the string description

class stoqlib.domain.product.ProductComponent(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A product and it’s related component eg other product

This maps the relationship between products, indicating what product is a component of another product.

See also: schema

product

reference to: Product

This is the main product, ie, the one that has components.

component

reference to: Product

This is the product that is a component of the product above

design_reference

column: Unicode

A design reference

price

column: PriceCol

The price to be used on |sale_item|. This is only used for package products and indicate the price this component has in the final package

class stoqlib.domain.product.ProductQualityTest(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A quality test that a manufactured product will be submitted to.

See also: schema

class stoqlib.domain.product.StorableBatchView[source]

Bases: stoqlib.database.viewable.Viewable

A view for batches

This is used to get the most information of a batch without doing lots of database queries.

It’s bestly used with find_by_storable()

batch

the batch object

alias of StorableBatch

branch

the branch this batch is in

alias of Branch

classmethod find_by_storable(store, storable, branch=None)[source]

Find results for this view that for storable

Normally it’s best to use this instead of store.find since it’ll only batches for the given storable.

Parameters:
  • store – the store that will be used to find the results
  • storable – the storable used to filter the results
  • branch – a branch that, if not None, will be used to filter the results to only get batches on that branch.
Returns:

the matching views

Return type:

a sequence of StorableBatchView

classmethod find_available_by_storable(store, storable, branch=None)[source]

Find results for this view that for storable that have stock

The same as find_by_storable(), but only results with stock > 0 will be fetched

Parameters:
  • store – the store that will be used to find the results
  • storable – the storable used to filter the results
  • branch – a branch that, if not None, will be used to filter the results to only get batches on that branch.
Returns:

the matching views

Return type:

a sequence of StorableBatchView

production

Base classes to manage production informations

class stoqlib.domain.production.ProductionOrder(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Production Order object implementation.

ORDER_OPENED = u'opened'

The production order is opened, production items might have been added.

ORDER_WAITING = u'waiting'

The production order is waiting some conditions to start the manufacturing process.

ORDER_PRODUCING = u'producing'

The production order have already started.

ORDER_QA = u'quality-assurance'

The production is in quality assurance phase.

ORDER_CLOSED = u'closed'

The production have finished.

ORDER_CANCELLED = u'cancelled'

Production cancelled

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

the production order status

open_date

column: DateTimeCol

the date when the production order was created

close_date

column: DateTimeCol

the date when the production order have been closed

cancel_date

column: DateTimeCol

the date when the production order have been cancelled

description

column: Unicode

the production order description

responsible

reference to: Employee

the person responsible for the production order

branch

reference to: Branch

branch this production belongs to

can_cancel()[source]

Checks if this order can be cancelled

Only orders that didn’t start yet can be canceled, this means only opened and waiting productions.

can_finalize()[source]

Checks if this order can be finalized

Only orders that didn’t start yet can be canceled, this means only producing and waiting qa productions.

get_service_items()[source]

Returns all the services needed by this production.

Returns:a sequence of ProductionService instances.
get_material_items()[source]

Returns all the material needed by this production.

Returns:a sequence of ProductionMaterial instances.
start_production()[source]

Start the production by allocating all the material needed.

cancel()[source]

Cancel the production when this is Open or Waiting.

try_finalize_production(ignore_completion=False)[source]

When all items are completely produced, change the status of the production to CLOSED.

class stoqlib.domain.production.ProductionItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Production Item object implementation.

quantity

column: QuantityCol

The product’s quantity that will be manufactured.

produced

column: QuantityCol

The product’s quantity that was manufactured.

lost

column: QuantityCol

The product’s quantity that was lost.

order

reference to: ProductionOrder

The ProductionOrder of this item.

product

reference to: Product

The product that will be manufactured.

can_produce(quantity)[source]

Returns if we can produce a certain quantity. We can produce a quantity items until we reach the total quantity that will be manufactured minus the quantity that was lost.

Parameters:quantity – the quantity that will be produced.
produce(quantity, produced_by=None, serials=None)[source]

Sets a certain quantity as produced. The quantity will be marked as produced only if there are enough materials allocated, otherwise a ValueError exception will be raised.

Parameters:quantity – the quantity that will be produced.
add_lost(quantity)[source]

Adds a quantity that was lost. The maximum quantity that can be lost is the total quantity minus the quantity already produced.

Parameters:quantity – the quantity that was lost.
class stoqlib.domain.production.ProductionMaterial(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Production Material object implementation.

This represents the material needed by a production. It can either be consumed or lost (due to manufacturing process).

product

reference to: Product

The product that will be consumed.

order

reference to: ProductionOrder

The production that will consume this material.

allocated

column: QuantityCol

The quantity that is actually allocated to this production. It may be more than the quantity required (and in this case, the remaining quantity will be returned to the stock later.

consumed

column: QuantityCol

The quantity already used of this material.

lost

column: QuantityCol

The quantity lost of this material.

to_purchase

column: QuantityCol

The quantity to purchase of this material.

to_make

column: QuantityCol

The quantity to manufacture of this material.

can_add_lost(quantity)[source]

Returns if we can loose a certain quantity of this material.

Parameters:quantity – the quantity that will be lost.
allocate(quantity=None)[source]

Allocates the needed quantity of this material by decreasing the stock quantity. If no quantity was specified, it will decrease all the stock needed or the maximum quantity available. Otherwise, allocate the quantity specified or raise a ValueError exception, if the quantity is not available.

Parameters:quantity – the quantity to be allocated or None to allocate the maximum quantity possible.
return_remaining()[source]

Returns remaining allocated material to the stock

This should be called only after the production order is closed.

add_lost(quantity)[source]

Adds the quantity lost of this material. The maximum quantity that can be lost is given by the formula:

- max_lost(quantity) = needed - consumed - lost - quantity
Parameters:quantity – the quantity that was lost.
consume(quantity)[source]

Consumes a certain quantity of material. The maximum quantity allowed to be consumed is given by the following formula:

  • max_consumed(quantity) = needed - consumed - lost - quantity
Parameters:quantity – the quantity to be consumed.
class stoqlib.domain.production.ProductionService(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Production Service object implementation.

service

reference to: Service

The service that will be used by the production.

order

reference to: ProductionOrder

The ProductionOrder of this service.

quantity

column: QuantityCol

The service’s quantity.

class stoqlib.domain.production.ProductionProducedItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class represents a composed product that was produced, but didn’t enter the stock yet. Its used mainly for the quality assurance process

check_tests()[source]

Checks if all tests for this produced items passes.

If all tests passes, sets self.test_passed = True

class stoqlib.domain.production.ProductionItemQualityResult(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This table stores the test results for every produced item.

profile

User profile management for applications

class stoqlib.domain.profile.ProfileSettings(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Profile settings for user profile instances. Each instance of this class stores information about the access availability in a certain application.

user_profile_id

column: UUIDCol

The user profile that has these settings.

app_dir_name

column: Unicode

The app name this user has or does not have access to.

has_permission

column: Bool

Has this user permission to use this app?

virtual_apps = {'link': ['admin']}

Virtual apps. They will have permission if one of the apps mapped on the list have permission

classmethod get_permission(store, profile, app)[source]

Check if a profile has access to an app

Parameters:
  • store – A store
  • profile – The UserProfile to check for permission
  • app – The name of the application
Returns:

Whether the profile has access to the profile or not

classmethod set_permission(store, profile, app, permission)[source]

Set the permission for a user profile to use a application :param store: a store :param profile: a UserProfile :param app: name of the application :param permission: a boolean of the permission

class stoqlib.domain.profile.UserProfile(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

User profile definition.

name

column: Unicode

Name of the user profile.

profile_settings

Profile settings that describes the access this profile has to an app.

max_discount

column: PercentCol

Maximum discount this profile can allow to sale items.

check_app_permission(app_name)[source]

Check if the user has permission to use an application :param app_name: name of application to check

stoqlib.domain.profile.update_profile_applications(store, profile=None)[source]

This method checks for all available applications and perform a comparision with the application names stored in user profiles. If a certain application is not there it is added.

purchase

Purchase management

class stoqlib.domain.purchase.PurchaseItem(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

This class stores information of the purchased items.

base_cost

column: PriceCol

the cost which helps the purchaser to define the main cost of a certain product.

sellable

reference to: Sellable

the sellable

order

reference to: PurchaseOrder

the purchase

classmethod get_ordered_quantity(store, sellable)[source]

Returns the quantity already ordered of a given sellable.

Parameters:
  • store – a store
  • sellable – the sellable we want to know the quantity ordered.
Returns:

the quantity already ordered of a given sellable or zero if no quantity have been ordered.

return_consignment(quantity)[source]

Return this as a consignment item

Parameters:quantity – the quantity to return
get_component_quantity(parent)[source]

Get the quantity of a component.

Parameters:parent – the |purchase_item| parent_item of self
Returns:the quantity of the component
class stoqlib.domain.purchase.PurchaseOrder(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Purchase and order definition.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

get_items(with_children=True)[source]

Get the items of the purchase order

Parameters:with_children – indicate if we should fetch children_items or not
add_item(sellable, quantity=Decimal('1'), parent=None, cost=None)[source]

Add a sellable to this purchase.

If the sellable is part of a package (parent is not None), then the actual cost and quantity will be calculated based on how many items of this component is on the package.

Parameters:
  • sellable – the sellable being added
  • quantity – How many units of this sellable we are adding
  • cost – The price being paid for this sellable
  • parent – The parent of this sellable, incase of a package
discount_percentage

Discount by percentage. Note that percentage must be added as an absolute value not as a factor like 1.05 = 5 % of surcharge The correct form is ‘percentage = 3’ for a discount of 3 %

surcharge_percentage

Surcharge by percentage. Note that surcharge must be added as an absolute value not as a factor like 0.97 = 3 % of discount. The correct form is ‘percentage = 3’ for a surcharge of 3 %

payments

Returns all valid payments for this purchase

This will return a list of valid payments for this purchase, that is, all payments on the payment group that were not cancelled. If you need to get the cancelled too, use self.group.payments.

Returns:a list of payment
can_cancel()[source]

Find out if it’s possible to cancel the order

Returns:True if it’s possible to cancel the order, otherwise False
can_close()[source]

Find out if it’s possible to close the order

Returns:True if it’s possible to close the order, otherwise False
confirm(confirm_date=None)[source]

Confirms the purchase order

Parameters:confirm_data – optional, datetime
close()[source]

Closes the purchase order

cancel()[source]

Cancels the purchase order

update_products_cost()[source]

Update purchase’s items cost

Update the costs of all products on this purchase to the costs specified in the order.

purchase_subtotal

Get the subtotal of the purchase. The sum of all the items cost * items quantity

received_total

Like {purchase_subtotal} but only takes into account the received items

get_remaining_total()[source]

The total value to be paid for the items not received yet

get_pending_items(with_children=True)[source]

Returns a sequence of all items which we haven’t received yet.

get_partially_received_items()[source]

Returns a sequence of all items which are partially received.

get_receiving_orders()[source]

Returns all ReceivingOrder related to this purchase order

get_data_for_labels()[source]

This function returns some necessary data to print the purchase’s items labels

has_batch_item()[source]

Fetch the storables from this purchase order and returns True if any of them is a batch storable.

Returns:True if this purchase order has batch items, False if

it doesn’t.

class stoqlib.domain.purchase.PurchaseItemView[source]

Bases: stoqlib.database.viewable.Viewable

This is a view which you can use to fetch purchase items within a specific purchase. It’s used by the PurchaseDetails dialog to display all the purchase items within a purchase

Parameters:
  • id – id of the purchase item
  • purchase_id – id of the purchase order the item belongs to
  • sellable – sellable of the item
  • cost – cost of the item
  • quantity – quantity ordered
  • quantity_received – quantity received
  • total – total value of the items purchased
  • total_received – total value of the items received
  • description – description of the sellable
  • unit – unit as a string or None if the product has no unit
purchase_item

alias of PurchaseItem

class stoqlib.domain.purchase.PurchaseOrderView[source]

Bases: stoqlib.database.viewable.Viewable

General information about purchase orders

Variables:
  • id – the id of purchase_order table
  • status – the purchase order status
  • open_date – the date when the order was started
  • quote_deadline – the date when the quotation expires
  • expected_receival_date – expected date to receive products
  • expected_pay_date – expected date to pay the products
  • receival_date – the date when the products were received
  • confirm_date – the date when the order was confirmed
  • salesperson_name – the name of supplier’s salesperson
  • expected_freight – the expected freight value
  • surcharge_value – the surcharge value for the order total
  • discount_value – the discount_value for the order total
  • supplier_name – the supplier name
  • transporter_name – the transporter name
  • branch_name – the branch company name
  • ordered_quantity – the total quantity ordered
  • received_quantity – the total quantity received
  • subtotal – the order subtotal (sum of product values)
  • total – subtotal - discount_value + surcharge_value
purchase

alias of PurchaseOrder

branch

alias of Branch

receiving

Receiving management

class stoqlib.domain.receiving.ReceivingOrderItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class stores information of the purchased items.

Note that objects of this type should not be created manually, only by calling Receiving

quantity

column: QuantityCol

the total quantity received for a certain product

cost

column: PriceCol

the cost for each product received

sellable

reference to: Sellable

the sellable

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was received in

get_remaining_quantity()[source]

Get the remaining quantity from the purchase order this item is included in. :returns: the remaining quantity

add_stock_items()[source]

This is normally called from ReceivingOrder when a the receving order is confirmed.

class stoqlib.domain.receiving.ReceivingOrder(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

Receiving order definition.

STATUS_PENDING = u'pending'

Products in the order was not received or received partially.

STATUS_CLOSED = u'closed'

All products in the order has been received then the order is closed.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status of the order

receival_date

column: DateTimeCol

Date that order has been closed.

confirm_date

column: DateTimeCol

Date that order was send to Stock application.

notes

column: Unicode

Some optional additional information related to this order.

freight_type

column: EnumCol

Type of freight

freight_total

column: PriceCol

Total of freight paid in receiving order.

discount_value

column: PriceCol

Discount value in receiving order’s payment.

secure_value

column: PriceCol

Secure value paid in receiving order’s payment.

expense_value

column: PriceCol

Other expenditures paid in receiving order’s payment.

invoice_number

column: Int

The number of the order that has been received.

add_purchase_item(item, quantity=None, batch_number=None, parent_item=None)[source]

Add a purchase item on this receiving order

Parameters:
  • item – the purchase item
  • quantity (decimal.Decimal) – the quantity of that item. If None, it will be get from the item’s pending quantity
  • batch_number – a batch number that will be used to get or create a batch it will be get from the item’s pending quantity or None if the item’s storable is not controlling batches.
Raises:

ValueError when validating the quantity and testing the item’s order for equality with order

update_payments(create_freight_payment=False)[source]

Updates the payment value of all payments realated to this receiving. If create_freight_payment is set, a new payment will be created with the freight value. The other value as the surcharges and discounts will be included in the installments.

Parameters:create_freight_payment – True if we should create a new payment with the freight value, False otherwise.
total_surcharges

Returns the sum of all surcharges (purchase & receiving)

total_discounts

Returns the sum of all discounts (purchase & receiving)

total

Fetch the total, including discount and surcharge for both the purchase order and the receiving order.

guess_freight_type()[source]

Returns a freight_type based on the purchase’s freight_type

surcharge_percentage

Surcharge by percentage. Note that surcharge must be added as an absolute value not as a factor like 0.97 = 3 % of discount. The correct form is ‘percentage = 3’ for a surcharge of 3 %

class stoqlib.domain.receiving.PurchaseReceivingMap(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This class stores a map for purchase and receivings.

One purchase may be received more than once, for instance, if it was shippped in more than one package.

Also, a receiving may be for different purchase orders, if more than one purchase order was shipped in the same package.

purchase

reference to: PurchaseOrder

The purchase that was recieved

receiving

reference to: ReceivingOrder

In which receiving the purchase was received.

returnedsale

class stoqlib.domain.returnedsale.ReturnedSaleItem(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An item of a returned sale

Note that objects of this type should never be created manually, only by calling Sale.create_sale_return_adapter()

quantity

column: QuantityCol

the returned quantity

price

column: PriceCol

The price which this sale_item was sold. When creating this object, if price is not passed to the contructor, it defaults to sale_item.price or sellable.price

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was removed from

returned_sale

reference to: ReturnedSale

the returned sale which this item belongs

icms_info_id

column: UUIDCol

Id of ICMS tax in product tax template

icms_info

reference to: InvoiceItemIcms

the stoqlib.domain.taxes.InvoiceItemIcms tax for self

ipi_info_id

column: UUIDCol

Id of IPI tax in product tax template

ipi_info

reference to: InvoiceItemIpi

the stoqlib.domain.taxes.InvoiceItemIpi tax fo self

pis_info_id

column: UUIDCol

Id of PIS tax in product tax template

pis_info

reference to: InvoiceItemPis

the stoqlib.domain.taxes.InvoiceItemPis tax fo self

cofins_info_id

column: UUIDCol

Id of COFINS tax in product tax template

cofins_info

reference to: InvoiceItemCofins

the stoqlib.domain.taxes.InvoiceItemCofins tax fo self

sale_item

reference to: SaleItem

the returned sale item

sellable

reference to: Sellable

The returned sellable Note that if sale_item != None, this is the same as sale_item.sellable

total

The total being returned

This is the same as price * quantity

return_(branch)[source]

Do the real return of this item

When calling this, the real return will happen, that is, if sellable is a product, it’s stock will be increased on branch.

undo()[source]

Undo this item return.

This is the oposite of the return, ie, the item will be removed back from stock and the sale item decreased quantity will be restored.

maybe_remove()[source]

Will eventualy remove the object from database

can_remove()[source]

Check if the ReturnedSaleItem can be removed from database

If the item is a package, check if all of its children are being returned

class stoqlib.domain.returnedsale.ReturnedSale(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Holds information about a returned sale.

This can be:
  • trade, a client is returning the sale and buying something new with that credit. In that case the returning sale is sale and the replacement sale is in new_sale.
  • return sale or devolution, a client is returning the sale without making a new sale.

Normally the old sale which is returned is sale, however it might be None in some situations for example, if the sale was done at a different branch that hasn’t been synchronized or is using another system.

STATUS_PENDING = u'pending'

This returned sale was received on another branch, but is not yet confirmed. A product goes back to stock only after confirmation

STATUS_CONFIRMED = u'confirmed'

This return was confirmed, meaning the product stock was increased.

STATUS_CANCELLED = 'cancelled'

This returned sale was canceled, ie, The product stock is decreased back and the original sale still have the products.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

Status of the returned sale

return_date

column: DateTimeCol

the date this return was done

confirm_date

column: DateTimeCol

the date that the |returned sale| with the status pending was received

reason

column: Unicode

the reason why this return was made

undo_reason

column: Unicode

The reason this returned sale was undone

sale

reference to: Sale

the sale we’re returning

new_sale

reference to: Sale

if not None, sale was traded for this sale

responsible

reference to: LoginUser

the login user responsible for doing this return

confirm_responsible

reference to: LoginUser

the login user responsible for receiving the pending return

undo_responsible

reference to: LoginUser

the login user responsible for undoing this returned sale.

branch

reference to: Branch

the branch in which this return happened

returned_items

a list of all items returned in this return

payments = None

payments generated by this returned sale

transporter = None

transporter used in returned sale

invoice

reference to: Invoice

The |invoice| generated by the returned sale

group

payment group for this return sale.

Can return:
client

The client of this return

Note that this is the same as sale.client

sale_total

The current total amount of the sale.

This is calculated by getting the total amount of the returned sale and subtracting the sum of returned_total of all existing returns for the same sale.

paid_total

The total paid for this sale

Note that this is the same as stoqlib.domain.sale.Sale.get_total_paid()

returned_total

The total being returned on this return

This is done by summing the ReturnedSaleItem.total of all of this returned items

total_amount

The total amount for this return

See return_() for details of how this is used.

total_amount_abs

The absolute total amount for this return

This is the same as abs(total_amount). Useful for displaying it on a gui, just changing it’s label to show if it’s ‘overpaid’ or ‘missing’.

classmethod get_pending_returned_sales(store, branch)[source]

Returns a list of pending |returned_sale|

Parameters:
  • store – a store
  • branch – the branch where the sale was made
return_(method_name=u'money', login_user=None)[source]

Do the return of this returned sale.

Parameters:method_name (unicode) – The name of the payment method that will be used to create this payment.
If total_amount is:
  • > 0, the client is returning more than it paid, we will create a payment with that value so the client can be reversed.
  • == 0, the client is returning the same amount that needs to be paid, so existing payments will be cancelled and the client doesn’t owe anything to us.
  • < 0, than the payments need to be readjusted before calling this.
trade()[source]

Do a trade for this return

Almost the same as return_(), but unlike it, this won’t generate reversed payments to the client. Instead, it’ll generate an inpayment using returned_total value, so it can be used as an “already paid quantity” on new_sale.

remove()[source]

Remove this return and it’s items from the database

confirm(login_user)[source]

Receive the returned_sale_items from a pending |returned_sale|

Parameters:user – the |login_user| that received the pending returned sale
undo(reason)[source]

Undo this returned sale.

This includes removing the returned items from stock again (updating the quantity decreased on the sale).

Parameters:reason – The reason for this operation.

sale

Domain objects related to the sale process in Stoq.

Sale object and related objects implementation

class stoqlib.domain.sale.SaleItem(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

An item of a sellable within a sale.

Different from sellable which contains information about the base price, tax, etc, this contains the price in which self was sold, it’s taxes, the quantity, etc.

Note that objects of this type should never be created manually, only by calling Sale.add_sellable()

See also: schema

quantity

column: QuantityCol

the quantity of the of sold item in this sale

quantity_decreased

column: QuantityCol

the quantity already decreased from stock.

average_cost

column: PriceCol

averiage cost of the items in this item

price

column: PriceCol

price of this item

sale

reference to: Sale

sale for this item

sellable

reference to: Sellable

sellable for this item

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was removed from

delivery

reference to: Delivery

The delivery this sale_item is in or None

delivery_adaptor

reference to: Delivery

The delivery that this item corresponds to. Ie, this sale_item’s sellable is the Delivery service that was added to the sale.

cfop

reference to: CfopData

fiscal entry

notes

column: Unicode

user defined notes, currently only used by services

estimated_fix_date

column: DateTimeCol

estimated date that self will be fixed, currently only used by services

icms_info_id

column: UUIDCol

Id of ICMS tax in product tax template

icms_info

reference to: InvoiceItemIcms

the stoqlib.domain.taxes.InvoiceItemIcms tax for self

ipi_info_id

column: UUIDCol

Id of IPI tax in product tax template

ipi_info

reference to: InvoiceItemIpi

the stoqlib.domain.taxes.InvoiceItemIpi tax for self

pis_info_id

column: UUIDCol

Id of PIS tax in product tax template

pis_info

reference to: InvoiceItemPis

the stoqlib.domain.taxes.InvoiceItemPis tax for self

cofins_info_id

column: UUIDCol

Id of COFINS tax in product tax template

cofins_info

reference to: InvoiceItemCofins

the stoqlib.domain.taxes.InvoiceItemCofins tax for self

parent_item_id

column: UUIDCol

Id of |sale_item| parent of self

children_items

A list of children of self

base_price

column: PriceCol

original value the sellable had when adding the sale item

sale_discount
The discount percentage (relative to the original price
when the item was sold)
Returns:the discount amount
price_with_discount

Applies the sale discount to this item.

This will apply the discount given in the sale proportionally to this item.

This value should be used when returning or trading this item, since the user should not receive more than what he paid for.

Please note that this may result in rounding problems, since precision may be lost when appling the discount in the items.

Returns:price with discount/surcharge
cfop_code

Returns the cfop code to be used on the NF-e

If the sale was also printed on a ECF, then the cfop should be:
  • 5.929: if sold to a client in the same state or
Returns:the cfop code
reserve(quantity)[source]

Reserve some quantity of this this item from stock

This will remove the informed quantity from the stock.

return_to_stock(quantity)[source]

Return some reserved quantity to stock

This will return a previously reserved quantity to stock, so that it can be sold in any other sale.

set_batches(batches)[source]

Set batches for this sale item

Set how much quantity of each batch this sale item represents. Note that this will replicate this item and create others, since the batch reference is one per sale item.

At the end, this sale item will contain the quantity not used by any batch yet or, if the sum of quantities on batches are equal to quantity, it will be used for one of the batches

Parameters:batches – a dict mapping the batch to it’s quantity
Returns:a list of the new created items
Raises:ValueError if this item already has a batch
Raises:ValueError if the sum of the batches quantities is greater than this item’s original quantity
set_discount(discount)[source]

Apply discount on this item

Note that the discount will be applied based on base_price and then substitute price, making any previous discount/surcharge being lost

Parameters:discount (decimal.Decimal) – the discount to be applied as a percentage, e.g. 10.0, 22.5
is_totally_returned()[source]

If this sale item was totally returned

Returns:True if it was totally returned, False otherwise.
is_service()[source]

If this sale item contains a service.

Returns:True if it’s a service
get_sale_surcharge()[source]
The surcharge percentage (relative to the original price
when the item was sold)
Returns:the surcharge amount
get_component(parent)[source]

Get the quantity of a component.

Parameters:parent – the |sale_item| parent_item of self
Returns:the |product_component|
class stoqlib.domain.sale.Delivery(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Delivery, transporting a set of sale items for sale.

Involves a transporter transporting a set of sale items to a receival address.

Optionally a tracking_code can be set to track the items.

See also: schema

STATUS_INITIAL = u'initial'

The delivery was created and is waiting to be picked

STATUS_CANCELLED = u'cancelled'

The delivery was cancelled

STATUS_PICKED = u'picked'

The delivery was picked and is waiting to be packed

STATUS_PACKED = u'packed'

The delivery was packed and is waiting to be packed

STATUS_SENT = u'sent'

sent to deliver

STATUS_RECEIVED = u'received'

received by the client

FREIGHT_TYPE_CIF = u'cif'

CIF (Cost, Insurance and Freight): The freight is responsibility of the receiver (i.e. the client)

FREIGHT_TYPE_FOB = u'fob'

CIF (Free on Board): The freight is responsibility of the sender (i.e. the branch)

FREIGHT_TYPE_3RDPARTY = u'3rdparty'

3rd party: The freight is responsibility of a third party

FREIGHT_TYPE_NONE = None

No freight: There’s no freight

status

column: EnumCol

the delivery status

open_date

column: DateTimeCol

the date which the delivery was created

cancel_date

column: DateTimeCol

The date that the delivery was cancelled

pick_date

column: DateTimeCol

The date that the delivery was picked

pack_date

column: DateTimeCol

The date that the delivery was packed

send_date

column: DateTimeCol

the date which the delivery sent to deliver

receive_date

column: DateTimeCol

the date which the delivery received by the client

tracking_code

column: Unicode

the delivery tracking code, a transporter specific identifier that can be used to look up the status of the delivery

freight_type

column: EnumCol

The type of the freight

volumes_kind

column: Unicode

The kind of the volumes

volumes_quantity

column: Int

The quantity of volumes in this freight

address

reference to: Address

the address to deliver to

transporter

reference to: Transporter

the transporter for this delivery

service_item

reference to: SaleItem

the sale item for the delivery itself

delivery_items

the sale items for the items to deliver

cancel_responsible

reference to: LoginUser

The responsible for cancelling the products for delivery

pick_responsible

reference to: LoginUser

The responsible for picking the products for delivery

pack_responsible

reference to: LoginUser

The responsible for packing the products for delivery

send_responsible

reference to: LoginUser

The responsible for delivering the products to the transporter

can_cancel()[source]

Check if we can cancel the delivery.

Only initial, picked or packed deliveries can be cancelled.

can_pick()[source]

Check if we can pick the delivery.

Only initial deliveries can be picked.

can_pack()[source]

Check if we can pack the delivery.

Only picked deliveries can be packed.

can_send()[source]

Check if we can send the delivery.

Only packed deliveries can be sent.

can_receive()[source]

Check if we can receive the delivery.

Only sent deliveries can be received.

set_initial()[source]

Set the delivery in its initial state.

cancel(responsible)[source]

Set the delivery as cancelled.

pick(responsible)[source]

Set the delivery as picked.

pack(responsible)[source]

Set the delivery as packed.

send(responsible)[source]

Set the delivery as sent.

receive()[source]

Set the delivery as received.

class stoqlib.domain.sale.Sale(store=None, **kw)[source]

Bases: stoqlib.domain.base.Domain

Sale logic, the process of selling a sellable to a client.

  • calculates the sale price including discount/interest/markup
  • creates payments
  • decreases the stock for products
  • creates a delivery (optional)
  • verifies that the client is suitable
  • creates commissions to the sales person
  • add money to the till (if paid with money)
  • calculate taxes and fiscal book entries
Status Can be set to
STATUS_QUOTE STATUS_INITIAL
STATUS_INITIAL STATUS_ORDERED,
STATUS_ORDERED STATUS_CONFIRMED STATUS_CANCELLED
STATUS_CONFIRMED STATUS_RENEGOTIATED
STATUS_CANCELLED None
STATUS_RENEGOTIATED None
STATUS_RETURNED None

digraph sale_status {
  STATUS_QUOTE -> STATUS_INITIAL;
  STATUS_INITIAL -> STATUS_ORDERED;
  STATUS_ORDERED -> STATUS_CONFIRMED;
  STATUS_ORDERED -> STATUS_CANCELLED;
  STATUS_CONFIRMED -> STATUS_CANCELLED;
  STATUS_CONFIRMED -> STATUS_RENEGOTIATED;
}

See also: schema

STATUS_INITIAL = u'initial'

The sale is opened, products or other sellable items might have been added.

STATUS_QUOTE = u'quote'

When asking for sale quote this is the initial state that is set before reaching the initial state

STATUS_ORDERED = u'ordered'

This state means the order was left the quoting state, but cant just yet go to the confirmed state. This may happen for various reasons, like when there is not enough stock to confirm the sale; when the sale has pending work orders; or when the confirmation should happen on the till app (because of the CONFIRM_SALES_AT_TILL parameter)

STATUS_CONFIRMED = u'confirmed'

The sale has been confirmed and all payments have been registered, but not necessarily paid.

STATUS_CANCELLED = u'cancelled'

The sale has been canceled, this can only happen to an sale which has not yet reached the SALE_CONFIRMED status.

STATUS_RETURNED = u'returned'

The sale has been returned, all the payments made have been canceled and the client has been compensated for everything already paid.

STATUS_RENEGOTIATED = u'renegotiated'

A sale that is closed as renegotiated, all payments for this sale should be canceled at list point. Another new sale is created with the new, renegotiated payments.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status of the sale

coupon_id

column: Int

identifier for the coupon of this sale, used by a ECF printer

open_date

column: DateTimeCol

the date sale was created, this is always set

confirm_date

column: DateTimeCol

the date sale was confirmed, or None if it hasn’t been confirmed

close_date

column: DateTimeCol

the date sale was paid, or None if it hasn’t be paid

cancel_date

column: DateTimeCol

the date sale was confirmed, or None if it hasn’t been cancelled

return_date

column: DateTimeCol

the date sale was confirmed, or None if it hasn’t been returned

expire_date

column: DateTimeCol

date when this sale expires, used by quotes

paid

column: Bool

This flag indicates if the sale its completely paid and received

discount_value

column: PriceCol

discount of the sale, in absolute value, for instance:

sale.total_sale_amount = 150
sale.discount_value = 18
# the price of the sale will now be 132
surcharge_value

column: PriceCol

surcharge of the sale, in absolute value, for instance:

sale.total_sale_amount = 150
sale.surcharge_value = 18
# the price of the sale will now be 168
total_amount

column: PriceCol

the total value of all the items in the same, this is set when a sale is confirmed, this is the same as calling Sale.get_total_sale_amount() at the time of confirming the sale,

cancel_reason

column: Unicode

The reason the sale was cancelled

client

reference to: Client

the client who this sale was sold to

salesperson

reference to: SalesPerson

the salesperson who sold the sale

transporter

reference to: Transporter

If we have a delivery, this is the transporter for this sale

group

reference to: PaymentGroup

the payment group of this sale

client_category

reference to: ClientCategory

the client category used for price determination.

cost_center

reference to: CostCenter

the cost center that the cost of the products sold in this sale should be accounted for. When confirming a sale with a cost center set, a cost center entry will be created for each product

comments

list of comments for this sale

returned_sales

All returned sales of this sale

sale_token_id

column: UUIDCol

The |sale_token| id

sale_token

reference to: SaleToken

Reference to |SaleToken|

invoice

reference to: Invoice

The |invoice| generated by the sale

cancel_responsible

reference to: LoginUser

The responsible for cancelling the sale. At the moment, the login user that cancelled the sale

branch

reference to: Branch

the branch this sale belongs to

cfop

reference to: CfopData

the fiscal entry

classmethod get_status_name(status)[source]

The Sale.status as a translated string

nfe_coupon_info

Returns

can_order()[source]

Only newly created sales can be ordered

Returns:True if the sale can be ordered
can_confirm()[source]

Only ordered sales can be confirmed

Returns:True if the sale can be confirmed
can_set_paid()[source]

Only confirmed sales can raise the flag paid. Also, the sale must have at least one payment and all the payments must be already paid.

Returns:True if the sale can be set as paid
can_set_not_paid()[source]

Only confirmed sales can be paid

Returns:True if the sale can be set as paid
can_set_renegotiated()[source]

Only sales with status confirmed can be renegotiated.

Returns:True if the sale can be renegotiated
can_cancel()[source]

Only ordered, confirmed, paid and quoting sales can be cancelled.

Returns:True if the sale can be cancelled
can_return()[source]

Only confirmed (with or without payment) sales can be returned

Returns:True if the sale can be returned
can_edit()[source]

Check if the sale can be edited.

Only quoting and ordered sales can be edited, as long as they are not external.

Returns:True if the sale can be edited
is_external()[source]

Check if this is an external sale.

Return type:bool
order()[source]

Orders the sale

Ordering a sale is the first step done after creating it. The state of the sale will change to Sale.STATUS_ORDERED. To order a sale you need to add sale items to it. A client might also be set for the sale, but it is not necessary.

confirm(till=None)[source]

Confirms the sale

Confirming a sale means that the customer has confirmed the sale. Sale items containing products are physically received and the payments are agreed upon but not necessarily received.

All money payments will be set as paid.

Parameters:till – the till where this sale was confirmed. Can be None in case the process was automated (e.g. a virtual store)
set_paid()[source]

Mark the sale as paid Marking a sale as paid means that all the payments have been received.

set_not_paid()[source]

Mark a sale as not paid. This happens when the user sets a previously paid payment as not paid.

set_renegotiated()[source]

Set the sale as renegotiated. The sale payments have been renegotiated and the operations will be done in another payment group.

set_not_returned()[source]

Sets a sale as not returnd

This will reset the sale status to confirmed (once you can only returna confirmed sale). Also, the return_date will be reset.

cancel(reason, force=False)[source]

Cancel the sale

You can only cancel an ordered sale. This will also cancel all the payments related to it.

Parameters:
  • reason – A short text describing the cancellation reason.
  • force – if True, can_cancel() will not be asserted. Only use this if you really need to (for example, when canceling the last sale on the ecf)
return_(returned_sale)[source]

Returns a sale Returning a sale means that all the items are returned to the stock. A renegotiation object needs to be supplied which contains the invoice number and the eventual penalty

Parameters:returned_sale – a stoqlib.domain.returnedsale.ReturnedSale object. It can be created by create_sale_return_adapter()
set_items_discount(discount)[source]

Apply discount on this sale’s items

Parameters:discount (decimal.Decimal) – the discount to be applied as a percentage, e.g. 10.0, 22.5
get_total_sale_amount(subtotal=None)[source]

Fetches the total value paid by the client. It can be calculated as:

Sale total = Sum(product and service prices) + surcharge +
                 interest - discount
Parameters:subtotal – pre calculated subtotal, pass in this to avoid a querying the database
Returns:the total value
get_sale_subtotal()[source]

Fetch the subtotal for the sale, eg the sum of the prices for of all items.

Returns:subtotal
get_sale_base_subtotal()[source]

Get the base subtotal of items

Just a helper that, unlike get_sale_subtotal(), will return the total based on item’s base price.

Returns:the base subtotal
get_items_total_quantity()[source]

Fetches the total number of items in the sale

Returns:number of items
get_total_paid()[source]

Return the total amount already paid for this sale :returns: the total amount paid

get_total_to_pay()[source]

Missing payment value for this sale.

Returns the value the client still needs to pay for this sale. This is the same as get_total_sale_amount() - get_total_paid()

get_returned_value()[source]

The total value returned from this sale.

This will return the sum of all returned sales of this sale.

get_available_discount_for_items(user=None, exclude_item=None)[source]

Get available discount for items in this sale

The available items discount is the total discount not used by items in this sale. For instance, if we have 2 products with a price of 100 and they can have 10% of discount, we have 20 of discount available. If one of those products price is set to 98, that is, using 2 of it’s discount, the available discount is now 18.

Parameters:
  • user – passed to stoqlib.domain.sellable.Sellable.get_maximum_discount() together with client_category to check for the max discount for sellables on this sale
  • exclude_item – a sale item to exclude from the calculations. Useful if you are trying to get some extra discount for that item and you don’t want it’s discount to be considered here
Returns:

the available discount

get_details_str()[source]

Returns the sale details

The details are composed by the items notes, the delivery address and the estimated fix date

Note that there might be some extra comments on comments

Returns:the sale details string.
get_salesperson_name()[source]
Returns:the sales person name
get_client_name()[source]

Returns the client name, if a client has been provided for this sale

Returns:the client name of a place holder string for sales without clients set.
get_client_document()[source]

Returns the client document for this sale

This could be either its cnpj or cpf.

get_client_role()[source]

Fetches the client role

Returns:the client role (an individual or a company) instance or None if the sale haven’t client set.
get_items_missing_batch()[source]

Get all sale items missing batch

This usually happens when we create a quote. Since we are not removing the items from the stock, they probably were not set on the sale item.

Returns:a result set of sale items that needs to set set the batch information
need_adjust_batches()[source]

Checks if we need to set batches for this sale’s sale items

This usually happens when we create a quote. Since we are not removing the items from the stock, they probably were not set on the sale item.

Returns:True if any sale item needs a batch, False otherwise.
check_and_adjust_batches()[source]

Check batches and perform a first adjustment when a sale item has only one batch.

Returns:True if all items that need a batch were adjusted, or False if there are items that were not possible to be adjusted.
only_paid_with_money()[source]

Find out if the sale is paid using money

Returns:True if the sale was paid with money
add_sellable(sellable, quantity=1, price=None, quantity_decreased=0, batch=None, parent=None)[source]

Adds a new item to a sale.

Parameters:
  • sellable – the sellable
  • quantity – quantity to add, defaults to 1
  • price – optional, the price, it not set the price from the sellable will be used
  • quantity_decreased – the quantity already decreased from stock. e.g. The param quantity 10 and that quantity were already decreased, so this param should be 10 too.
  • batch – the batch this sellable comes from, if the sellable is a storable. Should be None if it is not a storable or if the storable does not have batches.
  • parent – a |sale_item| parent_item of another |sale_item|
Returns:

a sale item for representing the sellable within this sale.

create_commission(payment)[source]

Creates a commission for the payment

This will create a commission for the given payment, sale and sale.salesperson. Note that, if the payment already has a commission, nothing will be done.

current_sale_token

The current token attached to this sale.

products

All sale items of this sale containing a product.

Returns:the result set containing the sale items, ordered by stoqlib.domain.sellable.Sellable.code
services

All sale items of this sale containing a service.

Returns:the result set containing the sale items, ordered by stoqlib.domain.sellable.Sellable.code
payments

Returns all valid payments for this sale ordered by open date

This will return a list of valid payments for this sale, that is, all payments on the payment groups that were not cancelled. If you need to get the cancelled too, use group.payments.

Returns:an ordered iterable of payment.
discount_percentage

Sets a discount by percentage.

Note that percentage must be added as an absolute value, in other words:

sale.total_sale_amount = 200
sale.discount_percentage = 5
# the price of the sale will now be be `190`
surcharge_percentage

Sets a discount by percentage.

Note that percentage must be added as an absolute value, in other words:

sale.total_sale_amount = 200
sale.surcharge_percentage = 5
# the price of the sale will now be `210`
class stoqlib.domain.sale.SaleToken(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A Token to help on sale for restaurants

This will be attached to a sale to help the sale for restaurants, hotels. eg: table 1, table 2, room 12, room 334

status

column: EnumCol

the status of the sale_token

code

column: Unicode

the code that used to identify the token

name

column: Unicode

The name of the token

sale

reference to: Sale

The sale that this token is attached to

branch

reference to: Branch

The branch that this token belongs

class stoqlib.domain.sale.SaleTokenView[source]

Bases: stoqlib.database.viewable.Viewable

Sale token view.

sale_token

alias of SaleToken

sale

alias of Sale

client

alias of Client

branch

alias of Branch

class stoqlib.domain.sale.SaleComment(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A simple holder for sale comments

See also: schema

date

column: DateTimeCol

When this comment was created

comment

column: Unicode

The comment itself.

author

reference to: LoginUser

The author of the comment

sale

reference to: Sale

The sale that was commented

class stoqlib.domain.sale.SaleView[source]

Bases: stoqlib.database.viewable.Viewable

Stores general informatios about sales

sale

the sale of the view

alias of Sale

client

the client of the view

alias of Client

branch

The branch this sale was sold

alias of Branch

invoice

The |invoice| of the view

alias of Invoice

token

The token referencing this sale

alias of SaleToken

id

column: PropertyColumn

the id of the sale table

identifier

column: PropertyColumn

unique numeric identifier for the sale

identifier_str = <storm.expr.Cast object>

unique numeric identifier for the sale, text representation

token_code

column: PropertyColumn

The code of the current token holding the sale

token_name

column: PropertyColumn

The name of the current token holding the sale

invoice_number

column: PropertyColumn

the sale invoice number

coupon_id

column: PropertyColumn

the id generated by the fiscal printer

open_date

column: PropertyColumn

the date when the sale was started

close_date

column: PropertyColumn

the date when the sale was closed

confirm_date

column: PropertyColumn

the date when the sale was confirmed

cancel_date

column: PropertyColumn

the date when the sale was cancelled

return_date

column: PropertyColumn

the date when the sale was returned

expire_date

column: PropertyColumn

the date when the sale will expire

status

column: PropertyColumn

the sale status

paid

column: PropertyColumn

the flag that indicates if the sale is completely paid

surcharge_value

column: PropertyColumn

the sale surcharge value

discount_value

column: PropertyColumn

the sale discount value

branch_id

column: PropertyColumn

the branch where this sale was sold

client_id

column: PropertyColumn

the if of the client table

salesperson_name = <storm.expr.Coalesce object>

the salesperson name

salesperson_id

column: PropertyColumn

the sale salesperson id

client_name = <storm.expr.Coalesce object>

the sale client name

client_fancy_name

column: PropertyColumn

the sale client fancy name

branch_name = <storm.expr.Coalesce object>

name of the branch this sale was sold

total_quantity = <storm.expr.Coalesce object>

the items total quantity for the sale

class stoqlib.domain.sale.SaleCommentsView[source]

Bases: stoqlib.database.viewable.Viewable

A view for sale comments

This is used to get the most information of a sale comment without doing lots of database queries

comment

column: PropertyColumn

the sale comment object

classmethod find_by_sale(store, sale)[source]

Find results for this view for sale

Parameters:
  • store – a store
  • sale – the sale used to filter the results
Returns:

the matching views

Return type:

a sequence of SaleCommentsView

class stoqlib.domain.sale.ReturnedSaleView[source]

Bases: stoqlib.database.viewable.Viewable

Stores general informatios about returned sales.

sale

alias of Sale

client

alias of Client

branch

alias of Branch

returned_sale

alias of ReturnedSale

returned_item

alias of ReturnedSaleItem

sellable

Domain objects related to something that can be sold, such a product or a service.

class stoqlib.domain.sellable.SellableUnit(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

The unit of a sellable. For instance: Kg (kilo), l (liter) and h (hour) When selling a sellable in a sale the quantity of a sale item will be entered in this unit.

See also: schema

SYSTEM_PRIMITIVES = [<UnitType value WEIGHT>, <UnitType value METERS>, <UnitType value LITERS>]

The values on the list are enums used to fill

description

column: Unicode

The unit description

unit_index

column: Int

This column defines if this object represents a custom product unit (created by the user through the product editor) or a native unit, like Km, Lt and pc.

This data is used mainly to interact with stoqdrivers, since when adding an item in a coupon we need to know if its unit must be specified as a description (using CUSTOM_PM constant) or as an index (using UNIT_*). Also, this is directly related to the DeviceSettings editor.

allow_fraction

column: Bool

If the unit allows to be represented in fractions.
e.g. We can have 1 car, 2 cars, but not 1/2 car.
class stoqlib.domain.sellable.SellableTaxConstant(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A tax constant tied to a sellable

See also: schema

description

column: Unicode

description of this constant

tax_type

column: Int

a TaxType constant, used by ECF

tax_value

column: PercentCol

the percentage value of the tax

get_value()[source]
Returns:the value to pass to ECF
classmethod get_by_type(tax_type, store)[source]

Fetch the tax constant for tax_type :param tax_type: the tax constant to fetch :param store: a store :returns: a sellable tax constant or None if none is found

class stoqlib.domain.sellable.SellableCategory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A Sellable category.

A way to group several sellables together, like “Shoes”, “Consumer goods”, “Services”.

A category can define markup, tax and commission, the values of the category will only be used when the sellable itself lacks a value.

Sellable categories can be grouped recursively.

See also: schema

description

column: Unicode

The category description

suggested_markup

column: PercentCol

Define the suggested markup when calculating the sellable’s price.

salesperson_commission

column: PercentCol

A percentage comission suggested for all the sales which products belongs to this category.

category

reference to: SellableCategory

base category of this category, None for base categories themselves

tax_constant

reference to: SellableTaxConstant

the sellable tax constant for this sellable category

children

the children of this category

full_description

The full description of the category, including its parents, for instance: u”Clothes:Shoes:Black Shoe 14 SL”

get_children_recursively()[source]

Return all the children from this category, recursively This will return all children recursively, e.g.:

   A
  /                     B   C
/                   D   E

In this example, calling this from A will return set([B, C, D, E])

get_commission()[source]

Returns the commission for this category. If it’s unset, return the value of the base category, if any

Returns:the commission
get_markup()[source]

Returns the markup for this category. If it’s unset, return the value of the base category, if any

Returns:the markup
get_tax_constant()[source]

Returns the tax constant for this category. If it’s unset, return the value of the base category, if any

Returns:the tax constant
classmethod get_base_categories(store)[source]

Returns all available base categories :param store: a store :returns: categories

class stoqlib.domain.sellable.ClientCategoryPrice(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A table that stores special prices for clients based on their client category.

See also: schema

sellable

reference to: Sellable

The sellable that has a special price

category

reference to: ClientCategory

The client category that has the special price

price

column: PriceCol

The price for this (sellable, client category)

max_discount

column: PercentCol

The max discount that may be applied.

remove()[source]

Removes this client category price from the database.

class stoqlib.domain.sellable.Sellable(store=None, category=None, cost=None, commission=None, description=None, price=None)[source]

Bases: stoqlib.domain.base.Domain

Sellable information of a certain item such a product or a service.

See also: schema

STATUS_AVAILABLE = u'available'

the sellable is available and can be used on a purchase/sale

STATUS_CLOSED = u'closed'

the sellable is closed, that is, it still exists for references, but it should not be possible to create a purchase/sale with it

code

column: Unicode

a code used internally by the shop to reference this sellable. It is usually not printed and displayed to clients, barcode is for that. It may be used as an shorter alternative to the barcode.

barcode

column: Unicode

barcode, mostly for products, usually printed and attached to the package.

status

column: EnumCol

status the sellable is in

base_price

column: PriceCol

price of sellable, how much the client paid.

cost_last_updated

column: DateTimeCol

the last time the cost was updated

price_last_updated

column: DateTimeCol

the last time the price was updated

max_discount

column: PercentCol

maximum discount allowed

notes

column: Unicode

notes for the sellable

unit

reference to: SellableUnit

the sellable unit, quantities of this sellable are in this unit.

tax_constant

reference to: SellableTaxConstant

the sellable tax constant, this controls how this sellable is taxed

product

reference to: Product

the product for this sellable or None

service

reference to: Service

the service for this sellable or None

product_storable

reference to: Storable

the storable for this product‘s sellable

default_sale_cfop

reference to: CfopData

the default C.F.O.P. that will be used when selling this sellable

on_sale_price

column: PriceCol

A special price used when we have a “on sale” state, this can be used for promotions

on_sale_start_date

column: DateTimeCol

When the promotional/special price starts to apply

on_sale_end_date

column: DateTimeCol

When the promotional/special price ends

images

This sellable’s images

category

reference to: SellableCategory

a reference to category table

commission

column: PercentCol

commission to pay after selling this sellable

cost

column: PriceCol

cost of the sellable, this is not tied to a specific supplier, which may have a different cost. This can also be the production cost of manufactured item by the company.

description

column: Unicode

full description of sellable

status_str

The sellable status as a string

unit_description

Returns the description of the sellable unit of this sellable

Returns:the unit description or an empty string if no sellable unit was set.
Return type:unicode
image

This sellable’s main image.

markup

Markup, the opposite of discount, a value added on top of the sale. It’s calculated as:

((cost/price)-1)*100
is_available()[source]

Whether the sellable is available and can be sold.

Returns:True if the item can be sold, False otherwise.
set_available()[source]

Mark the sellable as available

Being available means that it can be ordered or sold.

Raises:ValueError: if the sellable is already available
is_closed()[source]

Whether the sellable is closed or not.

Returns:True if closed, False otherwise.
close()[source]

Mark the sellable as closed.

After the sellable is closed, this will call the close method of the service or product related to this sellable.

Raises:ValueError: if the sellable is already closed
can_remove()[source]

Whether we can delete this sellable from the database.

False if the product/service was used in some cases below:

- Sold or received
- The |product| is in a |purchase|
can_close()[source]

Whether we can close this sellable.

Returns:True if the product has no stock left or the service is not required by the system (i.e. Delivery service is required). False otherwise.
get_suggested_markup()[source]

Returns the suggested markup for the sellable

Returns:suggested markup
Return type:decimal
get_category_description()[source]

Returns the description of this sellables category If it’s unset, return the constant from the category, if any

Returns:sellable category description or an empty string if no sellable category was set.
Return type:unicode
get_tax_constant()[source]

Returns the sellable tax constant for this sellable. If it’s unset, return the constant from the category, if any

Returns:the sellable tax constant or None if unset
get_category_prices()[source]

Returns all client category prices associated with this sellable.

Returns:the client category prices
get_category_price_info(category)[source]

Returns the ClientCategoryPrice information for the given ClientCategory and this sellable.

Returns:the ClientCategoryPrice or None
get_price_for_category(category)[source]

Given the client category, returns the price for that category or the default sellable price.

Parameters:category – a client category
Returns:The value that should be used as a price for this sellable.
check_code_exists(code)[source]

Check if there is another sellable with the same code.

Returns:True if we already have a sellable with the given code False otherwise.
check_barcode_exists(barcode)[source]

Check if there is another sellable with the same barcode.

Returns:True if we already have a sellable with the given barcode False otherwise.
check_taxes_validity()[source]

Check if icms taxes are valid.

This check is done because some icms taxes (such as CSOSN 101) have a ‘valid until’ field on it. If these taxes has expired, we cannot sell the sellable. Check this method using assert inside a try clause.

Raises:TaxError if there are any issues with the sellable taxes.
is_on_sale()[source]

Check if the price is currently on sale.

Returns:True if it is on sale, False otherwise
is_valid_quantity(new_quantity)[source]

Whether the new quantity is valid for this sellable or not.

If the new quantity is fractioned, check on this sellable unit if it allows fractioned quantities. If not, this new quantity cannot be used.

Note that, if the sellable lacks a unit, we will not allow fractions either.

Returns:True if new quantity is Ok, False otherwise.
is_valid_price(newprice, category=None, user=None, extra_discount=None)[source]

Checks if newprice is valid for this sellable

Returns a dict indicating whether the new price is a valid price as allowed by the discount by the user, by the category or by the sellable maximum discount

Parameters:
  • newprice – The new price that we are trying to sell this sellable for
  • category – Optionally define a client category that we will get the price info from
  • user – The user role may allow a different discount percentage.
  • extra_discount – some extra discount for the sellable to be considered for the min_price
Returns:

A dict with the following keys: * is_valid: True if the price is valid, else False * min_price: The minimum price for this sellable. * max_discount: The maximum discount for this sellable.

copy_sellable(target=None)[source]

This method copies self to another sellable

If the sellable target is None, a new sellable is created.

Parameters:target – The sellable target for the copy

returns: a sellable identical to self

remove()[source]

Remove this sellable. This will also remove the product or sellable and |categoryprice|

classmethod get_available_sellables_query(store)[source]

Get the sellables that are available and can be sold.

For instance, this will filter out the internal sellable used by a delivery.

This is similar to .get_available_sellables, but it returns a query instead of the actual results.

Parameters:store – a store
Returns:a query expression
classmethod get_available_sellables(store)[source]

Get the sellables that are available and can be sold.

For instance, this will filter out the internal sellable used by a delivery.

Parameters:store – a store
Returns:a resultset with the available sellables
classmethod get_unblocked_sellables_query(store, storable=False, supplier=None, consigned=False)[source]

Helper method for get_unblocked_sellables

When supplier is not `None, you should use this query only with Viewables that join with supplier, like ProductFullStockSupplierView.

Parameters:
  • store – a store
  • storable – if True, we should filter only the sellables that are also a storable.
  • suppliersupplier to filter on or None
  • consigned – if the sellables are consigned
Returns:

a query expression

classmethod get_unblocked_sellables(store, storable=False, supplier=None, consigned=False)[source]

Returns unblocked sellable objects, which means the available sellables plus the sold ones.

Parameters:
  • store – a store
  • storable – if True, only return sellables that also are storable
  • supplier – a supplier or None, if set limit the returned object to this supplier
Return type:

queryset of sellables

classmethod get_unblocked_by_categories_query(store, categories, include_uncategorized=True)[source]

Returns the available sellables by a list of categories.

Parameters:
  • store – a store
  • categories – a list of SellableCategory instances
  • include_uncategorized – whether or not include the sellables without a category
Return type:

generator of sellables

service

Base classes to manage services informations

class stoqlib.domain.service.Service(**kwargs)[source]

Bases: stoqlib.domain.base.Domain

Class responsible to store basic service informations.

sellable

reference to: Sellable

The sellable for this service

city_taxation_code

column: Unicode

The taxation code for this service in the city

service_list_item_code

column: Unicode

The federal service list item code for this service

p_iss

column: PercentCol

ISS Aliquot in percentage

remove()[source]

Removes this service from the database.

class stoqlib.domain.service.ServiceView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about services

Attribute id:the id of the asellable table
Attribute barcode:
 the sellable barcode
Attribute status:
 the sellable status
Attribute cost:the sellable cost
Attribute price:
 the sellable price
Attribute description:
 the sellable description
Attribute unit:the unit in case the sellable is not a product
Attribute service_id:
 the id of the service table
sellable

alias of Sellable

station

Station, a branch station per computer

class stoqlib.domain.station.BranchStation(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Defines a computer which access Stoqlib database and lives in a certain branch company

classmethod get_active_stations(store)[source]

Returns the currently active branch stations. :param store: a store :returns: a sequence of currently active stations

classmethod create(store, branch, name)[source]

Create a new station id for the current machine. Optionally a branch can be specified which will be set as the branch for created station.

Parameters:
  • store – a store
  • branch – the branch
  • name – name of the station
Returns:

a BranchStation instance

check_station_exists(name)[source]

Returns True if we already have a station with the given name

classmethod get_station(store, branch, name)[source]

Fetches a station from a branch

Parameters:
  • store – a store
  • branch – the branch
  • name – name of the station
get_branch_name()[source]

Returns the branch name

stockdecrease

Stock Decrease object and related objects implementation

class stoqlib.domain.stockdecrease.StockDecreaseItem(store=None, sellable=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

An item in a stock decrease object.

Note that objects of this type should not be created manually, only by calling StockDecrease.add_sellable()

stock_decrease

reference to: StockDecrease

The stock decrease this item belongs to

sellable

reference to: Sellable

the sellable for this decrease

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was removed from

cost

column: PriceCol

the cost of the sellable on the moment this decrease was created

quantity

column: QuantityCol

the quantity decreased for this item

icms_info_id

column: UUIDCol

Id of ICMS tax in product tax template

icms_info

reference to: InvoiceItemIcms

the stoqlib.domain.taxes.InvoiceItemIcms tax for self

ipi_info_id

column: UUIDCol

Id of IPI tax in product tax template

ipi_info

reference to: InvoiceItemIpi

the stoqlib.domain.taxes.InvoiceItemIpi tax for self

pis_info_id

column: UUIDCol

Id of PIS tax in product tax template

pis_info

reference to: InvoiceItemPis

the stoqlib.domain.taxes.InvoiceItemPis tax for self

cofins_info_id

column: UUIDCol

Id of COFINS tax in product tax template

cofins_info

reference to: InvoiceItemCofins

the stoqlib.domain.taxes.InvoiceItemCofins tax for self

class stoqlib.domain.stockdecrease.StockDecrease(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Stock Decrease object implementation.

Stock Decrease is when the user need to manually decrease the stock quantity, for some reason that is not a sale, transfer or other cases already covered in stoqlib.

STATUS_INITIAL = u'initial'

Stock Decrease is still being edited

STATUS_CONFIRMED = u'confirmed'

Stock Decrease is confirmed and stock items have been decreased.

STATUS_CANCELLED = u'cancelled'

Stock Decrease is cancelled and all items have been returned to stock.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

status

column: EnumCol

status of the sale

notes

column: Unicode

Some optional additional information related to this sale.

confirm_date

column: DateTimeCol

the date sale was created

cancel_date

column: DateTimeCol

The date the stock decrease was cancelled

cancel_reason

column: Unicode

The reason stock decrease loan was cancelled

responsible

reference to: LoginUser

who should be blamed for this

branch

reference to: Branch

branch where the sale was done

person_id

column: UUIDCol

person who is receiving

cfop_id

column: UUIDCol

the choosen CFOP

group_id

column: UUIDCol

the payment group related to this stock decrease

cost_center

reference to: CostCenter

the cost center that the cost of the products decreased in this stock decrease should be accounted for. When confirming a stock decrease with a cost center set, a cost center entry will be created for each product decreased.

transporter = None

transporter used in stock decrease

invoice

reference to: Invoice

The |invoice| generated by the stock decrease

cancel_responsible_id

column: UUIDCol

The responsible for cancelling the stock decrease. At the moment, the login user that cancelled the stock decrease

can_confirm()[source]

Only stock decreases with status equal to INITIAL can be confirmed

Returns:True if the stock decrease can be confirmed, otherwise False
confirm()[source]

Confirms the stock decrease

add_sellable(sellable, cost=None, quantity=1, batch=None)[source]

Adds a new sellable item to a stock decrease

Parameters:
  • sellable – the sellable
  • cost – the cost for the decrease. If None, sellable.cost will be used instead
  • quantity – quantity to add, defaults to 1
  • batch – the batch this sellable comes from, if the sellable is a storable. Should be None if it is not a storable or if the storable does not have batches.

synchronization

BranchSynchronization domain class

class stoqlib.domain.synchronization.BranchSynchronization(store=None, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

Created once per branch. Contains a string which is a reference to a policy defined in stoqlib.database.policy and a timestamp which is updated each time a synchronization is done.

sync_time

column: DateTimeCol

last time updated

branch

reference to: Branch

a branch

policy

column: Unicode

policy used to update the branch

system

Routines for system data management

class stoqlib.domain.system.SystemTable(store=None, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

Stores information about database schema migration

I{update}: the date when the database schema was updated I{patchlevel}: the version of the schema installed

classmethod is_available(store)[source]

Checks if Stoqlib database is properly installed :param store: a store

class stoqlib.domain.system.TransactionEntry(store=None, **kwargs)[source]

Bases: stoqlib.database.orm.ORMObject

A TransactionEntry keeps track of state associated with a database transaction. It’s main use case is to know information about the system when a domain object is created or modified.

Such information will be used by stoq when syncing databases

te_time

column: DateTimeCol

last time this object was modified

dirty

column: Bool

It this object was modified since the last time it was synced After the object is synced, this property will be set to False, so that when the next sync begins, only the objects that are dirty will be processed

taxes

class stoqlib.domain.taxes.BaseICMS(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseTax

NfeProductIcms stores the default values that will be used when creating NfeItemIcms objects

class stoqlib.domain.taxes.BasePIS(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseTax

Contains attributes to be used to calculate PIS tax in Brazil.

calculo

column: EnumCol

Operation type (percentage or value)

p_pis

column: PercentCol

Aliquot in percentage

class stoqlib.domain.taxes.BaseCOFINS(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseTax

Contains attributes to be used to calculate PIS tax in Brazil.

calculo

column: EnumCol

Operation type (percentage or value)

p_cofins

column: PercentCol

Aliquot in percentage

class stoqlib.domain.taxes.ProductIpiTemplate(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseIPI

Template of IPI tax

class stoqlib.domain.taxes.ProductPisTemplate(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BasePIS

Template of PIS tax

class stoqlib.domain.taxes.ProductCofinsTemplate(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseCOFINS

Template of COFINS tax

class stoqlib.domain.taxes.InvoiceItemIpi(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseIPI

Invoice of IPI tax.

class stoqlib.domain.taxes.InvoiceItemPis(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BasePIS

Invoice of PIS tax.

v_pis

column: PriceCol

Value of PIS tax.

v_bc

column: PriceCol

Value of the PIS tax calculation basis.

q_bc_prod

column: QuantityCol

Quantity sold

class stoqlib.domain.taxes.InvoiceItemCofins(*args, **kwargs)[source]

Bases: stoqlib.domain.taxes.BaseCOFINS

Invoice of COFINS tax.

v_cofins

column: PriceCol

Value of COFINS tax

v_bc

column: PriceCol

Value of the COFINS tax calculation basis.

q_bc_prod

column: QuantityCol

Quantity sold

till

Implementation of classes related to Fiscal operations.

class stoqlib.domain.till.Till(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

The Till describes the financial operations of a specific day.

The operations that are recorded in a Till:

  • Sales
  • Adding cash
  • Removing cash
  • Giving out an early salary

Each operation is associated with a till entry.

You can only open a Till once per day, and you cannot open a new till before you closed the previously opened one.

STATUS_PENDING = u'pending'

this till is created, but not yet opened

STATUS_OPEN = u'open'

this till is opened and we can make sales for it.

STATUS_CLOSED = u'closed'

end of the day, the till is closed and no more financial operations can be done in this store.

initial_cash_amount

column: PriceCol

The total amount we had the moment the till was opened.

final_cash_amount

column: PriceCol

The total amount we have the moment the till is closed.

opening_date

column: DateTimeCol

When the till was opened or None if it has not yet been opened.

closing_date

column: DateTimeCol

When the till was closed or None if it has not yet been closed

station

reference to: BranchStation

the branch station associated with the till, eg the computer which opened it.

responsible_open

reference to: LoginUser

The responsible for opening the till

responsible_close

reference to: LoginUser

The responsible for closing the till

classmethod get_current(store)[source]

Fetches the Till for the current station.

Parameters:store – a store
Returns:a Till instance or None
classmethod get_last_opened(store)[source]

Fetches the last Till which was opened. If in doubt, use Till.get_current instead. This method is a special case which is used to be able to close a till without calling get_current()

Parameters:store – a store
open_till()[source]

Open the till.

It can only be done once per day. The final cash amount of the previous till will be used as the initial value in this one after opening it.

close_till(observations=u'')[source]

This method close the current till operation with the confirmed sales associated. If there is a sale with a differente status than SALE_CONFIRMED, a new ‘pending’ till operation is created and these sales are associated with the current one.

add_entry(payment)[source]

Adds an entry to the till.

Parameters:payment – a payment
Returns:till entry representing the added debit
add_debit_entry(value, reason=u'')[source]

Add debit to the till

Parameters:
  • value – amount to add
  • reason – description of payment
Returns:

till entry representing the added debit

add_credit_entry(value, reason=u'')[source]

Add credit to the till

Parameters:
  • value – amount to add
  • reason – description of entry
Returns:

till entry representing the added credit

needs_closing()[source]

Checks if there’s an open till that needs to be closed before we can do any further fiscal operations. :returns: True if it needs to be closed, otherwise false

get_balance()[source]

Returns the balance of all till operations plus the initial amount cash amount. :returns: the balance :rtype: currency

get_cash_amount()[source]

Returns the total cash amount on the till. That includes “extra” payments (like cash advance, till complement and so on), the money payments and the initial cash amount. :returns: the cash amount on the till :rtype: currency

get_entries()[source]

Fetches all the entries related to this till :returns: all entries :rtype: sequence of till entry

get_credits_total()[source]

Calculates the total credit for all entries in this till :returns: total credit :rtype: currency

get_debits_total()[source]

Calculates the total debit for all entries in this till :returns: total debit :rtype: currency

class stoqlib.domain.till.TillEntry(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A TillEntry is a representing cash added or removed in a till. * A positive value represents addition. * A negative value represents removal.

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

date

column: DateTimeCol

the date the entry was created

description

column: Unicode

A small string describing what was done

value

column: PriceCol

value of transaction

till

reference to: Till

the till the entry takes part of

payment

reference to: Payment

payment of this entry, if any

branch

reference to: Branch

branch that received or gave money

time

The time of the entry

Note that this is the same as date.time(), but with microseconds replaced to 0.

transfer

Product transfer management

class stoqlib.domain.transfer.TransferOrderItem(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Transfer order item

sellable

reference to: Sellable

The sellable to transfer

batch

reference to: StorableBatch

If the sellable is a storable, the batch that was transfered

transfer_order

reference to: TransferOrder

The transfer this item belongs to

quantity

column: QuantityCol

The quantity to transfer

stock_cost

column: PriceCol

Average cost of the item in the source branch at the time of transfer.

icms_info

reference to: InvoiceItemIcms

the stoqlib.domain.taxes.InvoiceItemIcms tax for self

ipi_info

reference to: InvoiceItemIpi

the stoqlib.domain.taxes.InvoiceItemIpi tax for self

pis_info

reference to: InvoiceItemPis

the stoqlib.domain.taxes.InvoiceItemPis tax for self

cofins_info

reference to: InvoiceItemCofins

the stoqlib.domain.taxes.InvoiceItemCofins tax for self

get_total()[source]

Returns the total cost of a transfer item eg quantity * cost

send()[source]

Sends this item to it’s destination branch. This method should never be used directly, and to send a transfer you should use TransferOrder.send().

receive()[source]

Receives this item, increasing the quantity in the stock. This method should never be used directly, and to receive a transfer you should use TransferOrder.receive().

cancel()[source]

Cancel the receiving of this transfer item.

This method will return the product to the stock from source branch. This method should never be used directly, and to cancel a transfer you should use TransferOrder.cancel()

class stoqlib.domain.transfer.TransferOrder(store=None, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Transfer Order class

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

open_date

column: DateTimeCol

The date the order was created

receival_date

column: DateTimeCol

The date the order was received

cancel_date

column: DateTimeCol

The date the order was cancelled

cancel_responsible

reference to: Employee

The employee responsible for cancel the transfer

comments

column: Unicode

Comments of a transfer

source_branch

reference to: Branch

The branch sending the stock

destination_branch

reference to: Branch

The branch receiving the stock

source_responsible

reference to: Employee

The employee responsible for the transfer at source branch

destination_responsible

reference to: Employee

The employee responsible for the transfer at destination branch

payments = None

payments generated by this transfer

transporter = None

transporter used in transfer

invoice

reference to: Invoice

The |invoice| generated by the transfer

cancel_reason

column: Unicode

the reason the transfer was cancelled

add_sellable(sellable, batch, quantity=1, cost=None)[source]

Add the given sellable to this transfer.

Parameters:
  • sellable – The sellable we are transfering
  • batch – What batch of the storable (represented by sellable) we are transfering.
  • quantity – The quantity of this product that is being transfered.
send()[source]

Sends a transfer order to the destination branch.

receive(responsible, receival_date=None)[source]

Confirms the receiving of the transfer order.

cancel(responsible, cancel_reason, cancel_date=None)[source]

Cancel a transfer order

classmethod get_pending_transfers(store, branch)[source]

Get all the transfers that need to be recieved

Get all transfers that have STATUS_SENT and the current branch as the destination This is useful if you want to list all the items that need to be recieved in a certain branch

get_source_branch_name()[source]

Returns the source branch name

get_destination_branch_name()[source]

Returns the destination branch name

get_source_responsible_name()[source]

Returns the name of the employee responsible for the transfer at source branch

get_destination_responsible_name()[source]

Returns the name of the employee responsible for the transfer at destination branch

get_total_items_transfer()[source]

Retuns the transfer items quantity

uiform

Domain classes to define required and visible fields

class stoqlib.domain.uiform.UIField(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This describes a field in form a. Can be used makae fields mandatory or hide them completely.

update_field(mandatory=False, visible=False)[source]

This method changes some properties of the field

Parameters:
  • mandatory – A boolean indicating if the field is mandatory
  • visible – A boolean indicating if the field is visible
class stoqlib.domain.uiform.UIForm(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

This describes a form which has a number of fields

get_field(field_name)[source]

Returns a |uifield| from |uiform|

Parameters:field_name – name of a UIField
Returns:the |uifield| of that field_name

views

class stoqlib.domain.views.ProductFullStockView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about products. This view is used to query stock information on a certain branch.

Variables:
  • id – the id of the asellable table
  • barcode – the sellable barcode
  • status – the sellable status
  • cost – the sellable cost
  • price – the sellable price
  • description – the sellable description
  • unit – the unit of the product
  • product_id – the id of the product table
  • location – the location of the product
  • branch_id – the id of branch table
  • stock – the stock of the product
sellable

alias of Sellable

product

alias of Product

get_product_and_category_description()[source]

Returns the product and the category description in one string. The category description will be formatted inside square brackets, if any. Otherwise, only the product description will be returned.

class stoqlib.domain.views.ProductFullWithClosedStockView[source]

Bases: stoqlib.domain.views.ProductFullStockView

Stores information about products, showing the closed ones too.

class stoqlib.domain.views.ProductClosedStockView[source]

Bases: stoqlib.domain.views.ProductFullWithClosedStockView

Stores information about products that were closed.

class stoqlib.domain.views.ProductComponentView[source]

Bases: stoqlib.domain.views.ProductFullStockView

Stores information about production products

class stoqlib.domain.views.ProductComponentWithClosedView[source]

Bases: stoqlib.domain.views.ProductComponentView

Stores information about production products, including closed ones

class stoqlib.domain.views.ProductWithStockView[source]

Bases: stoqlib.domain.views.ProductFullStockView

Stores information about products, since product has a purchase or sale. This view is used to query stock information on a certain branch.

Variables:
  • id – the id of the asellable table
  • barcode – the sellable barcode
  • status – the sellable status
  • cost – the sellable cost
  • price – the sellable price
  • description – the sellable description
  • unit – the unit of the product
  • product_id – the id of the product table
  • branch_id – the id of branch table
  • stock – the stock of the product
class stoqlib.domain.views.ProductWithStockBranchView[source]

Bases: stoqlib.domain.views.ProductFullStockView

The same as ProductWithStockView but has a branch_id property that must be used to filte.

Note that when using this viewable, all queries must include the branch filter, otherwise, the results may be duplicated (once for each branch in the database)

class stoqlib.domain.views.ProductFullStockItemSupplierView[source]

Bases: stoqlib.domain.views.ProductFullStockItemView

Just like ProductFullStockView, but will also be joined with ProductSupplierInfo and Supplier, so use this only if you are specifing a supplier in the query.

class stoqlib.domain.views.ProductQuantityView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about products solded and received.

Variables:
  • id – the id of the sellable_id of products_quantity table
  • description – the product description
  • branch_id – the id of branch table
  • quantity_sold – the quantity solded of product
  • quantity_transfered – the quantity transfered of product
  • quantity_received – the quantity received of product
  • branch – the id of the branch_id of producst_quantity table
  • date_sale – the date of product’s sale
  • date_received – the date of product’s received
sellable

alias of Sellable

product

alias of Product

class stoqlib.domain.views.ProductBranchStockView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about the stock of a certain product among all branches

branch

alias of Branch

class stoqlib.domain.views.SellableFullStockView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about products. This view is used to query stock information on a certain branch.

Variables:
  • id – the id of the asellable table
  • barcode – the sellable barcode
  • status – the sellable status
  • cost – the sellable cost
  • price – the sellable price
  • description – the sellable description
  • unit – the unit of the product or None
  • product_id – the id of the product table or None
  • branch_id – the id of branch table or None
  • stock – the stock of the product or None
sellable

alias of Sellable

product

alias of Product

class stoqlib.domain.views.SellableCategoryView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about categories. This view is used to query the category with the related commission source.

category

alias of SellableCategory

class stoqlib.domain.views.QuotationView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about the quote group and its quotes.

purchase

alias of PurchaseOrder

class stoqlib.domain.views.SoldItemView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about all sale items, including the average cost of the sold items.

sellable

alias of Sellable

product

alias of Product

class stoqlib.domain.views.StockDecreaseView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about all stock decreases

stock_decrease

alias of StockDecrease

class stoqlib.domain.views.StockDecreaseItemsView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about all stock decrease items

branch

alias of Branch

class stoqlib.domain.views.SoldItemsByBranchView[source]

Bases: stoqlib.domain.views.SoldItemView

Store information about the all sold items by branch.

class stoqlib.domain.views.PurchasedItemAndStockView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about the purchase items that will be delivered and also the quantity that is already in stock. This view is used to query which products are going to be delivered and if they are on time or not.

Variables:
  • id – the id of the purchased item
  • product_id – the id of the product
  • purchased – the quantity purchased
  • received – the quantity already received
  • stocked – the quantity in stock
  • expected_receival_date – the date that the item might be deliverd
  • purchase_date – the date when the item was purchased
  • branch – the branch where the purchase was done
sellable

alias of Sellable

product

alias of Product

purchase_item

alias of PurchaseItem

branch

alias of Branch

class stoqlib.domain.views.PurchaseReceivingView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about received orders.

Variables:
  • id – the id of the receiving order
  • receival_date – the date when the receiving order was closed
  • invoice_number – the number of the order that was received
  • invoice_total – the total value of the received order
  • purchase_identifier – the identifier of the received order
  • branch_id – the id branch where the order was received
  • purchase_responsible_name – the one who have confirmed the purchase
  • responsible_name – the one who has received the order
  • supplier_name – the supplier name
order

alias of ReceivingOrder

class stoqlib.domain.views.SaleItemsView[source]

Bases: stoqlib.database.viewable.Viewable

Show information about sold items and about the corresponding sale. This is slightlig difrent than SoldItemView that groups sold items from diferent sales.

branch

alias of Branch

sellable

alias of Sellable

product

alias of Product

class stoqlib.domain.views.ReceivingItemView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about receiving items. This view is used to query products that are going to be received or was already received and the information related to that process.

Variables:
  • id – the id of the receiving item
  • order_identifier – the identifier of the receiving order
  • purchase_identifier – the identifier of the purchase order
  • purchase_item_id – the id of the purchase item
  • sellable_id – the id of the sellable related to the received item
  • invoice_number – the invoice number of the receiving order
  • receival_date – the date when the item was received
  • quantity – the received quantity
  • cost – the product cost
  • unit_description – the product unit description
  • supplier_name – the product supplier name
branch

alias of Branch

class stoqlib.domain.views.UnconfirmedSaleItemsView[source]

Bases: stoqlib.database.viewable.Viewable

Stores information about reserved products This view is used to query products that was reserved and temporarily removed from stock until the sale is completed.

Variables:
branch

alias of Branch

class stoqlib.domain.views.CostCenterEntryStockView[source]

Bases: stoqlib.database.viewable.Viewable

A viewable with information about cost center entries related to stock transactions.

stock_transaction

alias of StockTransactionHistory

class stoqlib.domain.views.ClientWithSalesView[source]

Bases: stoqlib.domain.person.ClientView

A client view capable of filtering clients with sales on a given branch.

classmethod find_by_birth_date(store, date, branch=None)[source]

Find clients by bith date.

Parameters:
  • store – The store used to do the query
  • date – The date to filter the birthdays, either the value directly or a tuple defining a (start, end) interval
  • branch – If not None will be used to filter only clients with at least one sale referencing it done on that branch

workorder

Work order implementation and utils

class stoqlib.domain.workorder.WorkOrderPackageItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A work order package item

This is a representation of a work order inside a work order package. This is used instead of the work order directly so we can keep a history of sent and received packages.

See also: schema

package

reference to: WorkOrderPackage

the work order package this item is transported in

order

reference to: WorkOrder

the work order this item represents

send()[source]

Send the item to the WorkOrderPackage.destination_branch

This will mark the package as sent. Note that it’s only possible to call this on the same branch as source_branch.

When calling this, the work orders’ WorkOrder.current_branch will be None, since they are on a package and not on any branch.

receive()[source]

Receive this item on the WorkOrderPackage.destination_branch

This will mark the package as received in the branch to receive it there. Note that it’s only possible to call this on the same branch as destination_branch.

When calling this, the work orders’ WorkOrder.current_branch will be set to WorkOrderPackage.destination_branch, since receiving means they got to their destination.

class stoqlib.domain.workorder.WorkOrderPackage(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A package of work orders

This is a package (called ‘malote’ on Brazil) that will be used to send workorder(s) to another branch for the task execution.

digraph work_order_package_status {
  STATUS_OPENED -> STATUS_SENT;
  STATUS_SENT -> STATUS_RECEIVED;
}

See also: schema

STATUS_OPENED = u'opened'

package is opened, waiting to be sent

STATUS_SENT = u'sent'

package was sent to the destination_branch

STATUS_RECEIVED = u'received'

package was received by the destination_branch

identifier

column: Unicode

the packages’s identifier

send_date

column: DateTimeCol

when the package was sent from the source_branch

receive_date

column: DateTimeCol

when the package was received by the destination_branch

send_responsible

reference to: LoginUser

the login user responsible for sending the package

receive_responsible

reference to: LoginUser

the login user responsible for receiving the package

destination_branch

reference to: Branch

the destination branch, that is, the branch where the package is going to be sent to

source_branch

reference to: Branch

the source branch, that is, the branch where the package is leaving

package_items

the work order package items inside this package

quantity

The quantity of work order package items inside this package

add_order(workorder, notes=None)[source]

Add a work order on this package

Note that this will set the WorkOrder.current_branch to None (since it’s now on the package).

Parameters:notes – some notes that will be used when adding an entry on WorkOrderHistory
Returns:the created work order package item
can_send()[source]

If we can send this package to the destination_branch

can_receive()[source]

If we can receive this package in the destination_branch

send()[source]

Send the package to the destination_branch

This will mark the package as sent. Note that it’s only possible to call this on the same branch as source_branch.

Each package_items will have it’s WorkOrderPackageItem.send() method called

receive()[source]

Receive the package on the destination_branch

This will mark the package as received in the branch to receive it there. Note that it’s only possible to call this on the same branch as destination_branch.

Each package_items will have it’s WorkOrderPackageItem.receive() method called

class stoqlib.domain.workorder.WorkOrderCategory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A work order‘s category

Used to categorize a work order. It can be differentiate mainly by the name, but one can use color in a gui to make the differentiation better.

See also: schema

name

column: Unicode

category’s name

color

column: Unicode

category’s color (e.g. #ff0000 for red)

class stoqlib.domain.workorder.WorkOrderItem(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

A work order item

This is an item in a work order. That is, a product or a service (here referenced by their respective sellable) used on the work and that will be after used to compose the sale item of the sale.

Note that objects of this type should not be created manually, only by calling WorkOrder.add_sellable()

See also: schema

quantity

column: QuantityCol

sellable‘s quantity used on the work order

quantity_decreased

column: QuantityCol

the quantity of sellable consumed (i.e. decreased from the stock). This needs to be equal to quantity for the work order to be finished

price

column: PriceCol

price of the sellable, this is how much the client is going to be charged for the sellable. This includes discounts and markup.

sellable

reference to: Sellable

the sellable of this item, either a service or a product

batch

reference to: StorableBatch

If the sellable is a storable, the batch that it was removed from

order

reference to: WorkOrder

work order this item belongs

sale_item

reference to: SaleItem

the corresponding sale item for this item

total

The total value for this item

Note that this is the same as quantity * price

reserve(quantity)[source]

Reserve some quantity of this item

Reserving some quantity of items means decreasing them from the stock. All quantity needs to be reserved for a work order to be finished. The already reserved quantity will be stored at quantity_decreased

Parameters:quantity – the quantity to consume
Raises:ValueError if the quantity to reserve is greater than the unreserved quantity (quantity - quantity_decreased
return_to_stock(quantity)[source]

Return some quantity of this item to stock

Returning some quantity of items to the stock means increasing the stock back.

Parameters:quantity – the quantity to return to the stock
Raises:ValueError if the quantity to return to the stock greater than the quantity_decreased
classmethod get_from_sale_item(store, sale_item)[source]

Get the work order item given one sale item

Parameters:
  • store – a store
  • sale_item – a sale item
Returns:

The work order item related to the sale item

Return type:

work order item

class stoqlib.domain.workorder.WorkOrder(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Represents a work order

Normally, this is a maintenance task, like:
  • The client reports a defect on an equipment.
  • The responsible for doing the quote analyzes the equipment and detects the real defect.
  • The client then approves the quote and the work begins.
  • After it’s finished, a sale is created for it, the client pays and gets it’s equipment back.

digraph work_order_status {
  STATUS_OPENED -> STATUS_WORK_WAITING;
  STATUS_OPENED -> STATUS_CANCELLED;
  STATUS_WORK_WAITING -> STATUS_WORK_IN_PROGRESS;
  STATUS_WORK_WAITING -> STATUS_CANCELLED;
  STATUS_WORK_IN_PROGRESS -> STATUS_WORK_FINISHED;
  STATUS_WORK_IN_PROGRESS -> STATUS_WORK_WAITING;
  STATUS_WORK_IN_PROGRESS -> STATUS_CANCELLED;
  STATUS_WORK_FINISHED -> STATUS_DELIVERED;
  STATUS_WORK_FINISHED -> STATUS_WORK_IN_PROGRESS;
}

See also: schema

STATUS_OPENED = u'opened'

a request for an order has been created, the order has not yet been approved the client

STATUS_CANCELLED = u'cancelled'

for some reason it was cancelled

STATUS_WORK_WAITING = u'waiting'

this is the initial status after the order gets approved by the client and also a helper state for STATUS_WORK_IN_PROGRESS since when there, the order can come back here to be explicit that it’s waiting (for material, for labor, etc) to continue the work

STATUS_WORK_IN_PROGRESS = u'in-progress'

work is currently in progress. Note that if at any time we need to wait for more material to continue the work, the status can go back to STATUS_WORK_WAITING and then come back here when we have it and the work is going to be continued

STATUS_WORK_FINISHED = u'finished'

work has been finished, but no sale has been created yet. Work orders with this status will be displayed in the till/pos applications and it’s possible to create a sale from them.

STATUS_DELIVERED = u'delivered'

a sale has been created, delivery and payment handled there

identifier

column: IdentifierCol

A numeric identifier for this object. This value should be used instead of Domain.id when displaying a numerical representation of this object to the user, in dialogs, lists, reports and such.

sellable

reference to: Sellable

a corresponding sellable for this equipament. Can be None if it is something that this shop does not sell

quantity

column: Int

If a sellable is specified, the number of items of this sellable this workorder is for

description

column: Unicode

description of the specific item brought by the client. This can be used to describe the equipament, if it is not one of the sellables available, or even to describe the serial number of the object.

defect_reported

column: Unicode

defect reported by the client

defect_detected

column: Unicode

defect detected by the quote_responsible

estimated_hours

column: Decimal

estimated hours needed to complete the work

estimated_cost

column: PriceCol

estimated cost of the work

estimated_start

column: DateTimeCol

estimated date the work will start

estimated_finish

column: DateTimeCol

estimated date the work will finish

open_date

column: DateTimeCol

date this work was opened

approve_date

column: DateTimeCol

date this work was approved (set by approve)

finish_date

column: DateTimeCol

date this work was finished (set by finish)

is_rejected

column: Bool

if the order was rejected by the other branch, e.g. when one branch sends the order in a work order package to another branch for execution and it sends it back because of something

branch

reference to: Branch

the branch where this order was created and responsible for it

execution_branch

reference to: Branch

the branch where the work’s execution was made. It’s automatically set by sending the order on a work order package

quote_responsible

reference to: Employee

the employee responsible for the defect_detected

execution_responsible

reference to: Employee

the employee responsible for the execution of the work

client

reference to: Client

the client, owner of the equipment

category

reference to: WorkOrderCategory

the work order category this work belongs

sale

reference to: Sale

the sale created after this work is finished

supplier_order

column: Unicode

Number of supplier order.

current_branch

reference to: Branch

the actual branch where the order is. Can differ from to another branch for execution

get_total_amount()[source]

Returns the total amount of this work order

This is the same as:

sum(item.total for item in :obj:`.order_items`)
add_sellable(sellable, price=None, quantity=1, batch=None)[source]

Adds a sellable to this work order

Parameters:
  • sellable – the sellable being added
  • price – the price the sellable will be sold when finishing this work order
  • quantity – the sellable’s quantity
  • batch – the batch this sellable comes from, if the sellable is a storable. Should be None if it is not a storable or if the storable does not have batches.
Returns:

the created work order item

is_items_totally_reserved()[source]

Check if this work order item’s are fully reserved

For a work order item to be fully synchronized, it’s WorkOrderItem.quantity should be equal to it’s WorkOrderItem.quantity_decreased

Returns:True if all is synchronized, False otherwise
is_in_transport()[source]

Checks if this work order is in transport

A work order is in transport if it’s current_branch is None. The transportation of the work order is done in a work order package

Returns:True if in transport, False otherwise
is_approved()[source]

Checks if this work order is approved

If the order is paused or in progress, it’s considered to be approved (obviously, the same applies to status after them, like finished and delivered).

Returns:True if the order is considered as approved, False otherwise.
is_finished()[source]

Checks if this work order is finished

A work order is finished when the work that needs to be done on it finished, so this will be True when WorkOrder.status is STATUS_WORK_FINISHED and STATUS_DELIVERED

is_late()[source]

Checks if this work order is late

Being late means we set an estimated finish date and that date has already passed.

can_cancel(ignore_sale=False)[source]

Checks if this work order can be cancelled

The order can be cancelled at any point, once it’s not finished (this is done by checking is_finished()) or its already cancelled

If the work order is related to a sale, the user cannot cancel it, and should cancel the sale instead.

Parameters:ignore_sale – Dont consider the related sale. This should only be used when the sale is being canceled
Returns:True if can be cancelled, False otherwise
can_approve()[source]

Checks if this work order can be approved

Returns:True if can be approved, False otherwise
can_pause()[source]

Checks if we can put the order on “waiting” state

Only orders with work in progress be put in that state.

Returns:True if can work, False otherwise
can_work()[source]

Checks if this order’s task can be worked

Note that the work needs to be approved before it’s task can be started to be worked.

Returns:True if can work, False otherwise
can_edit()[source]

Check if this work order can be edited

Returns:True if can edit, False otherwise
can_finish()[source]

Checks if this work order can finish

Note that the work needs to be started before you can finish.

Returns:True if can finish, False otherwise
can_close()[source]

Checks if this work order can delivery

Note that the work needs to be finished before you can deliver.

Also, all of it’s items need to be already decreased from the stock, that is, WorkOrderItem.quantity needs to be equal to WorkOrderItem.quantity.

Returns:True if can deliver, False otherwise
can_reopen()[source]

Checks if this work order can be re-opened

A finished or delivered order can be reopened.

Returns:True if it can, False otherwise
can_reject()[source]

Checks if the is_rejected flag can be set

Returns:True if it can, False otherwise
can_undo_rejection()[source]

Checks if the is_rejected flag can be unset

Returns:True if it can, False otherwise
reject(reason)[source]

Setter for the is_rejected flag

When setting the is_rejected flag to True, it should be done here since some additional logic (e.g. Registering a WorkOrderHistory) will be made together.

Parameters:reason – the explanation to why we are setting this flag
undo_rejection(reason)[source]

Unsetter for the is_rejected flag

When setting the is_rejected flag to False, it should be done here since some additional logic (e.g. Registering a WorkOrderHistory) will be made together.

Parameters:reason – an explanation to what was done to make this order not rejected anymore
cancel(reason=None, ignore_sale=False)[source]

Cancels this work order

Cancel the work order, probably because the client didn’t approve it or simply gave up of doing it.

All reserved items (the ones with WorkOrderItem.quantity_decreased > 0) will be returned to stock.

Parameters:reason – an explanation to why this order was cancelled
approve()[source]

Approves this work order

Approving means that the client has accepted the work’s quote and it’s cost and it can now start.

work()[source]

Set this orders state as “work in progress”

The execution_responsible started working on this order’s task and will finish sometime in the future.

Note that if the work has to stop for a while for some reason (e.g. lack of material, lack of labor, etc), one can call pause() to set the state properly and then call this again when the work can continue.

pause(reason)[source]

Set this orders state as “waiting”

This is used to indicate that the work has stopped for a while for a reason (e.g. lack of material, lack of labor, etc). When the work can continue call work()

Note: When comming from STATUS_OPENED, approve() must be used instead.

Parameters:reason – the reason explaining why this order was paused
finish()[source]

Finishes this work order’s task

The execution_responsible has finished working on this order’s task. It’s possible now to give the equipment back to the client and create a sale so we are able to deliver this order.

reopen(reason)[source]

Reopens the work order

This is useful if the order was finished but needs to be reopened for some reason. The state will be back to STATUS_WORK_IN_PROGRESS

Parameters:reason – the reason explaining why this order was reopened
close()[source]

Delivers this work order

This order’s task is done, the client got the equipment back and a sale was created for the work order items Nothing more needs to be done.

change_status(new_status, reason=None)[source]

Change the status of this work order

Using this function you can change the status is several steps.

Parameters:
  • new_status – the new status
  • reason – a reason for that status change. Only needed by some changes
Returns:

if the status was changed

Raises:

stoqlib.exceptions.InvalidStatus if the status cannot be changed

Raises:

stoqlib.exceptions.NeedReason if the change needs a reason to happen

classmethod find_by_sale(store, sale)[source]

Returns all work orders associated with the given sale.

Parameters:sale – The sale used to filter the existing work orders
Resturn:An iterable with all work orders:
Return type:resultset
class stoqlib.domain.workorder.WorkOrderHistory(*args, **kwargs)[source]

Bases: stoqlib.domain.base.Domain

Holds information about changes for work orders

Every time something happens to a work order, it should be logged here, e.g. When it is opened, when it is approved, when it sent in a work order package to another branch, etc.

date

column: DateTimeCol

the date and time that this event happened

what

column: Unicode

the “what has changed”. e.g. “Status”, “Current branch”

old_value

column: Unicode

the old value for the what

new_value

column: Unicode

the new value for the what

notes

column: Unicode

some notes about the change. Usually used for a more detailed explanation about the what

user

reference to: LoginUser

the login user that made this change

work_order

reference to: WorkOrder

the work order where this change happened

classmethod add_entry(store, workorder, what, old_value=None, new_value=None, notes=None)[source]

Add an entry to the history

Parameters:
  • store – a store
  • workorder – the work order where this change happened
  • what – the description of what has changed. See what for more information
  • old_value – the what’s old value. See old_value for more information
  • new_value – the what’s new value. See new_value for more information
Returns:

the newly created WorkOrderHistory

class stoqlib.domain.workorder.WorkOrderView[source]

Bases: stoqlib.database.viewable.Viewable

A view for work orders

This is used to get the most information of a work order without doing lots of database queries.

work_order

the work order object

alias of WorkOrder

category

the work order category object

alias of WorkOrderCategory

client

the client object

alias of Client

sale

the sale associated with this workorder

alias of Sale

classmethod find_pending(store, start_date=None, end_date=None)[source]

Find results for this view that are pending (not delivered yet)

Parameters:
  • store – the store that will be used to find the results
  • start_date – if not None, the results will be filtered to show only the ones with estimated_finish greater than it
  • end_date – if not None, the results will be filtered to show only the ones with estimated_finish lesser than it
Returns:

the matching views

Return type:

a sequence of WorkOrderWithPackageView

class stoqlib.domain.workorder.WorkOrderWithPackageView[source]

Bases: stoqlib.domain.workorder.WorkOrderView

A view for work orders in a work order package

This is the same as WorkOrderView, but package information is joined together

classmethod find_by_package(store, package)[source]

Find results for this view that are in the package

Parameters:
  • store – the store that will be used to find the results
  • package – the work order package used to filter the results
Returns:

the matching views

Return type:

a sequence of WorkOrderWithPackageView

class stoqlib.domain.workorder.WorkOrderApprovedAndFinishedView[source]

Bases: stoqlib.domain.workorder.WorkOrderView

A view for approved and finished work orders

This is the same as WorkOrderView, but only approved and finished orders are showed here.

class stoqlib.domain.workorder.WorkOrderFinishedView[source]

Bases: stoqlib.domain.workorder.WorkOrderView

A view for finished work orders that still dont have a sale

This viewable should be used only to find what workorders still dont have a sale and can be delivered (ie, they can have the sale created).

This is the same as WorkOrderView, but only finished orders are showed here.

class stoqlib.domain.workorder.WorkOrderPackageView[source]

Bases: stoqlib.database.viewable.Viewable

A view for work order packages

This is used to get the most information of a work order package without doing lots of database queries.

package

the work order package object

alias of WorkOrderPackage

class stoqlib.domain.workorder.WorkOrderPackageSentView[source]

Bases: stoqlib.domain.workorder.WorkOrderPackageView

A view for sent work order packages

This is the same as WorkOrderPackageView, but only sent orders are showed here.

class stoqlib.domain.workorder.WorkOrderHistoryView[source]

Bases: stoqlib.database.viewable.Viewable

A view for WorkOrderHistoryView

history

the WorkOrderHistory object

alias of WorkOrderHistory

classmethod find_by_work_order(store, workorder)[source]

Find results for this view that references workorder

Parameters:
  • store – the store that will be used to find the results
  • package – the work order used to filter the results
Returns:

the matching views

Return type:

a sequence of WorkOrderHistoryView