jobcalc package¶
Submodules¶
jobcalc.cli module¶
jobcalc.config module¶
-
jobcalc.config.CURRENCY_FORMAT= 'USD'¶ The currency format to use when formatting a currency string. Should be a valid format used by
babel.numbers.format_currency.This can be set by the
JOBCALC_CURRENCY_FORMATenvironment variable. Defaults to'USD'.
-
class
jobcalc.config.Config(*, seperator=None, divider=None, rate=None, default_hours=None, margins=None, discounts=None, deductions=None, debug=None)[source]¶ Bases:
objectThe main config class that holds common varibles that are used to set up a calculator instance. These variables can either be passed in or retrieved from their corresponding environment variable.
Parameters: - seperator (
Optional[str]) – A seperator used to seperate key, value pairs parsed from an environment variable. Defaults to';'. Can be set byJOBCALC_SEPERATOR. (ex. ‘key1:value1;key2:value2;’) - divider (
Optional[str]) – Used to divide a key, value pair parsed from an environment variable. Defaults to':'. Can be set byJOBCALC_DIVIDER. (ex. ‘key1:value1’) - rate (
Optional[str]) – An hourly rate to be used in calculations. Defaults to ‘0’. Can be set byJOBCALC_RATE. - default_hours (
Optional[str]) – Hours toalwaysbe used for a calculation. Defaults to'0'. Can be set byJOBCALC_DEFAULT_HOURS. - margins (
Optional[Dict]) – A dict with named margins that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_MARGINSusing theseperatoranddividerto distinguish the key, value pairs. All values will get converted to aPercentageto be used as a profit margin. (ex: ‘fifty:50;forty:40’). - discounts (
Optional[Dict]) – A dict with named discounts that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_DISCOUNTSusing theseperatoranddividerto distinguish the key, value pairs. All values will get converted to aPercentageto be used as a percentage discount. (ex. ‘standard:10;deluxe:15’). - deductions (
Optional[Dict]) – A dict with named deductions that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_DEDUCTIONSusing theseperatoranddividerto distinguish key, value pairs. All values will get converted to aCurrencyto be used as a monetary deduction. (ex. ‘one:100;two:200’) - debug (
Optional[bool]) – A bool to put calculator into debug mode. Defaults toFalse.
Return type: None
- seperator (
-
jobcalc.config.ENV_PREFIX= 'JOBCALC'¶ The prefix to use for all environment variables.
-
jobcalc.config.LOCALE= 'en_US'¶ The default locale to set for formatting a currency string. Should be a valid locale used by
babel.numbers.format_currency.This can be set by the
JOBCALC_CURRENCY_FORMATenvironment variable. Defaults to'en_US'.
-
class
jobcalc.config.TerminalConfig(*, prompt=None, suppress=None, formula=None, allow_empty=None, prompt_seperator=None, **kwargs)[source]¶ Bases:
jobcalc.config.ConfigExtends
Configwith command line interface specific variables.Note
Boolean envrionment variable’s will be determined as
Truewith any of the following values. Anything else isFalse.- ‘True’
- ‘TrUe’ (any combination upper-lower works)
- ‘1’
Parameters: - prompt (
Optional[bool]) – A bool that ifTruewill call theprompt-allsub-command if the main (job-calc) command is called without a sub-command. IfFalsethen we show the help doc. Default isFalse. Can be set byJOBCALC_PROMPT. - suppress (
Optional[bool]) – A bool that ifTruewill suppress the detailed table output for any commands called. Default isFalse. Can be set byJOBCALC_SUPPRESS. - formula (
Optional[bool]) – A bool that ifTruewill show the formula string for any commands called. Default isFalse. Can be set byJOBCALC_FORMULA. - allow_empty (
Optional[bool]) – A bool that ifTruewill not prompt for empty values before performing any calculations. Can be set byJOBCALC_ALLOW_EMPTY. - prompt_seperator (
Optional[str]) – A string that is used to seperate items that can be multiple values if prompted for. Defaults to' '. Can be set byJOBCALC_PROMPT_SEPERATOR.
Return type: None
-
jobcalc.config.env_strings= _EnvStrings(seperator='JOBCALC_SEPERATOR', divider='JOBCALC_DIVIDER', rate='JOBCALC_RATE', default_hours='JOBCALC_DEFAULT_HOURS', margins='JOBCALC_MARGINS', discounts='JOBCALC_DISCOUNTS', deductions='JOBCALC_DEDUCTIONS', prompt='JOBCALC_PROMPT', allow_empty='JOBCALC_ALLOW_EMPTY', suppress='JOBCALC_SUPPRESS', formula='JOBCALC_FORMULA', prompt_seperator='JOBCALC_PROMPT_SEPERATOR', config='JOBCALC_CONFIG')¶ A named tuple that holds all the commonly used environment variables. Primarily used to avoid typo’s and make an IDE work better.
-
jobcalc.config.from_yaml(path, cls=<class 'jobcalc.config.TerminalConfig'>)[source]¶ Create a
ConfigorTerminalConfigfrom a yaml file.Parameters: - path (
str) – The path to the file. - cls (
Config) – The class to return. Default isTerminalConfig
Raises: FileNotFoundError – If the path is not a valid file.
Return type: - path (
jobcalc.core module¶
-
class
jobcalc.core.BaseCalculator(costs=[], margins=[], discounts=[], deductions=[], ignore_margins=None)[source]¶ Bases:
objectThe
BaseCalculatorclass know’s how to takecosts, amargin, adiscount(percentage discount), anddeductionsand calculate a total with those items.All items can be either single or iterables of items, but all get stored as a list. And the sum of that list of items makes up the total for a given item.
Parameters: - costs (
Iterable) – Either a single item or list of items that can be converted to aCurrency, used as the subtotal for a calculation. - margins (
Iterable) – An item or list of items that can be converted to aPercentage, used as the profit margin for the calculation. - discounts (
Iterable) – An item or list of items that can be converted to aPercentage, used as a percentage discount for the calculation. - deductions (
Iterable) – An item or list of items that can be converted to aCurrency, used as monetary deduction for the calculation. - ignore_margins (
Optional[bool]) – A bool determining whether to ignore margins if any of the items incostsare otherCalculatorinstances. Defaults toFalse.
Return type: None
-
static
calculate(*args, **kwargs)[source]¶ Just attaches the
calculate()function as a staticmethod. This is the method called intotal(), so if a sub-class would like to implement a custom calculation, they can override this method.Return type: Currency
-
ctx(ignore_margins=None)[source]¶ A context manager that yields a
Contextthat is properly set up to be used in a calculation.Parameters: ignore_margins ( Optional[bool]) – A bool to determine whether to ignore margins in thesubtotalif ourcostsinclude otherCalculatorinstances. This will fallback toself.ignore_marginsif not supplied.Return type: Context
-
subtotal(ignore_margins=None)[source]¶ Calculate the subtotal of the
costs. This is used becausecostscan also consist of other calculators, so we call eithertotal()orsubtotal()accordingly on those items.Parameters: ignore_margins ( Optional[bool]) – A boolean, ifTrue, then we call subtotal on child calculators, if it’sFalsethen we call total. We fallback toself.ignore_marginsif this is not passed in.Return type: Currency
- costs (
-
class
jobcalc.core.Calculator(*, formatters=[], hours=[], rate=None, config=None, **kwargs)[source]¶ Bases:
jobcalc.core.BaseCalculatorExtends
BaseCalculator. Adds the ability to attach formatters, torendera formatted output. Addshoursand arateoption. Thehourswill be summed and multiplied by therateand added to thesubtotalof the job. Also adds the ability to pass in aConfiginstance for common configuration of aCalculator.Parameters: - formatters (
Iterable) – A single or iterable ofBaseFormatter‘s to format the output. - hours (
Iterable) – A single or iterable of items that can be converted to adecimal.Decimal. - rate (
Union[str,int,None]) – An single item that can be converted to adecimal.Decimalthat represents an hourly rate. - config (
Optional[Config]) – AConfiginstance to use for values, either set or loaded from the environment.
Return type: None
-
ctx(strict=False)[source]¶ Return a properly configured
Contextto be used.Note
This can also raise errors if
hoursorratecan not be converted to adecimal.Decimal. Most common error will be adecimal.InvalidOperationerror.Parameters: strict ( bool) – IfTruean error will be raised ifhoursare set on an instance, but noratehas been set. Default isFalseRaises: HourlyRateError – If strictisTrueand no hourly rate has been set.Return type: Context
-
rate¶ Used as the hourly rate for a calculator. Defaults to ‘0’. This will not accept anything that is not greater or equal to 0 or anything that can not be converted to a
decimal.Decimal.
-
render(seperator='nn')[source]¶ Return a string output of all the formatters for an instance. Joined by the seperator.
If no formatters have been set, then we fall back to :py:class`BasicFormatter`, which will just output the
total()as a formatted currency string.Parameters: seperator ( str) – A string to use as the seperator. Defaults to a double new-line.Return type: str
-
subtotal(**kwargs)[source]¶ Add’s sum of
costs+ (rate*hours) for the subtotal.Parameters: kwargs – Get passed to super‘s subtotal method.Return type: Currency
-
update(updates=None, append=True, **kwargs)[source]¶ A convenience method to update the common items of an instance.
Parameters: - updates (
Optional[Dict]) – Optional dict used for the updates where the keys are attribute names and the values are the items to set for the attribute. - append (
bool) – A bool, ifTruethen we add the items to the existing attribute, ifFalsethen we remove any items already set with the new items. Default isTrue. - kwargs – Same as
updates.
Example:
>>> calc = Calculator() >>> calc.update({'margins': '50'}) >>> assert calc.margins[-1] == '50' # True >>> calc.update(costs='123') >>> assert calc.costs[-1] == '123' # True
Return type: None - updates (
- formatters (
-
class
jobcalc.core.ColorKey(margins, discounts, hours, rate, deductions, costs)¶ Bases:
tupleA namedtuple that can be used to declare colors to be used when prompting for user input.
Note
See
colorclassfor valid colors.Parameters: - margins – Color when prompting for margin.
- discounts – Color when prompting for discounts.
- hours – Color when prompting for hours.
- rate – Color when prompting for rate.
- deductions – Color when prompting for deductions.
- costs – Color when prompting for costs.
-
costs¶ Alias for field number 5
-
deductions¶ Alias for field number 4
-
discounts¶ Alias for field number 1
-
hours¶ Alias for field number 2
-
margins¶ Alias for field number 0
-
rate¶ Alias for field number 3
-
class
jobcalc.core.Context(subtotal, margin, discount, deduction)¶ Bases:
tupleA namedtuple that represents the args for the
calculate()function.If these values are set properly then you can call
calculate(*context). and the values will be unpacked in the correct order.Parameters: - subtotal – The subtotal for the calculation.
- margin – The margin for the calculation
- discount – The percentage discount for the calculation.
- deduction – The monetary deduction for the calculation.
Example:
>>> ctx = Context(subtotal='123', margin='50', discount='10', ... deduction='0') >>> calculate(*ctx).formatted_string() '$221.40'
-
deduction¶ Alias for field number 3
-
discount¶ Alias for field number 2
-
margin¶ Alias for field number 1
-
subtotal¶ Alias for field number 0
-
jobcalc.core.DEFAULT_COLOR_KEY= ColorKey(margins='blue', discounts='yellow', hours='magenta', rate='cyan', deductions='red', costs='green')¶ The default colors to fallback to if none are declared for a calculator.
-
jobcalc.core.PromptResponse¶ A namedtuple that represents the response to prompting for user input.
Parameters: - value – The parsed value from the user input.
- multiple_heading_displayed – A boolean that indicates if we displayed the multiple value heading during a prompt.
- single_heading_displayed – A boolean that indicates if we displayed the single value heading during a prompt.
alias of
PromptRespone
-
class
jobcalc.core.TerminalCalculator(*, colors=None, **kwargs)[source]¶ Bases:
jobcalc.core.CalculatorExtends
Calculatorfor use in the command line interface.Parameters: - colors (
Optional[Iterable]) – A 6 tuple orColorKeyof colors - kwargs – Extra args to pass to :py:class:
Calculator
Return type: None
-
is_empty(attr)[source]¶ Determines if an attribute is considered empty, or equal to ‘0’.
If there are default hours set by an environment variable, then hours are considered empty if the sum of (hours - default_hours) are ‘0’.
Parameters: attr ( str) – The name of the attribute to check.Return type: bool
-
key_for_prompt(prompt)[source]¶ - A helper to return the correct key (attribute name) to use for
a prompt.
This is the opposite of the
normalize()method. In which it ensures the return value is pluralized for most cases as that’s the key that can be used in theupdate()method for an instance.This is helpful when making multiple prompts that save their values in a dict, that later is used to update the attributes on an instance.
Parameters: prompt ( str) –The attribute the prompt is for.
Example:
>>> calc = TerminalCalculator() >>> calc.key_for_prompt('discount') 'discounts' >>> calc.key_for_prompt('rates') # handle accidental plural's 'rate'
Return type: str
-
normalize(attr)[source]¶ A helper to normalize an attribute name, as most context’s expect the name to not be pluralized (except
hours), so we chop off the ‘s’ if applicable.This is also helpful if using
prompt_for()method, to make sure the name for the prompt is correct.Parameters: attr ( str) – The attribute name to normalize.Return type: str
-
prompt_all()[source]¶ Prompt the user for all input’s, also showing the current value, and add the values to this instance appropriately.
Return type: None
-
prompt_for(prompt, **kwargs)[source]¶ A context manager that prompt’s a user for input, and yields a
PromptResponse.Valid prompts are ‘margin’, ‘discount’, ‘deduction’, ‘cost’, ‘hours’, and ‘rate’. We will also do/ call the right method if use the plural form of prompt (ex. ‘margins’).
Parameters: - prompt (
str) – The attribute to prompt for (ex. ‘margin’) - kwargs – They get passed to the prompt_for_{prompt} command.
Example:
>>> calc = TerminalCalculator() >>> with calc.prompt_for('margin', default='0') as result: ... calc.update(margins=result.value)
Return type: PromptRespone- prompt (
-
prompt_for_cost(default=None, *, type=<jobcalc.param_types.CostsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for cost(s) for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
-
prompt_for_deduction(default=None, *, type=<jobcalc.param_types.DeductionsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for deduction(s) for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
-
prompt_for_discount(default=None, *, type=<jobcalc.param_types.DiscountsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for discount(s) for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
-
prompt_for_empty()[source]¶ Prompt the user for all the values that are determined to be empty or ‘0’, and add them to instance appropriately.
Return type: None
-
prompt_for_hours(default=None, *, type=<class 'decimal.Decimal'>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for hour(s) for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
-
prompt_for_margin(default=None, *, type=<jobcalc.param_types.MarginsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for margin(s) for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
-
prompt_for_rate(default=None, *, type=<class 'decimal.Decimal'>, is_single=True, current=None, display_multiple_header=True, display_single_header=True)¶ Prompt the user for a rate for the calculation.
Parameters: - default – Optional value to use as default for no input.
- current – Optional value to display as the current value.
- is_single – If input is single or accepts multiple values.
- type – A type to convert the value(s) to.
- display_multiple_header – If
Truethen show the multiple value header. - display_single_header – If
Truethen show the single value header.
Return type: PromptResponse
- colors (
-
jobcalc.core.calculate(subtotal='0', margin='0', multiplier='0', deduction='0')[source]¶ Calculates a total based on the parameters. Returned as a
Currency.Parameters: - subtotal (
Union[Currency,str]) – An item that can be converted to aCurrencyto be used for the calculation. This would be the sum of all the job costs, materials, hours, etc. - margin (
Union[Percentage,str]) – An item that can be converted to aPerentageto be used as the profit margin for the calculation. Default is 0. - multiplier (
Union[Percentage,str]) – An item that can be converted to aPercentageto be used as a percentage discount in the calculation. This discount comes off after the profit margin has been calculated. Default is 0. - deduction (
Union[Currency,str]) – An item that can be converted to aCurrencyto be used as a monetary discount in the calculation. This comes off after the profit margin has be calculated and any other percentage discounts have been taken off.
Return type: - subtotal (
jobcalc.exceptions module¶
-
exception
jobcalc.exceptions.EnvDictNotFound(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcErrorRaised if an env string is expected to return a dict, but was not found.
Return type: None
-
exception
jobcalc.exceptions.HourlyRateError(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,ValueErrorRaised if an hourly rate is expected, but not found or 0, during calculations.
Return type: None
-
exception
jobcalc.exceptions.InvalidEnvString(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if parsing an environment string into a dict fails.
Return type: None
-
exception
jobcalc.exceptions.InvalidFormatter(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,AttributeErrorRaised if an invalid formatter is found during calculations.
Return type: None
-
exception
jobcalc.exceptions.JobCalcError(msg=None)[source]¶ Bases:
ExceptionBase exception used by the app. All custom exceptions should inherit from this class.
Return type: None
-
exception
jobcalc.exceptions.NotCallableError(type=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if an expected type is supposed to be callable, but is not.
Return type: None
-
exception
jobcalc.exceptions.NotIterableError(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if an iterable is expected, but not recieved.
Return type: None
-
exception
jobcalc.exceptions.PercentageOutOfRange(value)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,ValueErrorRaised if percentage is above 100 or less than 0.
Return type: None
jobcalc.formatters module¶
-
class
jobcalc.formatters.BaseFormatter[source]¶ Bases:
objectAll formatter’s should sub-class this object, and override the
render()method.-
static
colorize(color)[source]¶ If an item is a
CurrencyorPercentage, then call it’sformatted_stringmethod, before colorizing the value.Parameters: - item (
Any) – A string, Currency, or Percentage to colorize. - color (
str) – The color to use on the item.
Return type: Color- item (
-
static
render()[source]¶ The method all sub-classes should override to render a calculator.
Raises: NotImplementedError – If a sub-class does not implement this method. Return type: str
-
static
totaled_ctx()[source]¶ A context manager that yields the
TotaledContextfor a calculator.Return type: TotaledContext
-
static
-
class
jobcalc.formatters.BasicFormatter[source]¶ Bases:
jobcalc.formatters.BaseFormatterA basic formatter that renders the total as a formatted string.
-
class
jobcalc.formatters.ColorContext(subtotal, margin, discount, deduction, total)¶ Bases:
tupleA named tuple used to hold colors for items when rendered.
Parameters: - subtotal – Color for subtotal’s
- margin – Color for margin’s
- discount – Color for discount’s
- deduction – Color for deduction’s
- total – Color for total’s
-
deduction¶ Alias for field number 3
-
discount¶ Alias for field number 2
-
margin¶ Alias for field number 1
-
subtotal¶ Alias for field number 0
-
total¶ Alias for field number 4
-
jobcalc.formatters.DEFAULT_COLORS= ColorContext(subtotal='magenta', margin='blue', discount='yellow', deduction='red', total='green')¶ Default colors to use as the
ColorContext.
-
jobcalc.formatters.DEFAULT_FORMULA_STRING= '\ncolor key: {header}\n\n\n{subtotal_string}\n\n(\n (({subtotal} / (1 - {margin}) * (1 - {discount})) - {deduction}) = {total}\n)\n'¶ A basic formula string to be formatted and rendered, to show the formula for a calculation.
-
class
jobcalc.formatters.FormulaFormatter(*colors, *, formula_string=None, no_color=False, title='FORMULA')[source]¶ Bases:
jobcalc.formatters.BaseFormatterPrints the formula used for the calculations.
Parameters: - colors – A 5 tuple or
ColorContextof strings that can be used by to convert an item to acolorclass.Color. Defaults to (subtotal=’magenta’, margin=’blue’, discount=’yellow’, deduction=’red’, total=’green’). - formula_string (
Optional[str]) – A string to use for the format. This should be a a string that we callformat, that accepts kwargs (header, subtotal, margin, discount, deduction, and total). Defaults toDEFAULT_FORMULA_STRING. - no_color (
bool) – Turns colored output off. - title (
str) – Title to display before the output.
Raises: TypeError – If colors is not a 5 tuple.
Return type: None
- colors – A 5 tuple or
-
class
jobcalc.formatters.TerminalFormatter(*colors, *, title='DETAILED', no_colors=False, color_header=False)[source]¶ Bases:
terminaltables.ascii_table.AsciiTable,jobcalc.formatters.BaseFormatterA
terminaltables.AsciiTable, that supports colors and a title.Parameters: - colors – A 5 tuple or
ColorContextof strings that can be used by to convert an item to acolorclass.Color. Defaults to (subtotal=’magenta’, margin=’blue’, discount=’yellow’, deduction=’red’, total=’green’). - title (
str) – A title for the table. Defaults to'DETAILED'. If you do not want a title, then this can be set toNone - no_colors (
bool) – IfTrue, turns off colored output for the table. Default isFalse. - color_header (
bool) – IfTruethen colorize the header as well. Default isFalse.
- colors – A 5 tuple or
-
class
jobcalc.formatters.TotaledContext(subtotal, margin, discount, deduction, total)¶ Bases:
tupleHolds all the values to be rendered by a formatter.
Parameters: - subtotal – The subtotal of all the costs, hours, etc. for a calculation.
- discount – The sum of all the percentage discounts for a calculation.
- deduction – The sum of all the monetary deductions for a calculation.
- total – The total of the calculation.
-
deduction¶ Alias for field number 3
-
discount¶ Alias for field number 2
-
margin¶ Alias for field number 1
-
subtotal¶ Alias for field number 0
-
total¶ Alias for field number 4
jobcalc.param_types module¶
-
class
jobcalc.param_types.BaseCurrencyType[source]¶ Bases:
click.types.ParamTypeA custom
click.ParamTypeused to convert values passed on the command line toCurrencyinstances.-
convert(value, param, ctx)[source]¶ The method that does the actual conversion of values. This method is called by
clickduring parsing of input values.Parameters: - value (
str) – The value(s) to be converted. These can be either a string, or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: - value (
-
-
class
jobcalc.param_types.BasePercentageType[source]¶ Bases:
click.types.ParamTypeA custom
click.ParamTypeused to convert values passed on the command line toPercentageinstances.-
convert(value, param, ctx)[source]¶ The method that does the actual conversion. This method is called directly from
clickduring parsing of input values.Parameters: - value (
str) – A single string or iterable of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: - value (
-
-
class
jobcalc.param_types.ConfigType[source]¶ Bases:
click.types.ParamType-
convert(value, param, ctx)[source]¶ Return type: TerminalConfig
-
name= 'config'¶
-
-
class
jobcalc.param_types.CostsType[source]¶ Bases:
jobcalc.param_types.BaseCurrencyTypeA
BaseCurrencyTypethat is used to convert command line values toCurrencyinstances.Values can either be single items or multiples seperated
';', if the input is during an option to a command line command or' 'if the input is during a prompt. These can be changed via environment variables. Seeconfigmodule for more information.-
convert(value, param, ctx)[source]¶ Parses and converts value(s) to
Currencyinstance(s).Parameters: - value (
Union[str,Tuple[str]]) – A string or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: - value (
-
name= 'cost'¶
-
-
class
jobcalc.param_types.Currency[source]¶ Bases:
decimal.DecimalA
Decimalsub-class that knows how to handle currency for our app. Adds aformatted_stringmethod to represent a currency instance.Currencywill convert any negative numbers to a positive number, which is what is required by our calculations.Note
When performing any operations (like addition, multiplication, etc.) to a
Currency, then the new value will need to be converted back to aCurrencyfor theformatted_stringmethod to work.-
formatted_string()[source]¶ Return a formatted currency string. This method uses
babel.numbers.format_currencyusing theconfig.CURRENCY_FORMATandconfig.LOCALEvariables that are set by the environment or default values. (‘USD’, ‘en_US’).Example:
>>> Currency('1000').formatted_string() '$1,000.00'
Return type: str
-
-
class
jobcalc.param_types.DeductionsType[source]¶ Bases:
jobcalc.param_types.BaseCurrencyTypeA
BaseCurrencyTypethat is used to convert command line values toCurrencyinstances.Values can either be single items or multiples seperated
';', if the input is during an option to a command line command or' 'if the input is during a prompt. These can be changed via environment variables. Seeconfigmodule for more information.-
convert(value, param, ctx)[source]¶ Parses and converts value(s) to
Currencyinstance(s).Parameters: - value (
Union[str,Tuple[str]]) – A string or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: - value (
-
name= 'deduction'¶
-
-
class
jobcalc.param_types.DiscountsType[source]¶ Bases:
jobcalc.param_types.BasePercentageTypeA
BasePercentagTypethat is used to convert command line values toPercentageinstances.Values can either be single items or multiples seperated
';', if the input is during an option to a command line command or' 'if the input is during a prompt. These can be changed via environment variables. Seeconfigmodule for more information.-
convert(value, param, ctx)[source]¶ Parses and converts value(s) to
Percentageinstance(s).Parameters: - value (
Union[str,Tuple[str]]) – A string or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: Union[Percentage,Tuple[Percentage]]- value (
-
name= 'discount'¶
-
-
class
jobcalc.param_types.HoursType[source]¶ Bases:
click.types.ParamTypeA
click.ParamTypethat is used to convert command line values todecimal.Decimalinstances.Values can either be single items or multiples seperated
';', if the input is during an option to a command line command or' 'if the input is during a prompt. These can be changed via environment variables. Seeconfigmodule for more information.-
convert(value, param, ctx)[source]¶ Parses and converts value(s) to
decimal.Decimalinstance(s)Parameters: - value (
Union[str,Tuple[str]]) – A string or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: Union[Decimal,Tuple[Decimal]]- value (
-
name= 'hours'¶
-
-
class
jobcalc.param_types.MarginsType[source]¶ Bases:
jobcalc.param_types.BasePercentageTypeA
BasePercentagTypethat is used to convert command line values toPercentageinstances.Values can either be single items or multiples seperated
';', if the input is during an option to a command line command or' 'if the input is during a prompt. These can be changed via environment variables. Seeconfigmodule for more information.-
convert(value, param, ctx)[source]¶ Parses and converts value(s) to
Percentageinstance(s).Parameters: - value (
Union[str,Tuple[str]]) – A string or tuple of strings to convert. - param (
Any) – The command line parameter this attached to. - ctx (
Any) – The command line context.
Return type: Union[Percentage,Tuple[Percentage]]- value (
-
name= 'margin'¶
-
-
class
jobcalc.param_types.Percentage[source]¶ Bases:
decimal.DecimalA
Decimalsub-class, that handle’s percentages correctly for our app. Adds aformatted_stringmethod for a percentage.A percentage for our purposes can either be a number between 0 and 100. If the number is between 0 and 1, then it is used as the percentage. If it is above 1 and less than 100, we divide the number by 100 to create or percentage.
Raises: PercentageOutOfRange – If the value is a negative number or 100 or above. Note
When performing any operations (like addition, multiplication, etc.) to a
Percentage, then the new value will need to be converted back to aPercentagefor theformatted_stringmethod to work.Example:
>>> p = Percentage('10') >>> repr(p) "Percentage('0.1')" >>> x = Percentage('10') + Percentage('5') >>> repr(x) "Decimal('0.15')" >>> x.formatted_string() Traceback ... AttributeError: 'decimal.Decimal' object has no attribute 'formatted_string' >>> x = Percentage(Percentage('10') + Percentage('5')) >>> x.formatted_string() '15.0%'
10% Example:
>>> Percentage('10').formatted_string() '10.0%' >>> Percentage('.1').formatted_string() '10.0%' >>> Percentage( ... Percentage('10').formatted_string()).formatted_string()) '10.0%'
-
jobcalc.param_types.check_env_dict(env_var=None, strict=None)[source]¶ A decorator to check iterate over the first arg, checking if the values map to a key in an
env_dict, returning it’s value if so. Parsing the first arg to a true value. (either the value for theenv_dictkey or the value itself, if not a key in theenv_dict.This decorator allows command line options to use named parameter’s that are mapped to values in an
env_dict.This will work the same whether wrapping a method attached to a class or a stand alone function.
Parameters: - env_var (
Optional[str]) – The name of theenv_dictto check in. - strict (
Optional[bool]) – A bool, ifTruethen an error will be raised if anenv_dictis not found forenv_var. Default isNone(False).
Raises: EnvDictNotFound – If
strictisTrueand anenv_dictwas not found forenv_var.Example:
$ export JOBCALC_DISCOUNTS='standard:5;deluxe:10;premium:15'
>>> @check_env_dict('JOBCALC_DISCOUNTS') ... def decorated(value): ... print(value) >>> decorated('standard') '5' >>> decorated('not_in_dict') 'not_in_dict'
- env_var (
-
jobcalc.param_types.parse_input_value(wrapped, instance, args, kwargs)[source]¶ A decorator to parse the first arg with
parse_input_string, before sending on to the wrapped function/method. This method allows multiple values to be passed into a command line option as a single string, split on the default seperator';'.Works properly with methods attached to classes or stand alone functions.
Example:
>>> @parse_input_value ... def decorated(values): ... print(values) >>> decorated('123;456;') ('123', '456') >>> class Parsed(object): ... @parse_input_value ... def decorated(self, values): ... print(values) >>> Parsed().decorated('123;456') ('123', '456')
Note
This method uses
parse_input_stringmethod which always returns a tuple, so the parsed value that get’s passed to the wrapped method will always be a tuple, which can be of length 1, if there wasn’t any values to split in the input string.Example:
>>> @parse_input_value ... def decorated(value): ... print(value) >>> decorated('123') ('123', )
jobcalc.utils module¶
-
jobcalc.utils.bool_from_env_string(string)[source]¶ Convert a string recieved from an environment variable into a bool.
‘true’, ‘TRUE’, ‘TrUe’, 1, ‘1’ = True
Everything else is False.
Parameters: string ( str) – The string to convert to a bool.Return type: bool
-
jobcalc.utils.colorize(string, color)[source]¶ Returns a colorized string.
See also
colorclassParameters: - string (
str) – The string to colorize. - color (
str) – The color for the string.
Example:
>>> colorize('some string', 'red') Color('[31msome string[39m')
Return type: Color- string (
-
jobcalc.utils.dict_from_env_string(string, seperator=None, divider=None, type=None)[source]¶ Creates a dict from a string, using a
seperatorto seperate the items and adividerto distinguish key, value pairs.Parameters: - string (
Union[str,dict]) – The string to create the dict from. - seperator (
Optional[str]) – The seperator to use to seperate items in the string. Defaults to';'. This can also be set by the environment variableJOBCALC_SEPERATOR. - divider (
Optional[str]) – Divides key, value pairs. Defaults to':'. This can also be set by the environment variableJOBCALC_DIVIDER. - type (
Optional[Callable]) – Callback to use to convert all the values to a certain type.
Example:
>>> dict_from_env_string('standard:5;deluxe:10;premium:15') {'standard': '5', 'deluxe': '10', 'premium': '15'} >>> dict_from_env_string('standard:5;deluxe:10;premium:15', ... type=Percentage) {'standard': Percentage('0.5'), 'deluxe': Percentage('0.1'), 'premium': Percentage('0.15')}
Return type: Dict- string (
-
jobcalc.utils.ensure_callback(callback, error=True)[source]¶ Ensures that a callback is
callable. Either raising errors or returning a valid callback.If
errorisFalseand the callback is not callable, then we return a callable that takes a single value as input and returns that same value.Parameters: - callback (
Callable) – The callback to check. - error (
bool) – IfTrue, raise aNotCallableErrorif the callback is not callable. IfFalsewe will return a valid callback, rather than error. Default isTrue.
Raises: NotCallableError – If the callback is not callable and
errorisTrue.Return type: Callable- callback (
-
jobcalc.utils.flatten(*args, *, ignoretypes=<class 'str'>)[source]¶ A generator to flatten iterables, containing single items and possible other iterables into a single iterable.
Parameters: - args – Any value to check for sub-lists (iterable) and flatten.
- ignoretypes (
Any) – A type or tuple of types to ignore (not flatten). Default isstr.
Example:
>>> list(flatten([1, 2, [3, 4], [5, [6, 7], [8, 9]]])) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> mylist = ['1', '2', [3, ['4'], ['5 is alive', 6], 7], [8, '9.0']] >>> list(flatten(mylist)) ['1', '2', 3, '4', '5 is alive', 6, 7, 8, '9.0'] >>> list(flatten([1, 2, (3, 4, 5)], ignoretypes=tuple)) [1, 2, (3, 4, 5)]
-
jobcalc.utils.parse_input_string(string, seperator=';', convert=None)[source]¶ Parses an input string that could have multiple values passed in from the command line.
Note
This method always returns a tuple, which can be of length 1 or more.
Parameters: - string (
str) – The input string to parse. - seperator (
str) – The seperator used to seperate items. Defaults to';'. - convert (
Optional[Callable]) – A callback that can be used to convert all the parsed values to a type. This can be acallablethat recieves a single value and returns a single value, or we can also handleclick.ParamType‘s. Default isNone.
Example:
>>> parse_input_string('123;456') ('123', '456') >>> parse_input_string('123;456', convert=Currency) (Currency('123'), Currency('456')) >>> parse_input_string('123') ('123', )
Return type: Tuple[Any]- string (
Module contents¶
-
jobcalc.bool_from_env_string(string)[source]¶ Convert a string recieved from an environment variable into a bool.
‘true’, ‘TRUE’, ‘TrUe’, 1, ‘1’ = True
Everything else is False.
Parameters: string ( str) – The string to convert to a bool.Return type: bool
-
jobcalc.ensure_callback(callback, error=True)[source]¶ Ensures that a callback is
callable. Either raising errors or returning a valid callback.If
errorisFalseand the callback is not callable, then we return a callable that takes a single value as input and returns that same value.Parameters: - callback (
Callable) – The callback to check. - error (
bool) – IfTrue, raise aNotCallableErrorif the callback is not callable. IfFalsewe will return a valid callback, rather than error. Default isTrue.
Raises: NotCallableError – If the callback is not callable and
errorisTrue.Return type: Callable- callback (
-
jobcalc.dict_from_env_string(string, seperator=None, divider=None, type=None)[source]¶ Creates a dict from a string, using a
seperatorto seperate the items and adividerto distinguish key, value pairs.Parameters: - string (
Union[str,dict]) – The string to create the dict from. - seperator (
Optional[str]) – The seperator to use to seperate items in the string. Defaults to';'. This can also be set by the environment variableJOBCALC_SEPERATOR. - divider (
Optional[str]) – Divides key, value pairs. Defaults to':'. This can also be set by the environment variableJOBCALC_DIVIDER. - type (
Optional[Callable]) – Callback to use to convert all the values to a certain type.
Example:
>>> dict_from_env_string('standard:5;deluxe:10;premium:15') {'standard': '5', 'deluxe': '10', 'premium': '15'} >>> dict_from_env_string('standard:5;deluxe:10;premium:15', ... type=Percentage) {'standard': Percentage('0.5'), 'deluxe': Percentage('0.1'), 'premium': Percentage('0.15')}
Return type: Dict- string (
-
jobcalc.parse_input_string(string, seperator=';', convert=None)[source]¶ Parses an input string that could have multiple values passed in from the command line.
Note
This method always returns a tuple, which can be of length 1 or more.
Parameters: - string (
str) – The input string to parse. - seperator (
str) – The seperator used to seperate items. Defaults to';'. - convert (
Optional[Callable]) – A callback that can be used to convert all the parsed values to a type. This can be acallablethat recieves a single value and returns a single value, or we can also handleclick.ParamType‘s. Default isNone.
Example:
>>> parse_input_string('123;456') ('123', '456') >>> parse_input_string('123;456', convert=Currency) (Currency('123'), Currency('456')) >>> parse_input_string('123') ('123', )
Return type: Tuple[Any]- string (
-
jobcalc.flatten(*args, *, ignoretypes=<class 'str'>)[source]¶ A generator to flatten iterables, containing single items and possible other iterables into a single iterable.
Parameters: - args – Any value to check for sub-lists (iterable) and flatten.
- ignoretypes (
Any) – A type or tuple of types to ignore (not flatten). Default isstr.
Example:
>>> list(flatten([1, 2, [3, 4], [5, [6, 7], [8, 9]]])) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> mylist = ['1', '2', [3, ['4'], ['5 is alive', 6], 7], [8, '9.0']] >>> list(flatten(mylist)) ['1', '2', 3, '4', '5 is alive', 6, 7, 8, '9.0'] >>> list(flatten([1, 2, (3, 4, 5)], ignoretypes=tuple)) [1, 2, (3, 4, 5)]
-
jobcalc.colorize(string, color)[source]¶ Returns a colorized string.
See also
colorclassParameters: - string (
str) – The string to colorize. - color (
str) – The color for the string.
Example:
>>> colorize('some string', 'red') Color('[31msome string[39m')
Return type: Color- string (
-
class
jobcalc.Config(*, seperator=None, divider=None, rate=None, default_hours=None, margins=None, discounts=None, deductions=None, debug=None)[source]¶ Bases:
objectThe main config class that holds common varibles that are used to set up a calculator instance. These variables can either be passed in or retrieved from their corresponding environment variable.
Parameters: - seperator (
Optional[str]) – A seperator used to seperate key, value pairs parsed from an environment variable. Defaults to';'. Can be set byJOBCALC_SEPERATOR. (ex. ‘key1:value1;key2:value2;’) - divider (
Optional[str]) – Used to divide a key, value pair parsed from an environment variable. Defaults to':'. Can be set byJOBCALC_DIVIDER. (ex. ‘key1:value1’) - rate (
Optional[str]) – An hourly rate to be used in calculations. Defaults to ‘0’. Can be set byJOBCALC_RATE. - default_hours (
Optional[str]) – Hours toalwaysbe used for a calculation. Defaults to'0'. Can be set byJOBCALC_DEFAULT_HOURS. - margins (
Optional[Dict]) – A dict with named margins that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_MARGINSusing theseperatoranddividerto distinguish the key, value pairs. All values will get converted to aPercentageto be used as a profit margin. (ex: ‘fifty:50;forty:40’). - discounts (
Optional[Dict]) – A dict with named discounts that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_DISCOUNTSusing theseperatoranddividerto distinguish the key, value pairs. All values will get converted to aPercentageto be used as a percentage discount. (ex. ‘standard:10;deluxe:15’). - deductions (
Optional[Dict]) – A dict with named deductions that can be used in a calculation. Defaults to{}. Can be set byJOBCALC_DEDUCTIONSusing theseperatoranddividerto distinguish key, value pairs. All values will get converted to aCurrencyto be used as a monetary deduction. (ex. ‘one:100;two:200’) - debug (
Optional[bool]) – A bool to put calculator into debug mode. Defaults toFalse.
Return type: None
- seperator (
-
class
jobcalc.TerminalConfig(*, prompt=None, suppress=None, formula=None, allow_empty=None, prompt_seperator=None, **kwargs)[source]¶ Bases:
jobcalc.config.ConfigExtends
Configwith command line interface specific variables.Note
Boolean envrionment variable’s will be determined as
Truewith any of the following values. Anything else isFalse.- ‘True’
- ‘TrUe’ (any combination upper-lower works)
- ‘1’
Parameters: - prompt (
Optional[bool]) – A bool that ifTruewill call theprompt-allsub-command if the main (job-calc) command is called without a sub-command. IfFalsethen we show the help doc. Default isFalse. Can be set byJOBCALC_PROMPT. - suppress (
Optional[bool]) – A bool that ifTruewill suppress the detailed table output for any commands called. Default isFalse. Can be set byJOBCALC_SUPPRESS. - formula (
Optional[bool]) – A bool that ifTruewill show the formula string for any commands called. Default isFalse. Can be set byJOBCALC_FORMULA. - allow_empty (
Optional[bool]) – A bool that ifTruewill not prompt for empty values before performing any calculations. Can be set byJOBCALC_ALLOW_EMPTY. - prompt_seperator (
Optional[str]) – A string that is used to seperate items that can be multiple values if prompted for. Defaults to' '. Can be set byJOBCALC_PROMPT_SEPERATOR.
Return type: None
-
class
jobcalc.Context(subtotal, margin, discount, deduction)¶ Bases:
tuple-
deduction¶ Alias for field number 3
-
discount¶ Alias for field number 2
-
margin¶ Alias for field number 1
-
subtotal¶ Alias for field number 0
-
-
jobcalc.PromptResponse¶ alias of
PromptRespone
-
jobcalc.calculate(subtotal='0', margin='0', multiplier='0', deduction='0')[source]¶ Calculates a total based on the parameters. Returned as a
Currency.Parameters: - subtotal (
Union[Currency,str]) – An item that can be converted to aCurrencyto be used for the calculation. This would be the sum of all the job costs, materials, hours, etc. - margin (
Union[Percentage,str]) – An item that can be converted to aPerentageto be used as the profit margin for the calculation. Default is 0. - multiplier (
Union[Percentage,str]) – An item that can be converted to aPercentageto be used as a percentage discount in the calculation. This discount comes off after the profit margin has been calculated. Default is 0. - deduction (
Union[Currency,str]) – An item that can be converted to aCurrencyto be used as a monetary discount in the calculation. This comes off after the profit margin has be calculated and any other percentage discounts have been taken off.
Return type: - subtotal (
-
class
jobcalc.BaseCalculator(costs=[], margins=[], discounts=[], deductions=[], ignore_margins=None)[source]¶ Bases:
objectThe
BaseCalculatorclass know’s how to takecosts, amargin, adiscount(percentage discount), anddeductionsand calculate a total with those items.All items can be either single or iterables of items, but all get stored as a list. And the sum of that list of items makes up the total for a given item.
Parameters: - costs (
Iterable) – Either a single item or list of items that can be converted to aCurrency, used as the subtotal for a calculation. - margins (
Iterable) – An item or list of items that can be converted to aPercentage, used as the profit margin for the calculation. - discounts (
Iterable) – An item or list of items that can be converted to aPercentage, used as a percentage discount for the calculation. - deductions (
Iterable) – An item or list of items that can be converted to aCurrency, used as monetary deduction for the calculation. - ignore_margins (
Optional[bool]) – A bool determining whether to ignore margins if any of the items incostsare otherCalculatorinstances. Defaults toFalse.
Return type: None
-
static
calculate(*args, **kwargs)[source]¶ Just attaches the
calculate()function as a staticmethod. This is the method called intotal(), so if a sub-class would like to implement a custom calculation, they can override this method.Return type: Currency
-
ctx(ignore_margins=None)[source]¶ A context manager that yields a
Contextthat is properly set up to be used in a calculation.Parameters: ignore_margins ( Optional[bool]) – A bool to determine whether to ignore margins in thesubtotalif ourcostsinclude otherCalculatorinstances. This will fallback toself.ignore_marginsif not supplied.Return type: Context
-
subtotal(ignore_margins=None)[source]¶ Calculate the subtotal of the
costs. This is used becausecostscan also consist of other calculators, so we call eithertotal()orsubtotal()accordingly on those items.Parameters: ignore_margins ( Optional[bool]) – A boolean, ifTrue, then we call subtotal on child calculators, if it’sFalsethen we call total. We fallback toself.ignore_marginsif this is not passed in.Return type: Currency
- costs (
-
class
jobcalc.Calculator(*, formatters=[], hours=[], rate=None, config=None, **kwargs)[source]¶ Bases:
jobcalc.core.BaseCalculatorExtends
BaseCalculator. Adds the ability to attach formatters, torendera formatted output. Addshoursand arateoption. Thehourswill be summed and multiplied by therateand added to thesubtotalof the job. Also adds the ability to pass in aConfiginstance for common configuration of aCalculator.Parameters: - formatters (
Iterable) – A single or iterable ofBaseFormatter‘s to format the output. - hours (
Iterable) – A single or iterable of items that can be converted to adecimal.Decimal. - rate (
Union[str,int,None]) – An single item that can be converted to adecimal.Decimalthat represents an hourly rate. - config (
Optional[Config]) – AConfiginstance to use for values, either set or loaded from the environment.
Return type: None
-
ctx(strict=False)[source]¶ Return a properly configured
Contextto be used.Note
This can also raise errors if
hoursorratecan not be converted to adecimal.Decimal. Most common error will be adecimal.InvalidOperationerror.Parameters: strict ( bool) – IfTruean error will be raised ifhoursare set on an instance, but noratehas been set. Default isFalseRaises: HourlyRateError – If strictisTrueand no hourly rate has been set.Return type: Context
-
rate¶ Used as the hourly rate for a calculator. Defaults to ‘0’. This will not accept anything that is not greater or equal to 0 or anything that can not be converted to a
decimal.Decimal.
-
render(seperator='nn')[source]¶ Return a string output of all the formatters for an instance. Joined by the seperator.
If no formatters have been set, then we fall back to :py:class`BasicFormatter`, which will just output the
total()as a formatted currency string.Parameters: seperator ( str) – A string to use as the seperator. Defaults to a double new-line.Return type: str
-
subtotal(**kwargs)[source]¶ Add’s sum of
costs+ (rate*hours) for the subtotal.Parameters: kwargs – Get passed to super‘s subtotal method.Return type: Currency
-
update(updates=None, append=True, **kwargs)[source]¶ A convenience method to update the common items of an instance.
Parameters: - updates (
Optional[Dict]) – Optional dict used for the updates where the keys are attribute names and the values are the items to set for the attribute. - append (
bool) – A bool, ifTruethen we add the items to the existing attribute, ifFalsethen we remove any items already set with the new items. Default isTrue. - kwargs – Same as
updates.
Example:
>>> calc = Calculator() >>> calc.update({'margins': '50'}) >>> assert calc.margins[-1] == '50' # True >>> calc.update(costs='123') >>> assert calc.costs[-1] == '123' # True
Return type: None - updates (
- formatters (
-
class
jobcalc.TerminalCalculator(*, colors=None, **kwargs)[source]¶ Bases:
jobcalc.core.CalculatorExtends
Calculatorfor use in the command line interface.Parameters: - colors (
Optional[Iterable]) – A 6 tuple orColorKeyof colors - kwargs – Extra args to pass to :py:class:
Calculator
Return type: None
-
is_empty(attr)[source]¶ Determines if an attribute is considered empty, or equal to ‘0’.
If there are default hours set by an environment variable, then hours are considered empty if the sum of (hours - default_hours) are ‘0’.
Parameters: attr ( str) – The name of the attribute to check.Return type: bool
-
key_for_prompt(prompt)[source]¶ - A helper to return the correct key (attribute name) to use for
a prompt.
This is the opposite of the
normalize()method. In which it ensures the return value is pluralized for most cases as that’s the key that can be used in theupdate()method for an instance.This is helpful when making multiple prompts that save their values in a dict, that later is used to update the attributes on an instance.
Parameters: prompt ( str) –The attribute the prompt is for.
Example:
>>> calc = TerminalCalculator() >>> calc.key_for_prompt('discount') 'discounts' >>> calc.key_for_prompt('rates') # handle accidental plural's 'rate'
Return type: str
-
normalize(attr)[source]¶ A helper to normalize an attribute name, as most context’s expect the name to not be pluralized (except
hours), so we chop off the ‘s’ if applicable.This is also helpful if using
prompt_for()method, to make sure the name for the prompt is correct.Parameters: attr ( str) – The attribute name to normalize.Return type: str
-
prompt_all()[source]¶ Prompt the user for all input’s, also showing the current value, and add the values to this instance appropriately.
Return type: None
-
prompt_for(prompt, **kwargs)[source]¶ A context manager that prompt’s a user for input, and yields a
PromptResponse.Valid prompts are ‘margin’, ‘discount’, ‘deduction’, ‘cost’, ‘hours’, and ‘rate’. We will also do/ call the right method if use the plural form of prompt (ex. ‘margins’).
Parameters: - prompt (
str) – The attribute to prompt for (ex. ‘margin’) - kwargs – They get passed to the prompt_for_{prompt} command.
Example:
>>> calc = TerminalCalculator() >>> with calc.prompt_for('margin', default='0') as result: ... calc.update(margins=result.value)
Return type: PromptRespone- prompt (
-
prompt_for_cost(default=None, *, type=<jobcalc.param_types.CostsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶
-
prompt_for_deduction(default=None, *, type=<jobcalc.param_types.DeductionsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶
-
prompt_for_discount(default=None, *, type=<jobcalc.param_types.DiscountsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶
-
prompt_for_empty()[source]¶ Prompt the user for all the values that are determined to be empty or ‘0’, and add them to instance appropriately.
Return type: None
-
prompt_for_hours(default=None, *, type=<class 'decimal.Decimal'>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶
-
prompt_for_margin(default=None, *, type=<jobcalc.param_types.MarginsType object>, is_single=False, current=None, display_multiple_header=True, display_single_header=True)¶
-
prompt_for_rate(default=None, *, type=<class 'decimal.Decimal'>, is_single=True, current=None, display_multiple_header=True, display_single_header=True)¶
- colors (
-
exception
jobcalc.JobCalcError(msg=None)[source]¶ Bases:
ExceptionBase exception used by the app. All custom exceptions should inherit from this class.
Return type: None
-
exception
jobcalc.InvalidEnvString(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if parsing an environment string into a dict fails.
Return type: None
-
exception
jobcalc.EnvDictNotFound(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcErrorRaised if an env string is expected to return a dict, but was not found.
Return type: None
-
exception
jobcalc.NotCallableError(type=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if an expected type is supposed to be callable, but is not.
Return type: None
-
exception
jobcalc.PercentageOutOfRange(value)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,ValueErrorRaised if percentage is above 100 or less than 0.
Return type: None
-
exception
jobcalc.NotIterableError(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,TypeErrorRaised if an iterable is expected, but not recieved.
Return type: None
-
exception
jobcalc.InvalidFormatter(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,AttributeErrorRaised if an invalid formatter is found during calculations.
Return type: None
-
exception
jobcalc.HourlyRateError(msg=None)[source]¶ Bases:
jobcalc.exceptions.JobCalcError,ValueErrorRaised if an hourly rate is expected, but not found or 0, during calculations.
Return type: None
-
class
jobcalc.BaseFormatter[source]¶ Bases:
objectAll formatter’s should sub-class this object, and override the
render()method.-
static
colorize(color)[source]¶ If an item is a
CurrencyorPercentage, then call it’sformatted_stringmethod, before colorizing the value.Parameters: - item (
Any) – A string, Currency, or Percentage to colorize. - color (
str) – The color to use on the item.
Return type: Color- item (
-
static
render()[source]¶ The method all sub-classes should override to render a calculator.
Raises: NotImplementedError – If a sub-class does not implement this method. Return type: str
-
static
totaled_ctx()[source]¶ A context manager that yields the
TotaledContextfor a calculator.Return type: TotaledContext
-
static
-
class
jobcalc.BasicFormatter[source]¶ Bases:
jobcalc.formatters.BaseFormatterA basic formatter that renders the total as a formatted string.
-
class
jobcalc.TerminalFormatter(*colors, *, title='DETAILED', no_colors=False, color_header=False)[source]¶ Bases:
terminaltables.ascii_table.AsciiTable,jobcalc.formatters.BaseFormatterA
terminaltables.AsciiTable, that supports colors and a title.Parameters: - colors – A 5 tuple or
ColorContextof strings that can be used by to convert an item to acolorclass.Color. Defaults to (subtotal=’magenta’, margin=’blue’, discount=’yellow’, deduction=’red’, total=’green’). - title (
str) – A title for the table. Defaults to'DETAILED'. If you do not want a title, then this can be set toNone - no_colors (
bool) – IfTrue, turns off colored output for the table. Default isFalse. - color_header (
bool) – IfTruethen colorize the header as well. Default isFalse.
-
render(calculator)[source]¶ Set’s up the table, and returns it as a string, to be rendered.
Parameters: calculator ( Any) – The calculator to create a table for. Should be aBaseCalculatoror sub-class.Return type: str
- colors – A 5 tuple or
-
class
jobcalc.FormulaFormatter(*colors, *, formula_string=None, no_color=False, title='FORMULA')[source]¶ Bases:
jobcalc.formatters.BaseFormatterPrints the formula used for the calculations.
Parameters: - colors – A 5 tuple or
ColorContextof strings that can be used by to convert an item to acolorclass.Color. Defaults to (subtotal=’magenta’, margin=’blue’, discount=’yellow’, deduction=’red’, total=’green’). - formula_string (
Optional[str]) – A string to use for the format. This should be a a string that we callformat, that accepts kwargs (header, subtotal, margin, discount, deduction, and total). Defaults toDEFAULT_FORMULA_STRING. - no_color (
bool) – Turns colored output off. - title (
str) – Title to display before the output.
Raises: TypeError – If colors is not a 5 tuple.
Return type: None
- colors – A 5 tuple or