id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
6,931
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil from operator import eq, ge, gt, le, lt from typing import TYPE_CHECKING, NamedTuple, cast, overload from flatlatex.data import subscript, superscript from fsspec.core import url_to_fs from prompt_toolkit.application.current import get_app_session from prompt_toolkit.data_structures import Size from prompt_toolkit.filters.base import Condition from prompt_toolkit.filters.utils import _always as always from prompt_toolkit.filters.utils import _never as never from prompt_toolkit.formatted_text.utils import split_lines from prompt_toolkit.layout.containers import WindowAlign from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.utils import Event from upath import UPath from euporie.core.border import ( DiLineStyle, DoubleLine, FullDottedLine, FullLine, GridStyle, InvisibleLine, LowerLeftEighthLine, LowerLeftHalfDottedLine, LowerLeftHalfLine, NoLine, ThickDoubleDashedLine, ThickLine, ThickQuadrupleDashedLine, ThinDoubleDashedLine, ThinLine, ThinQuadrupleDashedLine, UpperRightEighthLine, UpperRightHalfDottedLine, UpperRightHalfLine, ) from euporie.core.convert.datum import Datum, get_loop from euporie.core.convert.mime import get_format from euporie.core.current import get_app from euporie.core.data_structures import DiBool, DiInt, DiStr from euporie.core.ft.table import Cell, Table, compute_padding from euporie.core.ft.utils import ( FormattedTextAlign, FormattedTextVerticalAlign, add_border, align, apply_reverse_overwrites, apply_style, concat, fragment_list_to_words, fragment_list_width, join_lines, last_char, max_line_width, pad, paste, strip, truncate, valign, ) def strip( ft: StyleAndTextTuples, left: bool = True, right: bool = True, chars: str | None = None, only_unstyled: bool = False, ) -> StyleAndTextTuples: """Strip whitespace (or a given character) from the ends of formatted text. Args: ft: The formatted text to strip left: If :py:const:`True`, strip from the left side of the input right: If :py:const:`True`, strip from the right side of the input chars: The character to strip. If :py:const:`None`, strips whitespace only_unstyled: If :py:const:`True`, only strip unstyled fragments Returns: The stripped formatted text """ result = ft[:] for toggle, index, strip_func in [(left, 0, str.lstrip), (right, -1, str.rstrip)]: if result and toggle: text = strip_func(result[index][1], chars) while result and not text: del result[index] if not result: break text = strip_func(result[index][1], chars) if result and "[ZeroWidthEscape]" not in result[index][0]: result[index] = (result[index][0], text) return result The provided code snippet includes necessary dependencies for implementing the `match_css_selector` function. Write a Python function `def match_css_selector( selector: str, attrs: str, pseudo: str, element_name: str, is_first_child_element: bool, is_last_child_element: bool, sibling_element_index: int | None, **element_attrs: Any, ) -> bool` to solve the following problem: Determine if a CSS selector matches a particular element. Here is the function: def match_css_selector( selector: str, attrs: str, pseudo: str, element_name: str, is_first_child_element: bool, is_last_child_element: bool, sibling_element_index: int | None, **element_attrs: Any, ) -> bool: """Determine if a CSS selector matches a particular element.""" matched = True # Check for pseudo classes while pseudo and matched: if pseudo.startswith(":first-child"): matched = is_first_child_element pseudo = pseudo[12:] continue if pseudo.startswith(":last-child"): matched = is_last_child_element pseudo = pseudo[11:] continue if pseudo.startswith(":only-child"): matched = is_first_child_element and is_last_child_element pseudo = pseudo[11:] continue if pseudo.startswith(":nth-child("): pseudo = pseudo[11:] end = pseudo.find(")") if end > -1: rule = pseudo[:end] pseudo = pseudo[end + 1 :] matched = sibling_element_index is not None and ( # n-th child indices start at one (str(sibling_element_index + 1) == rule) or (rule == "odd" and sibling_element_index % 2 == 1) or (rule == "even" and sibling_element_index % 2 == 0) ) continue if pseudo.startswith(":link"): pseudo = pseudo[5:] matched = bool(element_attrs.get("href")) continue return False if not matched: return False while selector and matched: # Universal selector if selector == "*" and not element_name.startswith("::"): break # Element selectors if selector[0] not in ".#[": if selector.startswith(element_name): selector = selector[len(element_name) :] else: return False # ID selectors if selector.startswith("#"): if id_ := element_attrs.get("id"): if selector[1:].startswith(id_): selector = selector[1 + len(id_) :] else: return False else: return False # Class selectors if selector and selector.startswith("."): for class_name in sorted( element_attrs.get("class", "").split(), key=len, reverse=True ): # IF CLASS NAME SUBSTRING if selector[1:].startswith(class_name): selector = selector = selector[1 + len(class_name) :] break else: return False # Attribute selectors # TODO - chained attribute selectors if attrs and matched: for test in re.split(r"(?<=\])(?=\[)", attrs): test = test[1:-1] if (op := "*=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = value in element_attrs.get(attr, "") elif (op := "$=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = element_attrs.get(attr, "").endswith(value) elif (op := "^=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = element_attrs.get(attr, "").startswith(value) elif (op := "|=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = element_attrs.get(attr) in (value, f"{value}-") elif (op := "~=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = value in element_attrs.get(attr, "").split() elif (op := "=") in test: attr, _, value = test.partition(op) value = value.strip("'\"") matched = element_attrs.get(attr) == value else: matched = test in element_attrs if not matched: break else: selector = selector[2 + len(attrs) :] return matched
Determine if a CSS selector matches a particular element.
6,932
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil from operator import eq, ge, gt, le, lt from typing import TYPE_CHECKING, NamedTuple, cast, overload from flatlatex.data import subscript, superscript from fsspec.core import url_to_fs from prompt_toolkit.application.current import get_app_session from prompt_toolkit.data_structures import Size from prompt_toolkit.filters.base import Condition from prompt_toolkit.filters.utils import _always as always from prompt_toolkit.filters.utils import _never as never from prompt_toolkit.formatted_text.utils import split_lines from prompt_toolkit.layout.containers import WindowAlign from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.utils import Event from upath import UPath from euporie.core.border import ( DiLineStyle, DoubleLine, FullDottedLine, FullLine, GridStyle, InvisibleLine, LowerLeftEighthLine, LowerLeftHalfDottedLine, LowerLeftHalfLine, NoLine, ThickDoubleDashedLine, ThickLine, ThickQuadrupleDashedLine, ThinDoubleDashedLine, ThinLine, ThinQuadrupleDashedLine, UpperRightEighthLine, UpperRightHalfDottedLine, UpperRightHalfLine, ) from euporie.core.convert.datum import Datum, get_loop from euporie.core.convert.mime import get_format from euporie.core.current import get_app from euporie.core.data_structures import DiBool, DiInt, DiStr from euporie.core.ft.table import Cell, Table, compute_padding from euporie.core.ft.utils import ( FormattedTextAlign, FormattedTextVerticalAlign, add_border, align, apply_reverse_overwrites, apply_style, concat, fragment_list_to_words, fragment_list_width, join_lines, last_char, max_line_width, pad, paste, strip, truncate, valign, ) The provided code snippet includes necessary dependencies for implementing the `try_eval` function. Write a Python function `def try_eval(value: str, default: Any = None) -> Any` to solve the following problem: Attempt to cast a string to a python type. Here is the function: def try_eval(value: str, default: Any = None) -> Any: """Attempt to cast a string to a python type.""" parsed_value = default or value try: parsed_value = literal_eval(value) except ( ValueError, TypeError, SyntaxError, MemoryError, RecursionError, ): return parsed_value return parsed_value
Attempt to cast a string to a python type.
6,933
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil from operator import eq, ge, gt, le, lt from typing import TYPE_CHECKING, NamedTuple, cast, overload from flatlatex.data import subscript, superscript from fsspec.core import url_to_fs from prompt_toolkit.application.current import get_app_session from prompt_toolkit.data_structures import Size from prompt_toolkit.filters.base import Condition from prompt_toolkit.filters.utils import _always as always from prompt_toolkit.filters.utils import _never as never from prompt_toolkit.formatted_text.utils import split_lines from prompt_toolkit.layout.containers import WindowAlign from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.utils import Event from upath import UPath from euporie.core.border import ( DiLineStyle, DoubleLine, FullDottedLine, FullLine, GridStyle, InvisibleLine, LowerLeftEighthLine, LowerLeftHalfDottedLine, LowerLeftHalfLine, NoLine, ThickDoubleDashedLine, ThickLine, ThickQuadrupleDashedLine, ThinDoubleDashedLine, ThinLine, ThinQuadrupleDashedLine, UpperRightEighthLine, UpperRightHalfDottedLine, UpperRightHalfLine, ) from euporie.core.convert.datum import Datum, get_loop from euporie.core.convert.mime import get_format from euporie.core.current import get_app from euporie.core.data_structures import DiBool, DiInt, DiStr from euporie.core.ft.table import Cell, Table, compute_padding from euporie.core.ft.utils import ( FormattedTextAlign, FormattedTextVerticalAlign, add_border, align, apply_reverse_overwrites, apply_style, concat, fragment_list_to_words, fragment_list_width, join_lines, last_char, max_line_width, pad, paste, strip, truncate, valign, ) class CssSelector(NamedTuple): """A named tuple to hold CSS selector data.""" comb: str | None = None item: str | None = None attr: str | None = None pseudo: str | None = None def __repr__(self) -> str: """Return a string representation of the selector.""" defaults = self._field_defaults attrs = ", ".join( f"{k}={v!r}" for k, v in self._asdict().items() if v != defaults[k] ) return f"{self.__class__.__name__}({attrs})" The provided code snippet includes necessary dependencies for implementing the `selector_specificity` function. Write a Python function `def selector_specificity( selector_parts: tuple[CssSelector, ...], ) -> tuple[int, int, int]` to solve the following problem: Calculate the specificity score of a CSS selector. Here is the function: def selector_specificity( selector_parts: tuple[CssSelector, ...], ) -> tuple[int, int, int]: """Calculate the specificity score of a CSS selector.""" identifiers = classes = elements = 0 for selector in selector_parts: item = selector.item or "" identifiers += (ids := item.count("#")) classes += (clss := item.count(".")) if item != "*" and not ids and not clss: elements += 1 classes += (selector.attr or "").count("[") classes += (selector.pseudo or "").count(":") return (identifiers, classes, elements)
Calculate the specificity score of a CSS selector.
6,934
from __future__ import annotations import asyncio import logging import re from ast import literal_eval from bisect import bisect_right from collections.abc import Mapping from functools import cached_property, lru_cache, partial from html.parser import HTMLParser from itertools import zip_longest from math import ceil from operator import eq, ge, gt, le, lt from typing import TYPE_CHECKING, NamedTuple, cast, overload from flatlatex.data import subscript, superscript from fsspec.core import url_to_fs from prompt_toolkit.application.current import get_app_session from prompt_toolkit.data_structures import Size from prompt_toolkit.filters.base import Condition from prompt_toolkit.filters.utils import _always as always from prompt_toolkit.filters.utils import _never as never from prompt_toolkit.formatted_text.utils import split_lines from prompt_toolkit.layout.containers import WindowAlign from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.utils import Event from upath import UPath from euporie.core.border import ( DiLineStyle, DoubleLine, FullDottedLine, FullLine, GridStyle, InvisibleLine, LowerLeftEighthLine, LowerLeftHalfDottedLine, LowerLeftHalfLine, NoLine, ThickDoubleDashedLine, ThickLine, ThickQuadrupleDashedLine, ThinDoubleDashedLine, ThinLine, ThinQuadrupleDashedLine, UpperRightEighthLine, UpperRightHalfDottedLine, UpperRightHalfLine, ) from euporie.core.convert.datum import Datum, get_loop from euporie.core.convert.mime import get_format from euporie.core.current import get_app from euporie.core.data_structures import DiBool, DiInt, DiStr from euporie.core.ft.table import Cell, Table, compute_padding from euporie.core.ft.utils import ( FormattedTextAlign, FormattedTextVerticalAlign, add_border, align, apply_reverse_overwrites, apply_style, concat, fragment_list_to_words, fragment_list_width, join_lines, last_char, max_line_width, pad, paste, strip, truncate, valign, ) class CssSelector(NamedTuple): """A named tuple to hold CSS selector data.""" comb: str | None = None item: str | None = None attr: str | None = None pseudo: str | None = None def __repr__(self) -> str: """Return a string representation of the selector.""" defaults = self._field_defaults attrs = ", ".join( f"{k}={v!r}" for k, v in self._asdict().items() if v != defaults[k] ) return f"{self.__class__.__name__}({attrs})" _SELECTOR_RE = re.compile( r""" (?:^|\s*(?P<comb>[\s>+~]|(?=::))\s*) (?P<item>(?:::)?[^\s>+~:[\]]+)? (?P<attr>\[[^\s>+~]+\])? (?P<pseudo>\:[^:][^\s>+~]*)? """, re.VERBOSE, ) _AT_RULE_RE = re.compile( r""" ( [^@{]+ (?: {[^{}]*} | {(?:[^{]+?{(?:[^{}]|{[^}]+?})+?}\s*)*?} ) | ) """, re.VERBOSE, ) _NESTED_AT_RULE_RE = re.compile( r"@(?P<identifier>[\w-]+)\s*(?P<rule>[^{]*?)\s*{\s*(?P<part>.*)\s*}" ) _MEDIA_QUERY_TARGET_RE = re.compile( r""" (?: (?P<invert>not\s+)? (?:only\s+)? # Ignore this (?P<type>all|print|screen) | (?:\((?P<feature>[^)]+)\)) ) """, re.VERBOSE, ) def parse_css_content(content: str) -> dict[str, str]: """Convert CSS declarations into the internals style representation.""" theme: dict[str, str] = {} if not content: return theme for declaration in content.split(";"): name, _, value = declaration.partition(":") name = name.strip().lower() value = value.strip() # Helpers def _split_quad(value: str) -> tuple[str, str, str, str]: values = value.split() if len(values) == 1: top = right = bottom = left = values[0] elif len(values) == 2: top = bottom = values[0] left = right = values[1] elif len(values) == 3: top = values[0] right = left = values[1] bottom = values[2] elif len(values) >= 4: top, right, bottom, left, *_ = values else: top = right = bottom = left = "" return top, right, bottom, left def _split_pair(value: str) -> tuple[str, str]: values = value.split() if len(values) == 1: x = y = values[0] elif len(values) == 2: x = values[0] y = values[1] else: x = y = "" return x, y # Compute values if name == "background": # TODO - needs work for part in value.split(): if color := get_color(part): theme["background_color"] = color break elif name == "padding": ( theme["padding_top"], theme["padding_right"], theme["padding_bottom"], theme["padding_left"], ) = _split_quad(value) elif name in { "border", "border-top", "border-right", "border-bottom", "border-left", }: width_value = style_value = color_value = "" for each_value in value.split(maxsplit=2): if color := get_color(each_value): color_value = color elif ( css_dimension(each_value) is not None or each_value in _BORDER_WIDTH_STYLES ): width_value = each_value elif each_value in _BORDER_WIDTH_STYLES[0]: style_value = each_value if name in {"border", "border-top"}: theme["border_top_width"] = width_value theme["border_top_style"] = style_value theme["border_top_color"] = color_value if name in {"border", "border-right"}: theme["border_right_width"] = width_value theme["border_right_style"] = style_value theme["border_right_color"] = color_value if name in {"border", "border-bottom"}: theme["border_bottom_width"] = width_value theme["border_bottom_style"] = style_value theme["border_bottom_color"] = color_value if name in {"border", "border-left"}: theme["border_left_width"] = width_value theme["border_left_style"] = style_value theme["border_left_color"] = color_value elif name == "border-width": ( theme["border_top_width"], theme["border_right_width"], theme["border_bottom_width"], theme["border_left_width"], ) = _split_quad(value) elif name == "border-style": ( theme["border_top_style"], theme["border_right_style"], theme["border_bottom_style"], theme["border_left_style"], ) = _split_quad(value) elif name == "border-color": ( theme["border_top_color"], theme["border_right_color"], theme["border_bottom_color"], theme["border_left_color"], ) = _split_quad(value) elif name == "margin": ( theme["margin_top"], theme["margin_right"], theme["margin_bottom"], theme["margin_left"], ) = _split_quad(value) elif name == "overflow": theme["overflow_x"] = theme["overflow_y"] = value elif name == "list-style": for each_value in value.split(): if each_value in {"inside", "outside"}: theme["list_style_position"] = each_value elif each_value in _LIST_STYLE_TYPES: theme["list_style_type"] = each_value elif name == "flex-flow": values = set(value.split(" ")) directions = {"row", "row-reverse", "column", "column-reverse"} wraps = {"nowrap", "wrap", "wrap-reverse"} for value in values.intersection(directions): theme["flex_direction"] = value for value in values.intersection(wraps): theme["flex_wrap"] = value # Grid stuff elif name == "grid-template": rows, cols = value.split("/") theme["grid_template_rows"] = rows.strip() theme["grid_template_columns"] = cols.strip() elif name == "grid-column": start, _, end = value.partition("/") theme["grid_column_start"] = start.strip() theme["grid_column_end"] = end.strip() elif name == "grid-row": start, _, end = value.partition("/") theme["grid_row_start"] = start.strip() theme["grid_row_end"] = end.strip() # Gaps elif name == "gap": theme["column_gap"], theme["row_gap"] = _split_pair(value) elif name == "grid-column-gap": theme["column_gap"] = value elif name == "grid-row-gap": theme["row_gap"] = value else: name = name.replace("-", "_") theme[name] = value return theme def parse_media_condition(condition: str, dom: HTML) -> Filter: """Convert media rules to conditions.""" condition = condition.replace(" ", "") result: Filter for op_str, op_func in (("<=", le), (">=", ge), ("<", lt), (">", gt), ("=", eq)): if op_str in condition: operator = op_func feature, _, value = condition.partition(op_str) break else: feature, _, value = condition.partition(":") if feature.startswith("max-"): operator = le feature = feature[4:] elif feature.startswith("min-"): operator = ge feature = feature[4:] else: operator = eq if feature == "width": result = Condition( lambda: operator( width := dom.width or 80, css_dimension(value, vertical=False, available=width) or 80, ) ) elif feature == "height": result = Condition( lambda: operator( height := dom.height or 24, css_dimension(value, vertical=True, available=height) or 24, ) ) elif feature == "aspect": result = Condition( lambda: operator( (width := (dom.width or 80)) / (height := (dom.height or 24)), ( 80 if (dim := css_dimension(value, vertical=False, available=width)) is None else dim ) / ( 24 if (dim := css_dimension(value, vertical=True, available=height)) is None else dim ), ) ) elif feature == "device-width": result = Condition( lambda: operator( ( output.get_size() if (output := get_app_session()._output) else Size(24, 80) ).columns, css_dimension(value, vertical=False, available=dom.width) or 80, ) ) elif feature == "device-height": result = Condition( lambda: operator( ( output.get_size() if (output := get_app_session()._output) else Size(24, 80) ).rows, css_dimension(value, vertical=True, available=dom.height) or 24, ) ) elif feature == "device-aspect": result = Condition( lambda: operator( ( size := ( output.get_size() if (output := get_app_session()._output) else Size(24, 80) ) ).columns / size.rows, (css_dimension(value, vertical=False, available=dom.width) or 1) / (css_dimension(value, vertical=True, available=dom.height) or 1), ) ) # elif feature == "color": # Check output color depth else: result = always return result class HTML: """A HTML formatted text renderer. Accepts a HTML string and renders it at a given width. """ def __init__( self, markup: str, base: Path | str | None = None, width: int | None = None, height: int | None = None, collapse_root_margin: bool = False, fill: bool = True, css: CssSelectors | None = None, browser_css: CssSelectors | None = None, mouse_handler: Callable[[Node, MouseEvent], NotImplementedOrNone] | None = None, paste_fixed: bool = True, defer_assets: bool = False, on_update: Callable[[HTML], None] | None = None, on_change: Callable[[HTML], None] | None = None, _initial_format: str = "", ) -> None: """Initialize the markdown formatter. Args: markup: The markdown text to render base: The base url for the HTML dom width: The width in characters available for rendering. If :py:const:`None` the terminal width will be used height: The width in characters available for rendering. If :py:const:`None` the terminal height will be used collapse_root_margin: If :py:const:`True`, margins of the root element will be collapsed fill: Whether remaining space in block elements should be filled css: Base CSS to apply when rendering the HTML browser_css: The browser CSS to use mouse_handler: A mouse handler function to use when links are clicked paste_fixed: Whether fixed elements should be pasted over the output defer_assets: Whether to render the page before remote assets are loaded on_update: An optional callback triggered when the DOM updates on_change: An optional callback triggered when the DOM changes _initial_format: The initial format of the data being displayed """ self.markup = markup.strip() self.base = UPath(base or ".") self.title = "" self.browser_css = browser_css or _BROWSER_CSS self.css: CssSelectors = css or {} self.defer_assets = defer_assets self.render_count = 0 self.width = width self.height = height self.fill = fill self.collapse_root_margin = collapse_root_margin self.paste_fixed = paste_fixed self._initial_format = _initial_format self.graphic_data: set[Datum] = set() self.mouse_handler = mouse_handler self.formatted_text: StyleAndTextTuples = [] self.floats: dict[tuple[int, DiBool, DiInt], StyleAndTextTuples] = {} self.fixed: dict[tuple[int, DiBool, DiInt], StyleAndTextTuples] = {} self.fixed_mask: StyleAndTextTuples = [] # self.anchors = [] self.on_update = Event(self, on_update) self.on_change = Event(self, on_change) self._dom_processed = False self._assets_loaded = False self._url_cbs: dict[Path, Callable[[Any], None]] = {} self._url_fs_map: dict[Path, AbstractFileSystem] = {} # Lazily load attributes def parser(self) -> CustomHTMLParser: """Load the HTML parser.""" return CustomHTMLParser(self) def soup(self) -> Node: """Parse the markup.""" return self.parser.parse(self.markup) def process_dom(self) -> None: """Load CSS styles and image resources. Do not touch element's themes! """ def _process_css(data: bytes) -> None: try: css_str = data.decode() except Exception: log.warning("Error decoding stylesheet '%s...'", data[:20]) else: parse_style_sheet(css_str, self) def _process_img(child: Node, data: bytes) -> None: child.attrs["_data"] = data del child.attrs["_missing"] for child in self.soup.descendents: # Set base if child.name == "base": if href := child.attrs.get("href"): self.base = self.base.joinuri(href) # Set title elif child.name == "title": if contents := child.contents: self.title = contents[0]._text.strip() self.on_update.fire() # In case of a <link> style, load the url elif ( child.name == "link" and ( (attrs := child.attrs).get("rel") == "stylesheet" or (attrs.get("rel") == "preload" and attrs.get("as") == "style") ) and (href := attrs.get("href", "")) ): url = self.base.joinuri(href) fs, url = url_to_fs(str(url)) self._url_fs_map[url] = fs self._url_cbs[url] = _process_css # In case of a <style> tab, load first child's text elif child.name == "style": if child.contents: # Use unprocessed text attribute to avoid loading the element's theme css_str = child.contents[0]._text parse_style_sheet(css_str, self) # Load images elif child.name == "img" and (src := child.attrs.get("src")): child.attrs["_missing"] = "true" url = self.base.joinuri(src) fs, url = url_to_fs(str(url)) self._url_fs_map[url] = fs self._url_cbs[url] = partial(_process_img, child) self._dom_processed = True async def load_assets(self) -> None: """Load remote assets asynchronously.""" self._assets_loaded = True # Load all remote assets for each protocol using fsspec (where they are loaded # asynchronously in their own thread) and trigger callbacks if the file is # loaded successfully fs_url_map = { fs: [url for url, f in self._url_fs_map.items() if f == fs] for fs in set(self._url_fs_map.values()) } for fs, urls in fs_url_map.items(): try: results = fs.cat(urls, recursive=False, on_error="return") except Exception: log.warning("Error connecting to %s", fs) else: # for url, result in zip(urls, results.values()): for url, result in results.items(): if not isinstance(result, Exception): log.debug("File %s loaded", url) self._url_cbs[url](result) else: log.warning("Error loading %s", url) # Reset all nodes so they will update with the new CSS from assets if self.defer_assets: self.soup.reset() def render(self, width: int | None, height: int | None) -> StyleAndTextTuples: """Render the current markup at a given size.""" loop = get_loop() future = asyncio.run_coroutine_threadsafe(self._render(width, height), loop) return future.result() async def _render( self, width: int | None, height: int | None ) -> StyleAndTextTuples: """Render the current markup at a given size, asynchronously.""" # log.debug("Rendering at (%d, %d)", width, height) no_w = width is None and self.width is None no_h = height is None and self.height is None if no_w or no_h: size = get_app_session().output.get_size() if no_w: width = size.columns if no_h: height = size.rows if width is not None: self.width = width if height is not None: self.height = height assert self.width is not None assert self.height is not None # The soup gets parsed when we load assets, and asset data gets attached to it if not self._dom_processed: self.process_dom() if not self.defer_assets and not self._assets_loaded: await self.load_assets() ft = await self.render_element( self.soup, available_width=self.width, available_height=self.height, fill=self.fill, ) # Apply "ReverseOverwrite"s ft = apply_reverse_overwrites(ft) # Apply floats and fixed elements def _paste_floats( floats: dict[tuple[int, DiBool, DiInt], StyleAndTextTuples], lower_ft: StyleAndTextTuples, ) -> StyleAndTextTuples: """Paste floats on top of rendering.""" lower_ft_height = None for (_, anchors, position), float_ft in sorted(floats.items()): row = col = 0 if anchors.top: row = position.top elif anchors.bottom: if lower_ft_height is None: lower_ft_height = sum(1 for _ in split_lines(lower_ft)) row = ( lower_ft_height - sum(1 for _ in split_lines(float_ft)) - position.bottom ) if anchors.left: col = position.left elif anchors.right: row = ( max_line_width(lower_ft) - max_line_width(float_ft) - position.right ) lower_ft = paste(float_ft, lower_ft, row, col) return lower_ft # Draw floats if self.floats: ft = _paste_floats(self.floats, ft) # Paste floats onto a mask, then onto the rendering if required if self.fixed: assert self.width is not None assert self.height is not None fixed_mask = cast( "StyleAndTextTuples", [("", (" " * self.width) + "\n")] * self.height ) fixed_mask = _paste_floats(self.fixed, fixed_mask) fixed_mask = apply_reverse_overwrites(fixed_mask) if self.paste_fixed: ft = paste(fixed_mask, ft, 0, 0, transparent=True) self.fixed_mask = fixed_mask else: self.fixed_mask = [] self.render_count += 1 self.formatted_text = ft # Load assets after initial render and requuest a re-render when loaded if self.defer_assets and not self._assets_loaded: loop = asyncio.get_event_loop() task = loop.create_task(self.load_assets()) task.add_done_callback(lambda fut: self.on_change.fire()) return ft async def render_element( self, element: Node, available_width: int, available_height: int, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render a Node.""" # Update the element theme with the available space element.theme.update_space(available_width, available_height) # Render the contents if element.theme.d_table: render_func = self.render_table_content elif element.theme.d_list_item: render_func = self.render_list_item_content elif element.theme.d_grid: render_func = self.render_grid_content elif element.theme.latex: render_func = self.render_latex_content else: name = element.name.lstrip(":") render_func = getattr( self, f"render_{name}_content", self.render_node_content ) # Render the element ft = await render_func(element, left, fill, align_content) # Format the contents ft = await self.format_element(ft, element, left, fill, align_content) return ft async def render_text_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render a text element. Args: element: The page element to render left: The position on the current line at which to render the output - used to indent subsequent lines when rendering inline blocks like images fill: Whether to fill the remainder of the rendered space with whitespace align_content: Whether to align the element's content Returns: Formatted text """ ft: StyleAndTextTuples = [] text = await element.theme.text_transform(element.text) if parent_theme := element.theme.parent_theme: style = parent_theme.style else: style = "" ft.append((style, text)) return ft async def render_details_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render details, showing summary at the top and hiding contents if closed.""" ft = [] theme = element.theme summary = None contents = [] for child in element.contents: if not summary and child.name == "summary": summary = child else: contents.append(child) if summary: ft += await self.render_element( summary, available_width=theme.content_width, available_height=theme.content_height, left=left, fill=fill, ) if "open" in element.attrs and contents: # Create a dummy node with non-summary children and render it node = Node(dom=self, name="::content", parent=element, contents=contents) ft += [("", "\n")] ft += await self.render_element( node, available_width=theme.content_width, available_height=theme.content_height, left=left, fill=fill, ) return ft async def render_ol_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render lists, adding item numbers to child <li> elements.""" # Assign a list index to each item. This can be set via the 'value' attributed _curr = 0 for item in element.find_all("li"): _curr += 1 _curr = int(item.attrs.setdefault("value", str(_curr))) # Render list as normal return await self.render_node_content( element=element, left=left, fill=fill, align_content=align_content, ) render_ul_content = render_ol_content async def render_list_item_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render a list item.""" # Get element theme theme = element.theme # Get the bullet style list_style = theme.list_style_type bullet = list_style if list_style == "decimal": bullet = f"{element.attrs['value']}." # Add bullet element if bullet: bullet_element = Node(dom=self, name="::marker", parent=element) bullet_element.contents.append( Node(dom=self, name="::text", parent=bullet_element, text=bullet) ) if theme.list_style_position == "inside": element.contents.insert(0, bullet_element) else: element.marker = bullet_element # Render the list item ft = await self.render_node_content( element, left=left, fill=fill, align_content=align_content, ) return ft async def render_table_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render a HTML table element. Args: element: The list of parsed elements to render left: The position on the current line at which to render the output - used to indent subsequent lines when rendering inline blocks like images fill: Whether to fill the remainder of the rendered space with whitespace align_content: Whether to align the element's content Returns: Formatted text """ ft = [] table_theme = element.theme table_x_dim = Dimension( min=table_theme.min_width, preferred=table_theme.content_width if "width" in table_theme else None, max=table_theme.max_width or table_theme.content_width, ) table = Table( width=table_x_dim, expand="width" in table_theme, align=table_theme.text_align, style=table_theme.style, padding=DiInt(0, 0, 0, 0), border_line=table_theme.border_line, border_style=table_theme.border_style, border_visibility=table_theme.border_visibility, ) td_map = {} # Stack the elements in the shape of the table async def render_rows(elements: list[Node]) -> None: for tr in elements: if tr.name == "tr": tr_theme = tr.theme # tr_theme.update_space(available_width, available_height) row = table.new_row( align=tr_theme.text_align, style=tr_theme.style, border_line=tr_theme.border_line, border_style=tr_theme.border_style, border_visibility=tr_theme.border_visibility, ) for td in tr.contents: if td.name in ("th", "td"): td_theme = td.theme td_theme.update_space( table_theme.content_width or table_theme.available_width, table_theme.content_height or table_theme.available_width, ) cell = row.new_cell( text=await self.render_node_content( td, left=0, align_content=False, fill=False, ), padding=td_theme.padding, border_line=td_theme.border_line, border_style=td_theme.border_style, align=td_theme.text_align, colspan=try_eval(td.attrs.get("colspan", 1)), rowspan=try_eval(td.attrs.get("rowspan", 1)), style=td_theme.style + " nounderline", width=td_theme.width if "width" in td_theme else None, border_visibility=td_theme.border_visibility, ) # Save for later so we can add the contents once all the # cells are created and we can calculate the cell widths td_map[cell] = td # Render the table head for child in element.find_all("thead", recursive=False): await render_rows(child.contents) # Render the table body for child in element.find_all("tbody", recursive=False): await render_rows(child.contents) # Render rows not in a head / body / foot as part of the body await render_rows(element.contents) for child in element.find_all("tfoot", recursive=False): await render_rows(child.contents) # TODO - process <colgroup> elements # Add cell contents if td_map: col_widths = table.calculate_col_widths() for row in table.rows: for col_width, cell in zip(col_widths, row.cells): if td := td_map.get(cell): cell_padding = compute_padding(cell) available_width = ( table_x_dim.max if cell.colspan > 1 else col_width - cell_padding.left - cell_padding.right ) td.theme.update_space( available_width, table_theme.available_height ) cell.text = await self.render_node_content( td, # TODO - get actual colspan cell widths properly left=0, ) # Render the table ft_table = table.render() # Render the caption # TODO - support "caption-side" css captions = element.find_all("caption", recursive=False) if captions: table_width = max_line_width(ft_table) for child in captions: ft_caption = await self.render_element( child, available_width=table_width, available_height=table_theme.available_height, left=0, fill=True, ) if ft_caption: ft.extend(ft_caption) ft.extend(ft_table) return ft async def render_grid_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render a element with ``display`` set to ``grid``. Args: element: The list of parsed elements to render left: The position on the current line at which to render the output - used to indent subsequent lines when rendering inline blocks like images fill: Whether to fill the remainder of the rendered space with whitespace align_content: Whether to align the element's content Returns: Formatted text """ theme = element.theme theme_style = theme.style table = Table( style=theme.style, padding=DiInt(0, 0, 0, 0), width=theme.content_width, expand=False, background_style=theme_style, ) available_width = theme.content_width available_height = theme.content_height # TODO - calculate grid row heights col_width_template, _row_height_template = theme.grid_template grid_areas = theme.grid_areas or {0: {}} n_cols = max(len(col_width_template), len(grid_areas[0])) td_map = {} # Assign items to their positions in the table ## Sort children into those assigned a grid area and those unassigned child_areas: dict[str, Node] = {} remainder = [] for child in element.contents: # Sort by CSS `order if ga := child.theme.grid_area: child_areas[ga] = child else: remainder.append(child) ## Place children assigned a grid area their positions done = set() for y, grid_row in grid_areas.items(): for x, area in grid_row.items(): if area not in done and area in child_areas: child = child_areas.pop(area) colspan = 1 for i in range(x + 1, len(grid_row)): if grid_row[i] == area: colspan += 1 else: break rowspan = 1 for i in range(y + 1, len(grid_areas)): if grid_areas[i][x + colspan - 1] == area: rowspan += 1 else: break # Add a cell child to the table for this child cell = Cell( colspan=colspan, rowspan=rowspan, style=child.theme.style, border_line=NoLine, border_style=theme_style, ) table._rows[y].add_cell(cell, index=x) td_map[cell] = child done.add(area) table.sync_rows_to_cols() ## Place children without a grid area wherever they fit x = y = 0 for child in sorted((*child_areas.values(), *remainder)): child_theme = child.theme # Skip whitespace if not child_theme.in_flow: continue colspan = child_theme.grid_column_span # Find next available cell # Or skip cells to get to the child's assigned column # or skip cells until cell fits col_start = child_theme.grid_column_start while ( x in table._rows[y]._cells or (x > 0 and (x + colspan) > n_cols) or (col_start is not None and x != col_start) ): x += 1 if x >= n_cols: y += 1 x = 0 # Add a cell child to the table for this child cell = Cell( colspan=colspan, style=child_theme.style, border_line=NoLine, border_style=theme_style, ) table._rows[y].add_cell(cell, index=x) td_map[cell] = child table.sync_rows_to_cols() # Remove outer-most cell borders, and set grid gap gap_x, gap_y = map(bool, theme.gap) border_visibility = DiBool(gap_y, gap_x, gap_y, gap_x) for rowcols, directionss in ( (table._cols.values(), ("top", "bottom")), (table._rows.values(), ("left", "right")), ): for rowcol in rowcols: if cells := rowcol._cells: for func, direction in zip((min, max), directionss): cell = cells[func(cells)] cell.border_visibility = ( cell.border_visibility or border_visibility )._replace(**{direction: False}) # Calculate column widths n_cols = len(table._cols) available = available_width - gap_x * (n_cols - 1) col_widths = {} frs = {} for x, item in enumerate(col_width_template): if item.endswith("fr"): frs[x] = css_dimension(item, available=available) or 1 # TODO elif item == "min-content": content_widths = [] for cell in table._cols[x]._cells.values(): if cell in td_map: content_widths.append(td_map[cell].theme.min_content_width) if content_widths: col_widths[x] = max(content_widths) # elif item == "max-content": # content_widths = [] # for cell in table._cols[x]._cells.values(): # if cell in td_map: # content_widths.append(td_map[cell].theme.max_content_width) # if content_widths: # col_widths[x] = max(content_widths) # elif item.startwith("min-max"): # TODO elif ( value := css_dimension(item, vertical=False, available=available) ) is not None: col_widths[x] = round(value) else: # Give remaining columns one fraction frs[x] = 1 # Any undefined columns are min-content for x in set(range(n_cols)) - col_widths.keys() - frs.keys(): frs[x] = 1 ## Divide reminder between `fr` columns if frs: fr_available = available - sum(filter(None, col_widths.values())) fr_count = sum(frs.values()) for x, value in frs.items(): col_widths[x] = round(value / fr_count * fr_available) # Add remainder to last column to ensure column widths sum to available space if n_cols: col_widths[n_cols - 1] += available - sum(col_widths.values()) # Set cell widths for row in table._rows.values(): for x, cell in row._cells.items(): colspan = cell.colspan cell.width = sum(col_widths[x + i] for i in range(colspan)) + gap_x * ( colspan - 1 ) # Allow the table to adjust given cell widths to the available space cell_widths = table.calculate_cell_widths(available_width) # Render cell contents at the final calculated widths async def _render_cell(cell: Cell, td: Node, width: int, height: int) -> None: cell.text = await self.render_element( td, available_width=width, available_height=height, left=0, fill=True, align_content=align_content, ) coros = [] for row in table._rows.values(): for cell in row._cells.values(): if td := td_map.get(cell): width = cell_widths[cell] td.theme.update_space(width, theme.available_height) coros.append( _render_cell( cell, td, width or available_width, available_height ) ) await asyncio.gather(*coros) return table.render() async def render_latex_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render LaTeX math content.""" theme = element.theme # Render text representation ft: StyleAndTextTuples = await self.render_node_content( element, left, fill, align_content ) # Render graphic representation latex = element.text + "".join( child.text for child in element.renderable_descendents ) latex = f"${latex}$" if element.theme.d_blocky: latex = f"${latex}$" datum = Datum( latex, "latex", fg=theme.color or None, bg=theme.background_color or None, align=WindowAlign.CENTER, ) self.graphic_data.add(datum) # Calculate size and pad text representation cols, aspect = await datum.cell_size_async() rows = max(len(list(split_lines(ft))), ceil(cols * aspect)) cols = max(cols, max_line_width(ft)) key = datum.add_size(Size(rows, cols)) ft = [(f"[Graphic_{key}]", ""), *ft] ft = valign(ft, height=rows, how=FormattedTextVerticalAlign.TOP) return ft async def _render_image( self, data: bytes, format_: str, theme: Theme, path: Path | None = None ) -> StyleAndTextTuples: ... async def _render_image( self, data: str, format_: str, theme: Theme, path: Path | None = None ) -> StyleAndTextTuples: ... async def _render_image(self, data, format_, theme, path=None): """Render an image and prepare graphic representation.""" datum = Datum( data, format_, path=path, ) # Keep reference to this graphic self.graphic_data.add(datum) # Scale down the image to fit to width cols, aspect = await datum.cell_size_async() if content_width := theme.content_width: cols = content_width if cols == 0 else min(content_width, cols) rows = ceil(cols * aspect) # Convert the image to formatted-text ft = ( await datum.convert_async( to="ft", cols=cols, rows=rows or None, fg=theme.color, bg=theme.background_color, ) or [] ) # Remove trailing new-lines ft = strip(ft, chars="\n", left=False) # If we couldn't calculate the image size, use the size of the text output if rows == 0 and cols: rows = min(theme.content_height, len(list(split_lines(ft)))) aspect = rows / cols # Store reference to image element key = Datum.add_size(datum, Size(rows, cols)) return cast( "StyleAndTextTuples", # Flag graphic position [(f"[Graphic_{key}]", "")] # Set default background color on generated content + [(f"{theme.style} {style}", (text), *rest) for style, text, *rest in ft], ) async def render_img_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render an image's content.""" theme = element.theme content_width = theme.content_width # content_height = theme.content_height src = str(element.attrs.get("src", "")) path = self.base.joinuri(src) if not element.attrs.get("_missing") and (data := element.attrs.get("_data")): # Display it graphically format_ = get_format(path, default="png") ft = await self._render_image(data, format_, theme, path) else: style = f"class:image,placeholder {theme.style}" ft = [(style, "🌄")] if content_width and content_width >= 7: ft.extend( [ (style, " "), ( style, ( element.attrs.get("alt") or (path.name if path else "Image") ), ), ] ) return ft async def render_svg_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Display images rendered as ANSI art.""" theme = element.theme # HTMLParser clobber the case of element attributes element.attrs["xmlns"] = "http://www.w3.org/2000/svg" element.attrs["xmlns:xlink"] = "http://www.w3.org/1999/xlink" # We fix the SVG viewBox here data = element._outer_html().replace(" viewbox=", " viewBox=") # Replace "currentColor" with theme foreground color data = data.replace("currentColor", theme.color) ft = await self._render_image(data, "svg", theme) return ft async def render_input_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Render an input element.""" attrs = element.attrs element.contents.insert( 0, Node( dom=self, name="::text", parent=element, text=attrs.get("value", attrs.get("placeholder", " ")) or " ", ), ) ft = await self.render_node_content( element, left=left, fill=fill, align_content=align_content, ) return ft async def render_node_content( self, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Generate flows for the contents of the element.""" ft: StyleAndTextTuples = [] ft_left: StyleAndTextTuples ft_middle: StyleAndTextTuples ft_right: StyleAndTextTuples empty: StyleAndTextTuples = [] line_height = 1 baseline = 0 parent_theme = element.theme d_blocky = d_inline = d_inline_block = False float_lines_left: list[StyleAndTextTuples] = [] float_width_left = 0 float_lines_right: list[StyleAndTextTuples] = [] float_width_right = 0 content_width = parent_theme.content_width new_line: StyleAndTextTuples = [] def flush() -> None: """Add the current line to the rendered output.""" nonlocal new_line, ft, left, line_height, baseline if new_line: # Pad the new-line to form an alignable block new_line = pad(new_line, style=parent_theme.style) if ft: # Combine with the output ft = join_lines([ft, new_line]) if ft else new_line else: ft = new_line # Reset the new line left = 0 line_height = 1 baseline = 0 new_line = [] available_width = parent_theme.content_width available_height = parent_theme.content_height coros = {} for child in element.renderable_descendents: theme = child.theme if theme.skip: continue # Render the element coros[child] = self.render_element( child, available_width=available_width, available_height=available_height, left=0, fill=fill, align_content=align_content, ) renderings = await asyncio.gather(*coros.values()) # Render each child node for child, rendering in zip(coros, renderings): # Start a new line if we encounter a <br> element if child.name == "br": flush() continue # If the rendering was empty, move on if not rendering: continue theme = child.theme # We will start a new line if the previous item was a block if ft and d_blocky and last_char(ft) != "\n": line_height = 1 left = 0 baseline = 0 d_blocky = theme.d_blocky d_inline = theme.d_inline d_inline_block = theme.d_inline_block preformatted = theme.preformatted # If the rendering was a positioned absolutely or fixed, store it and draw it later if theme.theme["position"] == "fixed": self.fixed[(theme.z_index, theme.anchors, theme.position)] = rendering # if theme.theme["position"] == "absolute": # self.floats[(theme.z_index, theme.anchors, theme.position)] = rendering # if theme.theme["position"] == "relative": # ... TODO .. elif theme.floated == "right": lines = [] for ft_left, ft_right in zip_longest( split_lines(pad(rendering, style=theme.style)), float_lines_right, fillvalue=empty, ): lines.append([*ft_left, *ft_right]) float_lines_right = lines float_width_right = fragment_list_width(float_lines_right[0]) continue elif theme.floated == "left": lines = [] for ft_left, ft_right in zip_longest( lines, split_lines(pad(rendering, style=theme.style)), fillvalue=empty, ): lines.append([*ft_left, *ft_right]) float_lines_left = lines float_width_left = fragment_list_width(float_lines_left[0]) continue # If the rendering was inline, add it to the end of the last line of the # current output. This might involve re-aligning the last line in the # output, which could have been an inline-block elif d_inline and ( # parent_theme.d_inline or parent_theme.d_inline_block or preformatted parent_theme.d_inline or preformatted ): new_line.extend(rendering) elif d_inline or d_inline_block: if d_inline: tokens = list(fragment_list_to_words(rendering)) else: tokens = [rendering] for token in tokens: token_lines = list(split_lines(token)) token_width = max(fragment_list_width(line) for line in token_lines) token_height = len(token_lines) # Deal with floats float_width_right = ( fragment_list_width(float_lines_right[0]) if float_lines_right else 0 ) float_width_left = ( fragment_list_width(float_lines_left[0]) if float_lines_left else 0 ) # If we have floats, transform the current new line and add one row # from each active float if ( new_line and (content_width - float_width_left - float_width_right) - left - token_width < 0 ): new_rows = list(split_lines(new_line)) new_line_width = max( fragment_list_width(line) for line in new_rows ) transformed_rows = [] for ft_left, ft_middle, ft_right in zip_longest( float_lines_left[:line_height], ( pad( row, char=" ", style=parent_theme.style, width=new_line_width, ) for row in new_rows ), float_lines_right[:line_height], fillvalue=empty, ): line_width = ( content_width - fragment_list_width(ft_left) - fragment_list_width(ft_right) ) transformed_rows.append( [ *ft_left, *align( ft_middle, how=parent_theme.text_align, width=line_width, style=parent_theme.style, placeholder="", ), *ft_right, ] ) float_lines_left = float_lines_left[line_height:] float_lines_right = float_lines_right[line_height:] # Manually flush the transformed lines if ft: ft = join_lines([ft, *transformed_rows]) else: ft = join_lines(transformed_rows) baseline = 0 new_rows = [[]] left = 0 line_height = 1 new_line = [] if line_height == token_height == 1 or not new_line: new_line.extend(token) new_rows = [new_line] baseline = int(theme.vertical_align * (token_height - 1)) line_height = max(line_height, token_height) else: new_line, baseline = concat( ft_a=new_line, ft_b=token, baseline_a=baseline, baseline_b=int(theme.vertical_align * (token_height - 1)), style=parent_theme.style, ) new_rows = list(split_lines(new_line)) line_height = len(new_rows) left += token_width # Otherwise we are rendering a block-like element, which gets added to the # end of the output else: # Flush the latest line flush() # Start block elements on a new line if ft and d_blocky and last_char(ft) != "\n": ft.append(("", "\n")) ft.extend(rendering) # line_height = len(list(split_lines(rendering))) # ft.extend( # concat( # concat(join_lines( float_lines_left[:line_height]), rendering)[0], # join_lines(float_lines_right[:line_height]), # )[0] # ) # float_lines_left = float_lines_left[line_height:] # float_lines_right = float_lines_right[line_height:] line_height = 1 left = 0 # On "clear", draw the rest of the floats if float_lines_left or float_lines_right: for ft_left, ft_middle, ft_right in zip_longest( float_lines_left, split_lines(new_line[:]), float_lines_right, fillvalue=empty, ): float_width_right = ( fragment_list_width(float_lines_right[0]) if float_lines_right else 0 ) float_width_left = ( fragment_list_width(float_lines_left[0]) if float_lines_left else 0 ) line_width = ( content_width - fragment_list_width(ft_left) - fragment_list_width(ft_right) ) row = [ *ft_left, *align( ft_middle, how=parent_theme.text_align, width=line_width, style=parent_theme.style + " nounderline", placeholder="", ), *ft_right, ] ft = join_lines([ft, row]) if ft else row new_line = [] # Flush any current lines flush() # Draw flex elements # if parent_theme.get("flex") and parent_theme.get("flex-direction") == "column": # table = Table(border=Invisible, collapse_empty_borders=True) # row = table.new_row() # for output in outputs: # row.new_cell(output) # ft = table.render(available_width) # # else: # ft = sum(outputs, start=ft) return ft async def format_element( self, ft: StyleAndTextTuples, element: Node, left: int = 0, fill: bool = True, align_content: bool = True, ) -> StyleAndTextTuples: """Format an element's content based on its theme.""" theme = element.theme parent_theme = theme.parent_theme d_blocky = theme.d_blocky d_inline = theme.d_inline d_inline_block = theme.d_inline_block preformatted = theme.preformatted content_width = theme.content_width content_height = theme.content_height # Apply style to inline elements # if d_inline: # ft = apply_style(ft, theme.style) # If an element should not overflow it's width / height, truncate it if not d_inline and not preformatted: if theme.get("overflow_x") == "hidden": ft = truncate(ft, content_width, placeholder="", ignore_whitespace=True) elif theme.get("overflow_x") == "auto": ft = truncate( ft, content_width, placeholder="▹", ignore_whitespace=True, style=theme.style, ) else: ft = truncate( ft, content_width, placeholder="", ignore_whitespace=True, style=theme.style, ) # Truncate or expand the height overflow_y = theme.get("overflow_y") in {"hidden", "auto"} pad_height = d_blocky and theme.height is not None if overflow_y or pad_height: target_height = None if (min_height := theme.min_height) and min_height > content_height: target_height = min_height if (max_height := theme.max_height) and max_height < content_height: target_height = max_height elif height := theme.height: target_height = height if target_height is not None: # Truncate elements with hidden overflows if overflow_y: lines = [] for i, line in enumerate(split_lines(ft)): if i <= target_height: lines.append(line) else: lines = list(split_lines(ft)) # Pad height of block elements to theme height if pad_height and len(lines) < target_height: lines.extend([[]] * (target_height - len(lines))) ft = join_lines(lines) # Align content if align_content and d_blocky: alignment = theme.text_align if alignment != FormattedTextAlign.LEFT: ft = align( ft, alignment, width=None if d_inline_block else content_width, style=theme.style, ignore_whitespace=True, placeholder="", ) # # Fill space around block elements so they fill the content width if ft and ((fill and d_blocky and not theme.d_table) or d_inline_block): pad_width = None if d_blocky: pad_width = content_width elif d_inline_block: pad_width = max_line_width(ft) if theme.width is None else content_width if pad_width is not None: style = theme.style ft = pad( ft, width=round(pad_width), char=" ", style=style, ) # Use the rendered content width from now on for inline elements if d_inline_block or d_inline: content_width = max_line_width(ft) # Add padding & border if d_blocky or d_inline_block: padding = theme.padding border_visibility = theme.border_visibility if (any(padding) or any(border_visibility)) and not ( theme.d_table and theme.border_collapse ): ft = add_border( ft, style=theme.style, border_grid=theme.border_grid, width=content_width if not ft else None, border_visibility=border_visibility, border_style=theme.border_style, padding=padding, ) # Draw borders and padding on text inside inline elements elif element.name == "::text": padding = theme.padding border_visibility = theme.border_visibility if ( padding.left or padding.right or border_visibility.left or border_visibility.right ): if not element.is_first_child_node: border_visibility = border_visibility._replace(left=False) padding = padding._replace(left=0) if not element.is_last_child_node: border_visibility = border_visibility._replace(right=False) padding = padding._replace(right=0) if any(padding) or any(border_visibility): ft = add_border( ft, style=theme.style, border_grid=theme.border_grid, width=content_width if not ft else None, border_visibility=border_visibility, border_style=theme.border_style, padding=padding, ) # The "::marker" element is drawn in the margin, before any padding # If the element has no margin, it can end up in the parent's padding # We use [ReverseOverwrite] fragments to ensure the marker is ignored # now and written over the margin later. if element.marker is not None: marker_ft = await self.render_element( element.marker, available_width=99999, available_height=theme.available_height, left=0, fill=False, align_content=False, ) ft = [ *apply_style(marker_ft, "[ReverseOverwrite]"), *ft, ] parent_style = parent_theme.style if parent_theme else "" # Render the margin # if d_blocky and (alignment := theme.block_align) != FormattedTextAlign.LEFT: if (alignment := theme.block_align) != FormattedTextAlign.LEFT: # Center block contents if margin_left and margin_right are "auto" ft = align( ft, how=alignment, width=theme.available_width, style=parent_style, placeholder="", ) elif any(margin := theme.margin): ft = add_border( ft=ft, style=theme.style, border_visibility=DiBool.from_value(False), padding=margin, padding_style=parent_style, ) # Apply mouse handler to links if ( (parent := element.parent) and parent.name == "a" and callable(handler := self.mouse_handler) and (href := parent.attrs.get("href")) ): element.attrs["_link_path"] = self.base.joinuri(href) element.attrs["title"] = parent.attrs.get("title") ft = cast( "StyleAndTextTuples", [ (style, text, *(rest or [partial(handler, element)])) for style, text, *rest in ft ], ) return ft def __pt_formatted_text__(self) -> StyleAndTextTuples: """Return formatted text.""" if not self.formatted_text: self.render(width=None, height=None) return self.formatted_text def strip( ft: StyleAndTextTuples, left: bool = True, right: bool = True, chars: str | None = None, only_unstyled: bool = False, ) -> StyleAndTextTuples: """Strip whitespace (or a given character) from the ends of formatted text. Args: ft: The formatted text to strip left: If :py:const:`True`, strip from the left side of the input right: If :py:const:`True`, strip from the right side of the input chars: The character to strip. If :py:const:`None`, strips whitespace only_unstyled: If :py:const:`True`, only strip unstyled fragments Returns: The stripped formatted text """ result = ft[:] for toggle, index, strip_func in [(left, 0, str.lstrip), (right, -1, str.rstrip)]: if result and toggle: text = strip_func(result[index][1], chars) while result and not text: del result[index] if not result: break text = strip_func(result[index][1], chars) if result and "[ZeroWidthEscape]" not in result[index][0]: result[index] = (result[index][0], text) return result The provided code snippet includes necessary dependencies for implementing the `parse_style_sheet` function. Write a Python function `def parse_style_sheet(css_str: str, dom: HTML, condition: Filter = always) -> None` to solve the following problem: Collect all CSS styles from style tags. Here is the function: def parse_style_sheet(css_str: str, dom: HTML, condition: Filter = always) -> None: """Collect all CSS styles from style tags.""" dom_css = dom.css # Remove whitespace and newlines # css_str = css_str.strip().replace("\n", "") css_str = re.sub(r"\s*\n\s*", " ", css_str) # Remove comments css_str = re.sub(r"\/\*[^\*]+\*\/", "", css_str) # Replace ':before' and ':after' with '::before' and '::after' # for compatibility with old CSS and to make root selector work css_str = re.sub("(?<!:):(?=before|after|root)", "::", css_str) def parse_part(part_condition: Filter, css_str: str) -> None: """Parse a group of CSS rules.""" if css_str: css_str = css_str.replace("\n", "").strip() if css_str: for rule in css_str.rstrip("}").split("}"): selectors, _, content = rule.partition("{") content = content.strip().rstrip(";") rule_content = parse_css_content(content) if rule_content: parsed_selectors = tuple( tuple( CssSelector(**m.groupdict()) for m in _SELECTOR_RE.finditer(selector.strip()) ) for selector in map(str.strip, selectors.split(",")) ) rules = dom_css.setdefault(part_condition, {}) if parsed_selectors in rules: rules[parsed_selectors].update(rule_content) else: rules[parsed_selectors] = rule_content # Split out nested at-rules - we need to process them separately for part in _AT_RULE_RE.split(css_str): if ( part and part[0] == "@" and (m := _NESTED_AT_RULE_RE.match(part)) is not None ): m_dict = m.groupdict() # Process '@media' queries if m_dict["identifier"] == "media": # Split each query - separated by "or" or "," queries = re.split("(?: or |,)", m_dict["rule"]) query_conditions: Filter = never for query in queries: # Each query can be the logical sum of multiple targets target_conditions: Filter = always for target in query.split(" and "): if ( target_m := _MEDIA_QUERY_TARGET_RE.match(target) ) is not None: target_m_dict = target_m.groupdict() # Check for media type conditions if (media_type := target_m_dict["type"]) is not None: target_conditions &= ( always if media_type in {"all", "screen"} else never ) # Check for media feature conditions elif ( media_feature := target_m_dict["feature"] ) is not None: target_conditions &= parse_media_condition( media_feature, dom ) # Check for logical 'NOT' inverting the target condition if target_m_dict["invert"]: target_conditions = ~target_conditions # Logical OR of all media queries query_conditions |= target_conditions # Parse the @media CSS block (may contain nested at-rules) parse_style_sheet(m_dict["part"], dom, condition & query_conditions) # Parse the CSS and always use it else: parse_part(condition, part)
Collect all CSS styles from style tags.
6,935
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr The provided code snippet includes necessary dependencies for implementing the `last_char` function. Write a Python function `def last_char(ft: StyleAndTextTuples) -> str | None` to solve the following problem: Retrieve the last character of formatted text. Here is the function: def last_char(ft: StyleAndTextTuples) -> str | None: """Retrieve the last character of formatted text.""" for frag in reversed(ft): text = frag[1] for c in reversed(text): if c: return c return None
Retrieve the last character of formatted text.
6,936
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr The provided code snippet includes necessary dependencies for implementing the `apply_style` function. Write a Python function `def apply_style(ft: StyleAndTextTuples, style: str) -> StyleAndTextTuples` to solve the following problem: Apply a style to formatted text. Here is the function: def apply_style(ft: StyleAndTextTuples, style: str) -> StyleAndTextTuples: """Apply a style to formatted text.""" return [ ( f"{fragment_style} {style}" if "[ZeroWidthEscape]" not in fragment_style else fragment_style, text, ) for (fragment_style, text, *_) in ft ]
Apply a style to formatted text.
6,937
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr class FormattedTextVerticalAlign(Enum): """Vertical alignment of formatted text.""" TOP = "top" MIDDLE = "middle" BOTTOM = "bottom" def fragment_list_width(fragments: StyleAndTextTuples) -> int: """Return the character width of this text fragment list. Takes double width characters into account, and ignore special fragments: * ZeroWidthEscape * ReverseOverwrite Args: fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples. Returns: The width of the fragment list """ return sum( get_cwidth(c) for item in ( frag for frag in fragments if not any(x in frag[0] for x in _ZERO_WIDTH_FRAGMENTS) ) for c in item[1] ) The provided code snippet includes necessary dependencies for implementing the `valign` function. Write a Python function `def valign( ft: StyleAndTextTuples, how: FormattedTextVerticalAlign = FormattedTextVerticalAlign.MIDDLE, height: int | None = None, style: str = "", ) -> StyleAndTextTuples` to solve the following problem: Align formatted text vertically. Here is the function: def valign( ft: StyleAndTextTuples, how: FormattedTextVerticalAlign = FormattedTextVerticalAlign.MIDDLE, height: int | None = None, style: str = "", ) -> StyleAndTextTuples: """Align formatted text vertically.""" if height is None: return ft lines = list(split_lines(ft)) width = max(fragment_list_width(line) for line in lines) remaining = height - len(lines) if how == FormattedTextVerticalAlign.TOP: above = 0 below = remaining elif how == FormattedTextVerticalAlign.MIDDLE: above = remaining // 2 below = remaining - above else: above = remaining below = 0 return [ (style, ((" " * width) + "\n") * above), *ft, (style, ("\n" + (" " * width)) * below), ]
Align formatted text vertically.
6,938
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr def max_line_width(ft: StyleAndTextTuples) -> int: """Calculate the length of the longest line in formatted text.""" return max(fragment_list_width(line) for line in split_lines(ft)) def pad( ft: StyleAndTextTuples, width: int | None = None, char: str = " ", style: str = "", ) -> StyleAndTextTuples: """Fill space at the end of lines.""" if width is None: width = max_line_width(ft) filled_output = [] for line in split_lines(ft): if (remaining := (width - fragment_list_width(line))) > 0: line.append((style + " nounderline", (char * remaining))) filled_output.append(line) return join_lines(filled_output) def paste( ft_top: StyleAndTextTuples, ft_bottom: StyleAndTextTuples, row: int = 0, col: int = 0, transparent: bool = False, ) -> StyleAndTextTuples: """Pate formatted text on top of other formatted text.""" ft: StyleAndTextTuples = [] top_lines = dict(enumerate(split_lines(ft_top), start=row)) for y, line_b in enumerate(split_lines(ft_bottom)): if y in top_lines: line_t = top_lines[y] line_t_width = fragment_list_width(line_t) ft += substring(line_b, 0, col) if transparent: chars_t = explode_text_fragments(line_t) chars_b = explode_text_fragments( substring(line_b, col, col + line_t_width) ) for char_t, char_b in zip(chars_t, chars_b): if char_t[0] == "" and char_t[1] == " ": ft.append(char_b) else: ft.append(char_t) else: ft += line_t ft += substring(line_b, col + line_t_width) else: ft += line_b ft.append(("", "\n")) if ft: ft.pop() return ft The provided code snippet includes necessary dependencies for implementing the `concat` function. Write a Python function `def concat( ft_a: StyleAndTextTuples, ft_b: StyleAndTextTuples, baseline_a: int = 0, baseline_b: int = 0, style: str = "", ) -> tuple[StyleAndTextTuples, int]` to solve the following problem: Concatenate two blocks of formatted text, aligning at a given baseline. Args: ft_a: The first block of formatted text to combine ft_b: The second block of formatted text to combine baseline_a: The row to use to align the first block of formatted text with the second, counted in lines down from the top of the block baseline_b: The row to use to align the second block of formatted text with the second, counted in lines down from the top of the block style: The style to use for any extra lines added Returns: A tuple containing the combined formatted text and the new baseline position Here is the function: def concat( ft_a: StyleAndTextTuples, ft_b: StyleAndTextTuples, baseline_a: int = 0, baseline_b: int = 0, style: str = "", ) -> tuple[StyleAndTextTuples, int]: """Concatenate two blocks of formatted text, aligning at a given baseline. Args: ft_a: The first block of formatted text to combine ft_b: The second block of formatted text to combine baseline_a: The row to use to align the first block of formatted text with the second, counted in lines down from the top of the block baseline_b: The row to use to align the second block of formatted text with the second, counted in lines down from the top of the block style: The style to use for any extra lines added Returns: A tuple containing the combined formatted text and the new baseline position """ rows_a = len(list(split_lines(ft_a))) - 1 rows_b = len(list(split_lines(ft_b))) - 1 cols_a = max_line_width(ft_a) lines_above = max(baseline_a, baseline_b) - min(baseline_a, baseline_b) lines_below = max(rows_a - baseline_a, rows_b - baseline_b) - min( rows_a - baseline_a, rows_b - baseline_b, ) if baseline_a < baseline_b: ft_a = [("", lines_above * "\n"), *ft_a] elif baseline_a > baseline_b: ft_b = [("", lines_above * "\n"), *ft_b] if rows_a - baseline_a < rows_b - baseline_b: ft_a = [*ft_a, ("", lines_below * "\n")] elif rows_a - baseline_a > rows_b - baseline_b: ft_b = [*ft_b, ("", lines_below * "\n")] ft = paste( ft_b, pad(ft_a, style=style), row=0, col=cols_a, ) new_baseline = max(baseline_a, baseline_b) return ft, new_baseline
Concatenate two blocks of formatted text, aligning at a given baseline. Args: ft_a: The first block of formatted text to combine ft_b: The second block of formatted text to combine baseline_a: The row to use to align the first block of formatted text with the second, counted in lines down from the top of the block baseline_b: The row to use to align the second block of formatted text with the second, counted in lines down from the top of the block style: The style to use for any extra lines added Returns: A tuple containing the combined formatted text and the new baseline position
6,939
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr The provided code snippet includes necessary dependencies for implementing the `indent` function. Write a Python function `def indent( ft: StyleAndTextTuples, margin: str = " ", style: str = "", skip_first: bool = False, ) -> StyleAndTextTuples` to solve the following problem: Indent formatted text with a given margin. Args: ft: The formatted text to strip margin: The margin string to add style: The style to apply to the margin skip_first: If :py:const:`True`, the first line is skipped Returns: The indented formatted text Here is the function: def indent( ft: StyleAndTextTuples, margin: str = " ", style: str = "", skip_first: bool = False, ) -> StyleAndTextTuples: """Indent formatted text with a given margin. Args: ft: The formatted text to strip margin: The margin string to add style: The style to apply to the margin skip_first: If :py:const:`True`, the first line is skipped Returns: The indented formatted text """ result: StyleAndTextTuples = [] for i, line in enumerate(split_lines(ft)): if not (i == 0 and skip_first): result.append((style, margin)) result += line result.append(("", "\n")) result.pop() return result
Indent formatted text with a given margin. Args: ft: The formatted text to strip margin: The margin string to add style: The style to apply to the margin skip_first: If :py:const:`True`, the first line is skipped Returns: The indented formatted text
6,940
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr class FormattedTextAlign(Enum): """Alignment of formatted text.""" LEFT = "left" RIGHT = "right" CENTER = "center" def max_line_width(ft: StyleAndTextTuples) -> int: """Calculate the length of the longest line in formatted text.""" return max(fragment_list_width(line) for line in split_lines(ft)) def align( ft: StyleAndTextTuples, how: FormattedTextAlign = FormattedTextAlign.LEFT, width: int | None = None, style: str = "", placeholder: str = "…", ignore_whitespace: bool = False, ) -> StyleAndTextTuples: """Align formatted text at a given width. Args: how: The alignment direction ft: The formatted text to strip width: The width to which the output should be padded. If :py:const:`None`, the length of the longest line is used style: The style to apply to the padding placeholder: The string that will appear at the end of a truncated line ignore_whitespace: If True, whitespace will be ignored Returns: The aligned formatted text """ style = f"{style} nounderline" lines = split_lines(ft) if width is None: lines = [strip(line) if ignore_whitespace else line for line in split_lines(ft)] width = max(fragment_list_width(line) for line in lines) result: StyleAndTextTuples = [] for line in lines: line_width = fragment_list_width(line) # Truncate the line if it is too long if line_width > width: result += truncate(line, width, style, placeholder, ignore_whitespace) else: pad_left = pad_right = 0 if how == FormattedTextAlign.CENTER: pad_left = (width - line_width) // 2 pad_right = width - line_width - pad_left elif how == FormattedTextAlign.LEFT: pad_right = width - line_width elif how == FormattedTextAlign.RIGHT: pad_left = width - line_width if pad_left: result.append((style, " " * pad_left)) result.extend(line) if pad_right: result.append((style, " " * pad_right)) result.append((style, "\n")) result.pop() return result def join_lines(fragments: list[StyleAndTextTuples]) -> StyleAndTextTuples: """Join a list of lines of formatted text.""" ft = [] if fragments: for line in fragments[:-1]: ft.extend(line) ft.append(("", "\n")) lines = list(split_lines(fragments[-1])) for line in lines[:-1]: ft.extend(line) ft.append(("", "\n")) ft.extend(lines[-1]) return ft class GridStyle: """A collection of characters which can be used to draw a grid.""" class _BorderLineChars(NamedTuple): LEFT: str MID: str SPLIT: str RIGHT: str _grid_cache: FastDictCache[tuple[GridStyle, GridStyle], GridStyle] = FastDictCache(get_value=_combine_grids) def __init__( self, line_style: LineStyle = NoLine, mask: Mask = Masks.grid ) -> None: """Create a new :py:class:`GridStyle` instance. Args: line_style: The line style to use to construct the grid mask: A mask which can be used to exclude certain character from the grid """ self.grid = { part: GridChar( *((line_style if x else NoLine) for x in mask.mask[part]) ) for part in GridPart } self.mask = mask def TOP(self) -> _BorderLineChars: """Allow dotted attribute access to the top grid row.""" return self._BorderLineChars( get_grid_char(self.grid[GridPart.TOP_LEFT]), get_grid_char(self.grid[GridPart.TOP_MID]), get_grid_char(self.grid[GridPart.TOP_SPLIT]), get_grid_char(self.grid[GridPart.TOP_RIGHT]), ) def MID(self) -> _BorderLineChars: """Allow dotted attribute access to the mid grid row.""" return self._BorderLineChars( get_grid_char(self.grid[GridPart.MID_LEFT]), get_grid_char(self.grid[GridPart.MID_MID]), get_grid_char(self.grid[GridPart.MID_SPLIT]), get_grid_char(self.grid[GridPart.MID_RIGHT]), ) def SPLIT(self) -> _BorderLineChars: """Allow dotted attribute access to the split grid row.""" return self._BorderLineChars( get_grid_char(self.grid[GridPart.SPLIT_LEFT]), get_grid_char(self.grid[GridPart.SPLIT_MID]), get_grid_char(self.grid[GridPart.SPLIT_SPLIT]), get_grid_char(self.grid[GridPart.SPLIT_RIGHT]), ) def BOTTOM(self) -> _BorderLineChars: """Allow dotted attribute access to the bottom grid row.""" return self._BorderLineChars( get_grid_char(self.grid[GridPart.BOTTOM_LEFT]), get_grid_char(self.grid[GridPart.BOTTOM_MID]), get_grid_char(self.grid[GridPart.BOTTOM_SPLIT]), get_grid_char(self.grid[GridPart.BOTTOM_RIGHT]), ) def HORIZONTAL(self) -> str: """For compatibility with :class:`prompt_toolkit.widgets.base.Border`.""" return self.SPLIT_MID def VERTICAL(self) -> str: """For compatibility with :class:`prompt_toolkit.widgets.base.Border`.""" return self.MID_SPLIT def __getattr__(self, value: str) -> str: """Allow the parts of the grid to be accessed as attributes by name.""" key = getattr(GridPart, value) return get_grid_char(self.grid[key]) def __dir__(self) -> list: """Lit the public attributes of the grid style.""" return [x.name for x in GridPart] + ["TOP", "MID", "SPLIT", "BOTTOM"] def __add__(self, other: GridStyle) -> GridStyle: """Combine two grid styles.""" return self._grid_cache[self, other] def __repr__(self) -> str: """Return a string representation of the grid style.""" return "\n".join( "".join( get_grid_char(char_key) for char_key in list(self.grid.values())[i * 4 : (i + 1) * 4] ) for i in range(4) ) ThinGrid = ThinLine.grid class DiBool(NamedTuple): """A tuple of four bools with directions.""" top: bool = False right: bool = False bottom: bool = False left: bool = False def from_value(cls, value: bool) -> DiBool: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) class DiInt(NamedTuple): """A tuple of four integers with directions.""" top: int = 0 right: int = 0 bottom: int = 0 left: int = 0 def from_value(cls, value: int) -> DiInt: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) class DiStr(NamedTuple): """A tuple of four strings with directions.""" top: str = "" right: str = "" bottom: str = "" left: str = "" def from_value(cls, value: str) -> DiStr: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `add_border` function. Write a Python function `def add_border( ft: StyleAndTextTuples, width: int | None = None, style: str = "", border_grid: GridStyle = ThinGrid, border_visibility: DiBool | bool = True, border_style: DiStr | str = "", padding: DiInt | int = 0, padding_style: DiStr | str = "", ) -> StyleAndTextTuples` to solve the following problem: Add a border around formatted text. Args: ft: The formatted text to enclose with a border width: The target width including the border and padding style: The style to apply to the content background border_grid: The grid style to use for the border border_visibility: Determines which edges should receive a border border_style: The style to apply to the border padding: The width of spacing to apply between the content and the border padding_style: The style to apply to the border Returns: The indented formatted text Here is the function: def add_border( ft: StyleAndTextTuples, width: int | None = None, style: str = "", border_grid: GridStyle = ThinGrid, border_visibility: DiBool | bool = True, border_style: DiStr | str = "", padding: DiInt | int = 0, padding_style: DiStr | str = "", ) -> StyleAndTextTuples: """Add a border around formatted text. Args: ft: The formatted text to enclose with a border width: The target width including the border and padding style: The style to apply to the content background border_grid: The grid style to use for the border border_visibility: Determines which edges should receive a border border_style: The style to apply to the border padding: The width of spacing to apply between the content and the border padding_style: The style to apply to the border Returns: The indented formatted text """ if isinstance(border_visibility, bool): border_visibility = DiBool.from_value(border_visibility) if isinstance(padding, int): padding = DiInt.from_value(padding) if isinstance(border_style, str): border_style = DiStr.from_value(border_style) if isinstance(padding_style, str): padding_style = DiStr.from_value(padding_style) edge_width = ( border_visibility.left + border_visibility.right + padding.left + padding.right ) if width is None: inner_width = max_line_width(ft) width = inner_width + edge_width else: inner_width = width - edge_width # Ensure all lines are the same length if ft: ft = align( ft, FormattedTextAlign.LEFT, width=inner_width, style=style, ) output: list[StyleAndTextTuples] = [] base_style = f"{style} nounderline" # Add top row if border_visibility.top: new_line: StyleAndTextTuples = [] if border_visibility.left: new_line.append( ( f"{base_style} class:border,left,top {border_style.top} {border_style.left}", border_grid.TOP_LEFT, ) ) new_line.append( ( f"{base_style} class:border,top {border_style.top}", border_grid.TOP_MID * (inner_width + padding.left + padding.right), ) ) if border_visibility.right: new_line.append( ( f"{base_style} class:border,right,top {border_style.top} {border_style.right}", border_grid.TOP_RIGHT, ) ) output.append(new_line) # Add top padding for _ in range(padding.top or 0): new_line = [] if border_visibility.left: new_line.append( ( f"{base_style} class:border,left {border_style.left}", border_grid.MID_LEFT, ) ) if padding.top: new_line.append( ( f"{base_style} class:padding,top {padding_style.top}", " " * (inner_width + padding.left + padding.right), ) ) if border_visibility.right: new_line.append( ( f"{base_style} class:border,right {border_style.right}", border_grid.MID_RIGHT, ) ) output.append(new_line) # Add contents with left & right padding if ft: for line in split_lines(ft): new_line = [] if border_visibility.left: new_line.append( ( f"{base_style} class:border,left {border_style.left}", border_grid.MID_LEFT, ) ) if padding.left: new_line.append( ( f"{base_style} class:padding,left {padding_style.left}", " " * (padding.left or 0), ) ) new_line.extend(line) if padding.right: new_line.append( ( f"{base_style} class:padding,right {padding_style.right}", " " * (padding.right or 0), ) ) if border_visibility.right: new_line.append( ( f"{base_style} class:border,right {border_style.right}", border_grid.MID_RIGHT, ) ) output.append(new_line) # Add bottom padding for _ in range(int(padding.bottom) or 0): new_line = [] if border_visibility.left: new_line.append( ( f"{base_style} class:border,left {border_style.left}", border_grid.MID_LEFT, ) ) if padding.bottom: new_line.append( ( f"{base_style} class:padding,bottom {padding_style.bottom}", " " * (inner_width + padding.left + padding.right), ) ) if border_visibility.right: new_line.append( ( f"{base_style} class:border,right {border_style.right}", border_grid.MID_RIGHT, ) ) output.append(new_line) # Add bottom row if border_visibility.bottom: new_line = [] if border_visibility.left: new_line.append( ( f"{base_style} class:border,left,bottom {border_style.bottom} {border_style.left}", border_grid.BOTTOM_LEFT, ) ) new_line.append( ( f"{base_style} class:border,bottom {border_style.bottom}", border_grid.BOTTOM_MID * (inner_width + padding.left + padding.right), ) ) if border_visibility.right: new_line.append( ( f"{base_style} class:border,right,bottom {border_style.bottom} {border_style.right}", border_grid.BOTTOM_RIGHT, ) ) output.append(new_line) return join_lines(output)
Add a border around formatted text. Args: ft: The formatted text to enclose with a border width: The target width including the border and padding style: The style to apply to the content background border_grid: The grid style to use for the border border_visibility: Determines which edges should receive a border border_style: The style to apply to the border padding: The width of spacing to apply between the content and the border padding_style: The style to apply to the border Returns: The indented formatted text
6,941
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr The provided code snippet includes necessary dependencies for implementing the `lex` function. Write a Python function `def lex(ft: StyleAndTextTuples, lexer_name: str) -> StyleAndTextTuples` to solve the following problem: Format formatted text using a named :py:mod:`pygments` lexer. Here is the function: def lex(ft: StyleAndTextTuples, lexer_name: str) -> StyleAndTextTuples: """Format formatted text using a named :py:mod:`pygments` lexer.""" from prompt_toolkit.lexers.pygments import _token_cache try: lexer = get_lexer_by_name(lexer_name) except ClassNotFound: return ft else: output: StyleAndTextTuples = [] for style, text, *_rest in ft: for _, t, v in lexer.get_tokens_unprocessed(text): output.append((f"{style} {_token_cache[t]}", v)) return output
Format formatted text using a named :py:mod:`pygments` lexer.
6,942
from __future__ import annotations import re from enum import Enum from typing import Iterable, cast from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples from prompt_toolkit.formatted_text.utils import ( fragment_list_to_text, split_lines, to_plain_text, ) from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.utils import get_cwidth from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from euporie.core.border import GridStyle, ThinGrid from euporie.core.data_structures import DiBool, DiInt, DiStr def fragment_list_width(fragments: StyleAndTextTuples) -> int: """Return the character width of this text fragment list. Takes double width characters into account, and ignore special fragments: * ZeroWidthEscape * ReverseOverwrite Args: fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples. Returns: The width of the fragment list """ return sum( get_cwidth(c) for item in ( frag for frag in fragments if not any(x in frag[0] for x in _ZERO_WIDTH_FRAGMENTS) ) for c in item[1] ) def substring( ft: StyleAndTextTuples, start: int | None = None, end: int | None = None ) -> StyleAndTextTuples: """Extract a substring from formatted text.""" output: StyleAndTextTuples = [] if start is None: start = 0 if end is None or start < 0 or end < 0: width = fragment_list_width(ft) if end is None: end = width if start < 0: start = width + start if end < 0: end = width + end x = 0 for style, text, *extra in ft: if any(x in style for x in _ZERO_WIDTH_FRAGMENTS): frag_len = 0 else: frag_len = sum(get_cwidth(c) for c in text) if (start <= x + frag_len <= end + frag_len) and ( (text := text[max(0, start - x) : end - x]) or style ): output.append(cast("OneStyleAndTextTuple", (style, text, *extra))) x += frag_len return output def join_lines(fragments: list[StyleAndTextTuples]) -> StyleAndTextTuples: """Join a list of lines of formatted text.""" ft = [] if fragments: for line in fragments[:-1]: ft.extend(line) ft.append(("", "\n")) lines = list(split_lines(fragments[-1])) for line in lines[:-1]: ft.extend(line) ft.append(("", "\n")) ft.extend(lines[-1]) return ft The provided code snippet includes necessary dependencies for implementing the `apply_reverse_overwrites` function. Write a Python function `def apply_reverse_overwrites(ft: StyleAndTextTuples) -> StyleAndTextTuples` to solve the following problem: Write fragments tagged with "[ReverseOverwrite]" over text to their left. Here is the function: def apply_reverse_overwrites(ft: StyleAndTextTuples) -> StyleAndTextTuples: """Write fragments tagged with "[ReverseOverwrite]" over text to their left.""" def _apply_overwrites( overwrites: StyleAndTextTuples, transformed_line: StyleAndTextTuples ) -> tuple[StyleAndTextTuples, StyleAndTextTuples]: """Pate `overwrites` over the end of `transformed_line`.""" # Remove the ``[ReverseOverwrite]`` from the overwrite fragments top = cast( StyleAndTextTuples, [(x[0].replace("[ReverseOverwrite]", ""), *x[1:]) for x in overwrites], ) top_width = fragment_list_width(top) if fragment_list_width(transformed_line) >= top_width: # Replace the end of the line with the overwrite-fragments if the overwrite # -fragments are shorter than the line transformed_line = [*substring(transformed_line, 0, -top_width), *top] else: # Otherwise, replace the whole line with the overwrites transformed_line = overwrites[:] overwrites.clear() return overwrites, transformed_line transformed_lines = [] for untransformed_line in split_lines(ft): overwrites = [] transformed_line: StyleAndTextTuples = [] for frag in untransformed_line: # Collect overwrite fragments if "[ReverseOverwrite]" in frag[0]: overwrites.append(frag) continue # If we have any overwrite-fragments, apply them on top of the current line if overwrites: overwrites, transformed_line = _apply_overwrites( overwrites, transformed_line ) # Collect non-overwrite fragments transformed_line.append(frag) # Add this list to transformed_lines.append(transformed_line) return join_lines(transformed_lines)
Write fragments tagged with "[ReverseOverwrite]" over text to their left.
6,943
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) The provided code snippet includes necessary dependencies for implementing the `pairwise` function. Write a Python function `def pairwise(iterable: Iterable[PairT]) -> Iterator[tuple[PairT, PairT]]` to solve the following problem: Return successiver overlapping pairs from an iterable. Here is the function: def pairwise(iterable: Iterable[PairT]) -> Iterator[tuple[PairT, PairT]]: """Return successiver overlapping pairs from an iterable.""" a, b = tee(iterable) next(b, None) return zip(a, b)
Return successiver overlapping pairs from an iterable.
6,944
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) class Cell: """A table cell.""" def __init__( self, text: AnyFormattedText = "", row: Row | None = None, col: Col | None = None, colspan: int = 1, rowspan: int = 1, width: int | None = None, align: FormattedTextAlign | None = None, style: str = "", padding: DiInt | int = 0, border_line: DiLineStyle | LineStyle = ThinLine, border_style: DiStr | str = "", border_visibility: DiBool | bool | None = True, ) -> None: """Create a new table cell. Args: text: Text or formatted text to display in the cell row: The row to which this cell belongs col: The column to which this cell belongs colspan: The number of columns this cell spans rowspan: The number of row this cell spans width: The desired width of the cell align: How the text in the cell should be aligned style: The style to apply to the cell's contents padding: The padding around the contents of the cell border_line: The line to use for the borders border_style: The style to apply to the cell's borders border_visibility: The visibility of each border edge """ self.expands = self self.text = text self.row = row or DummyRow() self.col = col or DummyCol() self.colspan = colspan self.rowspan = rowspan self.width = width self.align = align self.style = style self.padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) self.border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) self.border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) self.border_visibility = ( DiBool( border_visibility, border_visibility, border_visibility, border_visibility, ) if isinstance(border_visibility, bool) else border_visibility ) self._col_index: int | None = None self._row_index: int | None = None def padding(self) -> DiInt: """The cell's padding.""" return self._padding def padding(self, padding: DiInt | int) -> None: """Set the cell's padding.""" self._padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) def border_line(self) -> DiLineStyle: """The cell's border line.""" return self._border_line def border_line(self, border_line: DiLineStyle | LineStyle) -> None: """Set the cell's border line.""" self._border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) def border_style(self) -> DiStr: """The cell's border style.""" return self._border_style def border_style(self, border_style: DiStr | str) -> None: """Set the cell's border style.""" self._border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) def __repr__(self) -> str: """Return a text representation of the cell.""" cell_text = to_plain_text(self.text) if len(cell_text) > 5: cell_text = cell_text[:4] + "…" return f"{self.__class__.__name__}({cell_text!r})" class SpacerCell(Cell): """A dummy cell to virtually occupy space when ``colspan`` or ``rowspan`` are used.""" def __init__( self, expands: Cell, span_row_index: int, span_col_index: int, text: AnyFormattedText = "", row: Row | None = None, col: Col | None = None, colspan: int = 1, rowspan: int = 1, width: int | None = None, align: FormattedTextAlign | None = None, style: str = "", padding: DiInt | int | None = None, border_line: DiLineStyle | LineStyle = NoLine, border_style: DiStr | str = "", border_visibility: DiBool | bool | None = None, ) -> None: """Create a new table cell. Args: expands: This should be reference to the spanning cell span_col_index: The index of a spacer cell inside a colspan span_row_index: The index of a spacer cell inside a rowspan text: Text or formatted text to display in the cell row: The row to which this cell belongs col: The column to which this cell belongs colspan: The number of columns this cell spans rowspan: The number of row this cell spans width: The desired width of the cell align: How the text in the cell should be aligned style: The style to apply to the cell's contents padding: The padding around the contents of the cell border_line: The line to use for the borders border_style: The style to apply to the cell's borders border_visibility: The visibility of each border edge """ super().__init__( text="", row=row, col=col, colspan=1, rowspan=1, width=None, align=align, style=expands.style, padding=0, border_line=expands.border_line, border_style=expands.border_style, border_visibility=expands.border_visibility, ) self.expands = expands self.span_row_index = span_row_index self.span_col_index = span_col_index class _Dummy(Cell): """A dummy cell with not content, padding or borders.""" def __init__( self, text: AnyFormattedText = "", row: Row | None = None, col: Col | None = None, colspan: int = 1, rowspan: int = 1, width: int | None = None, align: FormattedTextAlign | None = None, style: str = "", padding: DiInt | int = 0, border_line: DiLineStyle | LineStyle = NoLine, border_style: DiStr | str = "", border_visibility: DiBool | bool | None = None, ) -> None: """Create an dummy cells to fill empty space in a table.""" table = (row or col or DummyRow()).table background_style = table.background_style super().__init__( row=row, col=col, style=background_style, padding=0, border_line=NoLine, border_style=background_style, border_visibility=False, ) def __repr__(self) -> str: """Represent the cell instance as a string.""" return f"{self.__class__.__name__}()" NoLine = LineStyle("None", rank=(0, 0), visible=False) InvisibleLine = LineStyle("Invisible", rank=(9999, 9999), parent=NoLine, visible=False) class DiLineStyle(NamedTuple): """A description of a cell border: a :class:`LineStyle` for each edge.""" top: LineStyle = NoLine right: LineStyle = NoLine bottom: LineStyle = NoLine left: LineStyle = NoLine def from_value(cls, value: LineStyle) -> DiLineStyle: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `compute_border_line` function. Write a Python function `def compute_border_line(cell: Cell, render_count: int = 0) -> DiLineStyle` to solve the following problem: Compute a cell's border line. Here is the function: def compute_border_line(cell: Cell, render_count: int = 0) -> DiLineStyle: """Compute a cell's border line.""" if isinstance(cell, _Dummy): return DiLineStyle(NoLine, NoLine, NoLine, NoLine) output = {} row = cell.row col = cell.col table = cell.row.table row_cells = row.cells col_cells = col.cells cell_border_line = cell.border_line row_border_line = row.border_line col_border_line = col.border_line table_border_line = table.border_line if (value := row_border_line.top) is not NoLine or ( cell == col_cells[0] and (value := table_border_line.top) is not NoLine ): output["top"] = value if (value := row_border_line.bottom) is not NoLine or ( cell == col_cells[-1] and (value := table_border_line.bottom) is not NoLine ): output["bottom"] = value if (value := col_border_line.left) is not NoLine or ( cell == row_cells[0] and (value := table_border_line.left) is not NoLine ): output["left"] = value if (value := col_border_line.right) is not NoLine or ( cell == row_cells[-1] and (value := table_border_line.right) is not NoLine ): output["right"] = value for direction in ("top", "right", "bottom", "left"): if (value := getattr(cell_border_line, direction, NoLine)) is not NoLine: output[direction] = value if isinstance(cell, SpacerCell): expands = cell.expands # Set left border to invisible in colspan if 0 < cell.span_col_index < expands.colspan: output["left"] = InvisibleLine # Set top border to invisible in rowspan if 0 < cell.span_row_index < expands.rowspan: output["top"] = InvisibleLine return DiLineStyle(**output)
Compute a cell's border line.
6,945
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) class Col(RowCol): """A column in a table.""" _type = "col" span_type = "rowspan" def calculate_cell_width(cell: Cell, render_count: int = 0) -> int: """Compute the final width of a cell, including padding.""" if cell.colspan > 1: return 0 padding = compute_padding(cell, render_count) return ( (cell.width or max_line_width(compute_text(cell, render_count))) + padding.left + padding.right ) def compute_border_width(cell: Cell, render_count: int = 0) -> DiInt: """Compute the width of a cell's borders.""" if isinstance(cell, _Dummy): output = {"top": 0, "right": 0, "bottom": 0, "left": 0} else: output = {"top": 1, "right": 1, "bottom": 1, "left": 1} # XXX If don't understand why row needs to follow cell expansion but column doesn't row = cell.row col = cell.col table = row.table if row not in table._rows.values() or col not in table._cols.values(): # The table has not yet been fully constructed return DiInt(**output) row_index = table.rows.index(row) col_index = table.cols.index(col) row_cells_bv = [compute_border_visibility(cell, render_count) for cell in row.cells] col_cells_bv = [compute_border_visibility(cell, render_count) for cell in col.cells] for cell, cell_left in zip(row.cells, table.rows[row_index - 1].cells): if ( compute_border_visibility(cell).left or compute_border_visibility(cell_left).right ): break row_top_cells_bv = ( compute_border_visibility(cell, render_count) for cell in ( table.rows[row_index - 1].cells if row_index - 1 in table._rows else [] ) ) col_left_cells_bv = ( compute_border_visibility(cell, render_count) for cell in ( table.cols[col_index - 1].cells if col_index - 1 in table._cols else [] ) ) col_right_cells_bv = ( compute_border_visibility(cell, render_count) for cell in ( table.cols[col_index + 1].cells if col_index + 1 in table._cols else [] ) ) row_bottom_cells_bv = ( compute_border_visibility(cell, render_count) for cell in ( table.rows[row_index + 1].cells if row_index + 1 in table._rows else [] ) ) output["top"] = int( any( bv.top or (bv_other and bv_other.bottom) for bv, bv_other in zip_longest(row_cells_bv, row_top_cells_bv) ) ) output["right"] = int( any( bv.right or (bv_other and bv_other.left) for bv, bv_other in zip_longest(col_cells_bv, col_right_cells_bv) ) ) output["bottom"] = int( any( bv.bottom or (bv_other and bv_other.top) for bv, bv_other in zip_longest(row_cells_bv, row_bottom_cells_bv) ) ) output["left"] = int( any( bv.left or (bv_other and bv_other.right) for bv, bv_other in zip_longest(col_cells_bv, col_left_cells_bv) ) ) return DiInt(**output) The provided code snippet includes necessary dependencies for implementing the `calculate_col_widths` function. Write a Python function `def calculate_col_widths( cols: tuple[Col], width: Dimension, expand_to_width: bool, min_col_width: int = 2, render_count: int = 0, ) -> list[int]` to solve the following problem: Calculate column widths given the available space. Reduce the widest column until we fit in available width, or expand cells to to fill the available width. Args: cols: A list of columns in the table width: The desired width of the table expand_to_width: Whether the column should expand to fill the available width min_col_width: The minimum width allowed for a column render_count: The number of times the app has been rendered Returns: List of new column widths Here is the function: def calculate_col_widths( cols: tuple[Col], width: Dimension, expand_to_width: bool, min_col_width: int = 2, render_count: int = 0, ) -> list[int]: """Calculate column widths given the available space. Reduce the widest column until we fit in available width, or expand cells to to fill the available width. Args: cols: A list of columns in the table width: The desired width of the table expand_to_width: Whether the column should expand to fill the available width min_col_width: The minimum width allowed for a column render_count: The number of times the app has been rendered Returns: List of new column widths """ # TODO - this function is too slow col_widths = [ max( min_col_width, *(calculate_cell_width(cell, render_count) for cell in col.cells), ) for col in cols ] def total_width(col_widths: list[int]) -> int: """Calculate the total width of the columns including borders.""" width = sum(col_widths) if cols: width += compute_border_width(cols[0].cells[0], render_count).left for _i, col in enumerate(cols): width += compute_border_width(col.cells[0], render_count).right return width def expand(target: int) -> None: """Expand the columns.""" max_width = max(target, len(col_widths) * min_col_width) while total_width(col_widths) < max_width: # Expand only columns which do not have a width set if possible # TODO - expand proportionately to given widths col_index_widths = [ (i, col_widths[i]) for i, col in enumerate(cols) if all(cell.width is None for cell in col.cells) ] if not col_index_widths: col_index_widths = list(enumerate(col_widths)) if col_index_widths: idxmin = min(col_index_widths, key=lambda x: x[1])[0] col_widths[idxmin] += 1 else: break def contract(target: int) -> None: """Contract the columns.""" max_width = max(target, len(col_widths) * min_col_width) while total_width(col_widths) > max_width: idxmax = max(enumerate(col_widths), key=lambda x: x[1])[0] col_widths[idxmax] -= 1 # Determine whether to expand or contract the table current_width = total_width(col_widths) if width.preferred_specified: if current_width < width.preferred: expand(width.preferred) elif current_width > width.preferred: contract(width.preferred) if width.max_specified: if current_width > width.max: contract(width.max) if current_width < width.max and expand_to_width: expand(width.max) if width.min_specified and current_width < width.min: expand(width.min) return col_widths
Calculate column widths given the available space. Reduce the widest column until we fit in available width, or expand cells to to fill the available width. Args: cols: A list of columns in the table width: The desired width of the table expand_to_width: Whether the column should expand to fill the available width min_col_width: The minimum width allowed for a column render_count: The number of times the app has been rendered Returns: List of new column widths
6,946
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) class GridChar(NamedTuple): """Repreentation of a grid node character. The four compass points represent the line style joining from the given direction. """ north: LineStyle east: LineStyle south: LineStyle west: LineStyle def get_grid_char(key: GridChar) -> str: """Return the character represented by a combination of :class:`LineStyles`.""" if key in _GRID_CHARS: return _GRID_CHARS[key] else: # If there is no matching character representation, replace the line style # whose parent has the highest ranking with the parent style until a character # is found m_key = list(key) while any(x.parent for x in m_key): parent_ranks = {(9999,) if line.parent == NoLine else line.parent.rank: i for i, line in enumerate(m_key) if line.parent} idx = parent_ranks[max(parent_ranks)] if parent := m_key[idx].parent: m_key[idx] = parent char = _GRID_CHARS.get(GridChar(*m_key)) if char: return char # If all else fails, return a space else: return " " class DiLineStyle(NamedTuple): """A description of a cell border: a :class:`LineStyle` for each edge.""" top: LineStyle = NoLine right: LineStyle = NoLine bottom: LineStyle = NoLine left: LineStyle = NoLine def from_value(cls, value: LineStyle) -> DiLineStyle: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `get_node` function. Write a Python function `def get_node( nw_bl: DiLineStyle, ne_bl: DiLineStyle, se_bl: DiLineStyle, sw_bl: DiLineStyle, ) -> str` to solve the following problem: Calculate which character to use at the intersection of four cells. Here is the function: def get_node( nw_bl: DiLineStyle, ne_bl: DiLineStyle, se_bl: DiLineStyle, sw_bl: DiLineStyle, ) -> str: """Calculate which character to use at the intersection of four cells.""" return get_grid_char( GridChar( max(nw_bl.right, ne_bl.left), max(ne_bl.bottom, se_bl.top), max(se_bl.left, sw_bl.right), max(sw_bl.top, nw_bl.bottom), ) )
Calculate which character to use at the intersection of four cells.
6,947
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) NoLine = LineStyle("None", rank=(0, 0), visible=False) class GridChar(NamedTuple): """Repreentation of a grid node character. The four compass points represent the line style joining from the given direction. """ north: LineStyle east: LineStyle south: LineStyle west: LineStyle def get_grid_char(key: GridChar) -> str: """Return the character represented by a combination of :class:`LineStyles`.""" if key in _GRID_CHARS: return _GRID_CHARS[key] else: # If there is no matching character representation, replace the line style # whose parent has the highest ranking with the parent style until a character # is found m_key = list(key) while any(x.parent for x in m_key): parent_ranks = {(9999,) if line.parent == NoLine else line.parent.rank: i for i, line in enumerate(m_key) if line.parent} idx = parent_ranks[max(parent_ranks)] if parent := m_key[idx].parent: m_key[idx] = parent char = _GRID_CHARS.get(GridChar(*m_key)) if char: return char # If all else fails, return a space else: return " " class DiLineStyle(NamedTuple): """A description of a cell border: a :class:`LineStyle` for each edge.""" top: LineStyle = NoLine right: LineStyle = NoLine bottom: LineStyle = NoLine left: LineStyle = NoLine def from_value(cls, value: LineStyle) -> DiLineStyle: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `get_horizontal_edge` function. Write a Python function `def get_horizontal_edge(n_bl: DiLineStyle, s_bl: DiLineStyle) -> str` to solve the following problem: Calculate which character to use to divide horizontally adjacent cells. Here is the function: def get_horizontal_edge(n_bl: DiLineStyle, s_bl: DiLineStyle) -> str: """Calculate which character to use to divide horizontally adjacent cells.""" line_style = max(n_bl.bottom, s_bl.top) return get_grid_char(GridChar(NoLine, line_style, NoLine, line_style))
Calculate which character to use to divide horizontally adjacent cells.
6,948
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) NoLine = LineStyle("None", rank=(0, 0), visible=False) class GridChar(NamedTuple): """Repreentation of a grid node character. The four compass points represent the line style joining from the given direction. """ north: LineStyle east: LineStyle south: LineStyle west: LineStyle def get_grid_char(key: GridChar) -> str: """Return the character represented by a combination of :class:`LineStyles`.""" if key in _GRID_CHARS: return _GRID_CHARS[key] else: # If there is no matching character representation, replace the line style # whose parent has the highest ranking with the parent style until a character # is found m_key = list(key) while any(x.parent for x in m_key): parent_ranks = {(9999,) if line.parent == NoLine else line.parent.rank: i for i, line in enumerate(m_key) if line.parent} idx = parent_ranks[max(parent_ranks)] if parent := m_key[idx].parent: m_key[idx] = parent char = _GRID_CHARS.get(GridChar(*m_key)) if char: return char # If all else fails, return a space else: return " " class DiLineStyle(NamedTuple): """A description of a cell border: a :class:`LineStyle` for each edge.""" top: LineStyle = NoLine right: LineStyle = NoLine bottom: LineStyle = NoLine left: LineStyle = NoLine def from_value(cls, value: LineStyle) -> DiLineStyle: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `get_vertical_edge` function. Write a Python function `def get_vertical_edge(w_bl: DiLineStyle, e_bl: DiLineStyle) -> str` to solve the following problem: Calculate which character to use to divide vertically adjacent cells. Here is the function: def get_vertical_edge(w_bl: DiLineStyle, e_bl: DiLineStyle) -> str: """Calculate which character to use to divide vertically adjacent cells.""" line_style = max(w_bl.right, e_bl.left) return get_grid_char(GridChar(line_style, NoLine, line_style, NoLine))
Calculate which character to use to divide vertically adjacent cells.
6,949
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) class Cell: """A table cell.""" def __init__( self, text: AnyFormattedText = "", row: Row | None = None, col: Col | None = None, colspan: int = 1, rowspan: int = 1, width: int | None = None, align: FormattedTextAlign | None = None, style: str = "", padding: DiInt | int = 0, border_line: DiLineStyle | LineStyle = ThinLine, border_style: DiStr | str = "", border_visibility: DiBool | bool | None = True, ) -> None: """Create a new table cell. Args: text: Text or formatted text to display in the cell row: The row to which this cell belongs col: The column to which this cell belongs colspan: The number of columns this cell spans rowspan: The number of row this cell spans width: The desired width of the cell align: How the text in the cell should be aligned style: The style to apply to the cell's contents padding: The padding around the contents of the cell border_line: The line to use for the borders border_style: The style to apply to the cell's borders border_visibility: The visibility of each border edge """ self.expands = self self.text = text self.row = row or DummyRow() self.col = col or DummyCol() self.colspan = colspan self.rowspan = rowspan self.width = width self.align = align self.style = style self.padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) self.border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) self.border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) self.border_visibility = ( DiBool( border_visibility, border_visibility, border_visibility, border_visibility, ) if isinstance(border_visibility, bool) else border_visibility ) self._col_index: int | None = None self._row_index: int | None = None def padding(self) -> DiInt: """The cell's padding.""" return self._padding def padding(self, padding: DiInt | int) -> None: """Set the cell's padding.""" self._padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) def border_line(self) -> DiLineStyle: """The cell's border line.""" return self._border_line def border_line(self, border_line: DiLineStyle | LineStyle) -> None: """Set the cell's border line.""" self._border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) def border_style(self) -> DiStr: """The cell's border style.""" return self._border_style def border_style(self, border_style: DiStr | str) -> None: """Set the cell's border style.""" self._border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) def __repr__(self) -> str: """Return a text representation of the cell.""" cell_text = to_plain_text(self.text) if len(cell_text) > 5: cell_text = cell_text[:4] + "…" return f"{self.__class__.__name__}({cell_text!r})" def compute_style(cell: Cell, render_count: int = 0) -> str: """Compute a cell's style string.""" return f"{cell.row.table.style} {cell.col.style} {cell.row.style} {cell.style}" def compute_text(cell: Cell, render_count: int = 0) -> StyleAndTextTuples: """Compute a cell's input, converted to :class:`FormattedText`.""" return to_formatted_text(cell.text, style=compute_style(cell)) def compute_padding(cell: Cell, render_count: int = 0) -> DiInt: """Compute a cell's padding.""" output = {} table_padding = cell.row.table.padding row_padding = cell.row.padding col_padding = cell.col.padding cell_padding = cell.padding for direction in ("top", "right", "bottom", "left"): output[direction] = max( getattr(table_padding, direction, 0), getattr(row_padding, direction, 0), getattr(col_padding, direction, 0), getattr(cell_padding, direction, 0), 0, ) return DiInt(**output) def compute_align(cell: Cell, render_count: int = 0) -> FormattedTextAlign: """Compute the alignment of a cell.""" if (align := cell.align) is not None: return align else: return cell.row.align or cell.col.align or cell.row.table.align def wrap( ft: StyleAndTextTuples, width: int, style: str = "", placeholder: str = "…", left: int = 0, truncate_long_words: bool = True, strip_trailing_ws: bool = False, margin: str = "", ) -> StyleAndTextTuples: """Wrap formatted text at a given width. If words are longer than the given line they will be truncated Args: ft: The formatted text to wrap width: The width at which to wrap the text style: The style to apply to the truncation placeholder placeholder: The string that will appear at the end of a truncated line left: The starting position within the first line truncate_long_words: If :const:`True` words longer than a line will be truncated strip_trailing_ws: If :const:`True`, trailing whitespace will be removed from the ends of lines margin: Text to use a margin for the continuation of wrapped lines Returns: The wrapped formatted text """ result: StyleAndTextTuples = [] lines = list(split_lines(ft)) n_lines = len(lines) output_line = 0 for i, line in enumerate(lines): if fragment_list_width(line) <= width - left: result += line if i < len(lines) - 1: result.append(("", "\n")) output_line += 1 left = 0 else: for word in fragment_list_to_words(line): # Skip empty fragments # if word[0] == word[1] == "": # continue fragment_width = fragment_list_width(word) # Start a new line - we are at the end of the current output line if left + fragment_width > width and left > 0: # Add as much trailing whitespace as we can if not strip_trailing_ws and ( trailing_ws := (not to_plain_text(word).strip()) ): result.extend(substring(word, end=width - left)) # Remove trailing whitespace if strip_trailing_ws: result = strip(result, left=False) # Start new line result.append(("", "\n")) if margin: result.append((style, margin)) output_line += 1 left = len(margin) # If we added trailing whitespace, process the next fragment if not strip_trailing_ws and trailing_ws: continue # Strip left-hand whitespace from a word at the start of a line # if output_line != 0 and left == 0: if left == 0: word = strip(word, right=False) # Truncate words longer than a line if ( truncate_long_words # Detect start of line and result and result[-1][1] == f"\n{margin}" # Check the word is too long and fragment_width > width - left ): result += truncate(word, width - left, style, placeholder) left += fragment_width # Otherwise just add the word to the line else: result.extend(word) left += fragment_width left = 0 if i + 1 < n_lines: result.append(("", "\n")) if strip_trailing_ws: result = strip(result, left=False) return result def align( ft: StyleAndTextTuples, how: FormattedTextAlign = FormattedTextAlign.LEFT, width: int | None = None, style: str = "", placeholder: str = "…", ignore_whitespace: bool = False, ) -> StyleAndTextTuples: """Align formatted text at a given width. Args: how: The alignment direction ft: The formatted text to strip width: The width to which the output should be padded. If :py:const:`None`, the length of the longest line is used style: The style to apply to the padding placeholder: The string that will appear at the end of a truncated line ignore_whitespace: If True, whitespace will be ignored Returns: The aligned formatted text """ style = f"{style} nounderline" lines = split_lines(ft) if width is None: lines = [strip(line) if ignore_whitespace else line for line in split_lines(ft)] width = max(fragment_list_width(line) for line in lines) result: StyleAndTextTuples = [] for line in lines: line_width = fragment_list_width(line) # Truncate the line if it is too long if line_width > width: result += truncate(line, width, style, placeholder, ignore_whitespace) else: pad_left = pad_right = 0 if how == FormattedTextAlign.CENTER: pad_left = (width - line_width) // 2 pad_right = width - line_width - pad_left elif how == FormattedTextAlign.LEFT: pad_right = width - line_width elif how == FormattedTextAlign.RIGHT: pad_left = width - line_width if pad_left: result.append((style, " " * pad_left)) result.extend(line) if pad_right: result.append((style, " " * pad_right)) result.append((style, "\n")) result.pop() return result The provided code snippet includes necessary dependencies for implementing the `compute_lines` function. Write a Python function `def compute_lines( cell: Cell, width: int, render_count: int = 0 ) -> list[StyleAndTextTuples]` to solve the following problem: Wrap the cell's text to a given width. Args: cell: The cell whose lines to compute width: The width at which to wrap the cell's text. render_count: The number of times the application has been rendered Returns: A list of lines of formatted text Here is the function: def compute_lines( cell: Cell, width: int, render_count: int = 0 ) -> list[StyleAndTextTuples]: """Wrap the cell's text to a given width. Args: cell: The cell whose lines to compute width: The width at which to wrap the cell's text. render_count: The number of times the application has been rendered Returns: A list of lines of formatted text """ padding = compute_padding(cell, render_count) return list( split_lines( align( wrap( [ *([("", "\n" * padding.top)] if padding.top else []), *compute_text(cell, render_count), *([("", "\n" * padding.bottom)] if padding.bottom else []), ], width=width, placeholder="", ), compute_align(cell, render_count), width=width, style=compute_style(cell, render_count), placeholder="", ) ) )
Wrap the cell's text to a given width. Args: cell: The cell whose lines to compute width: The width at which to wrap the cell's text. render_count: The number of times the application has been rendered Returns: A list of lines of formatted text
6,950
from __future__ import annotations from collections import defaultdict from functools import lru_cache, partial from itertools import tee, zip_longest from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app_session from prompt_toolkit.formatted_text.base import to_formatted_text from prompt_toolkit.formatted_text.utils import split_lines, to_plain_text from prompt_toolkit.layout.dimension import Dimension, to_dimension from euporie.core.border import ( DiLineStyle, GridChar, InvisibleLine, LineStyle, NoLine, ThinLine, get_grid_char, ) from euporie.core.data_structures import ( DiBool, DiInt, DiStr, ) from euporie.core.ft.utils import ( FormattedTextAlign, align, fragment_list_width, join_lines, max_line_width, wrap, ) class Cell: """A table cell.""" def __init__( self, text: AnyFormattedText = "", row: Row | None = None, col: Col | None = None, colspan: int = 1, rowspan: int = 1, width: int | None = None, align: FormattedTextAlign | None = None, style: str = "", padding: DiInt | int = 0, border_line: DiLineStyle | LineStyle = ThinLine, border_style: DiStr | str = "", border_visibility: DiBool | bool | None = True, ) -> None: """Create a new table cell. Args: text: Text or formatted text to display in the cell row: The row to which this cell belongs col: The column to which this cell belongs colspan: The number of columns this cell spans rowspan: The number of row this cell spans width: The desired width of the cell align: How the text in the cell should be aligned style: The style to apply to the cell's contents padding: The padding around the contents of the cell border_line: The line to use for the borders border_style: The style to apply to the cell's borders border_visibility: The visibility of each border edge """ self.expands = self self.text = text self.row = row or DummyRow() self.col = col or DummyCol() self.colspan = colspan self.rowspan = rowspan self.width = width self.align = align self.style = style self.padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) self.border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) self.border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) self.border_visibility = ( DiBool( border_visibility, border_visibility, border_visibility, border_visibility, ) if isinstance(border_visibility, bool) else border_visibility ) self._col_index: int | None = None self._row_index: int | None = None def padding(self) -> DiInt: """The cell's padding.""" return self._padding def padding(self, padding: DiInt | int) -> None: """Set the cell's padding.""" self._padding = ( DiInt(padding, padding, padding, padding) if isinstance(padding, int) else padding ) def border_line(self) -> DiLineStyle: """The cell's border line.""" return self._border_line def border_line(self, border_line: DiLineStyle | LineStyle) -> None: """Set the cell's border line.""" self._border_line = ( DiLineStyle(border_line, border_line, border_line, border_line) if isinstance(border_line, LineStyle) else border_line ) def border_style(self) -> DiStr: """The cell's border style.""" return self._border_style def border_style(self, border_style: DiStr | str) -> None: """Set the cell's border style.""" self._border_style = ( DiStr(border_style, border_style, border_style, border_style) if isinstance(border_style, str) else border_style ) def __repr__(self) -> str: """Return a text representation of the cell.""" cell_text = to_plain_text(self.text) if len(cell_text) > 5: cell_text = cell_text[:4] + "…" return f"{self.__class__.__name__}({cell_text!r})" class DiStr(NamedTuple): """A tuple of four strings with directions.""" top: str = "" right: str = "" bottom: str = "" left: str = "" def from_value(cls, value: str) -> DiStr: """Construct an instance from a single value.""" return cls(top=value, right=value, bottom=value, left=value) The provided code snippet includes necessary dependencies for implementing the `compute_border_style` function. Write a Python function `def compute_border_style(cell: Cell, render_count: int = 0) -> DiStr` to solve the following problem: Compute the cell's final style for each of a cell's borders. Here is the function: def compute_border_style(cell: Cell, render_count: int = 0) -> DiStr: """Compute the cell's final style for each of a cell's borders.""" output = {} row = cell.row col = cell.col table = row.table max_row = len(table._rows) - 1 max_col = len(table._cols) - 1 cell_border_style = cell.border_style row_border_style = row.border_style col_border_style = col.border_style table_border_style = table.border_style output["top"] = "".join( ( table_border_style.top if cell._row_index == 0 else "", col_border_style.top if cell._row_index == 0 else "", row_border_style.top, cell_border_style.top, ) ) output["right"] = "".join( ( table_border_style.right if cell._col_index == max_col else "", col_border_style.right, row_border_style.right if cell._col_index == max_col else "", cell_border_style.right, ) ) output["bottom"] = "".join( ( table_border_style.bottom if cell._row_index == max_row else "", col_border_style.bottom if cell._row_index == max_row else "", row_border_style.bottom, cell_border_style.bottom, ) ) output["left"] = "".join( ( table_border_style.left if cell._col_index == 0 else "", col_border_style.left, row_border_style.left if cell._col_index == 0 else "", cell_border_style.left, ) ) return DiStr(**output)
Compute the cell's final style for each of a cell's borders.
6,951
from __future__ import annotations import logging from functools import lru_cache, partial from typing import TYPE_CHECKING from prompt_toolkit.application.current import get_app from prompt_toolkit.data_structures import Point from prompt_toolkit.layout import containers from prompt_toolkit.layout.containers import WindowAlign, WindowRenderInfo from prompt_toolkit.layout.controls import ( FormattedTextControl, UIContent, fragment_list_width, to_formatted_text, ) from prompt_toolkit.layout.dimension import sum_layout_dimensions from prompt_toolkit.layout.screen import _CHAR_CACHE from prompt_toolkit.layout.utils import explode_text_fragments from prompt_toolkit.mouse_events import MouseEvent from prompt_toolkit.utils import get_cwidth, take_using_weights, to_str from euporie.core.data_structures import DiInt from euporie.core.layout.screen import BoundedWritePosition def _get_divided_heights( width: int, height: int, dimensions: tuple[Dimension, ...] ) -> list[int] | None: # Sum dimensions sum_dimensions = sum_layout_dimensions(list(dimensions)) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > height: return None # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions] ) i = next(child_generator) # Increase until we meet at least the 'preferred' size. preferred_stop = min(height, sum_dimensions.preferred) preferred_dimensions = [d.preferred for d in dimensions] while sum(sizes) < preferred_stop: if sizes[i] < preferred_dimensions[i]: sizes[i] += 1 i = next(child_generator) # Increase until we use all the available space. (or until "max") if not get_app().is_done: max_stop = min(height, sum_dimensions.max) max_dimensions = [d.max for d in dimensions] while sum(sizes) < max_stop: if sizes[i] < max_dimensions[i]: sizes[i] += 1 i = next(child_generator) return sizes
null
6,952
from __future__ import annotations import asyncio import logging from threading import Thread from typing import TYPE_CHECKING, cast from prompt_toolkit.cache import FastDictCache from prompt_toolkit.data_structures import Point from prompt_toolkit.filters import Condition from prompt_toolkit.formatted_text.utils import split_lines from prompt_toolkit.layout.containers import Window from prompt_toolkit.layout.controls import UIContent, UIControl from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType from prompt_toolkit.utils import Event from upath import UPath from euporie.core.commands import add_cmd from euporie.core.convert.datum import Datum, get_loop from euporie.core.convert.mime import get_format from euporie.core.current import get_app from euporie.core.ft.html import HTML, Node from euporie.core.ft.utils import fragment_list_width, paste from euporie.core.graphics import GraphicProcessor from euporie.core.key_binding.registry import ( load_registered_bindings, register_bindings, ) from euporie.core.path import parse_path class WebViewControl(UIControl): """Web view displays. A control which displays rendered HTML content. """ _window: Window def __init__( self, url: str | Path = "about:blank", link_handler: Callable | None = None, ) -> None: """Create a new web-view control instance.""" self._cursor_position = Point(0, 0) self.loading = False self.resizing = False self.rendering = False self.stale = False self.lines: list[StyleAndTextTuples] = [] self.graphic_processor = GraphicProcessor(control=self) self.width = 0 self.height = 0 self.url: Path = UPath(url) self.status: list[AnyFormattedText] = [] self.link_handler = link_handler or self.load_url self.render_task: Future[None] | None = None self.rendered = Event(self) self.on_cursor_position_changed = Event(self) self.prev_stack: list[Path] = [] self.next_stack: list[Path] = [] # self.cursor_processor = CursorProcessor( # lambda: self.cursor_position, style="fg:red" # ) self.loop = asyncio.new_event_loop() self.render_thread = Thread(target=self.loop.run_forever, daemon=True) self.key_bindings = load_registered_bindings( "euporie.web.widgets.webview.WebViewControl" ) self._dom_cache: FastDictCache[tuple[Path], HTML] = FastDictCache( get_value=self.get_dom, size=100 ) self._line_cache: FastDictCache[ tuple[HTML, int, int], list[StyleAndTextTuples] ] = FastDictCache(get_value=self.get_lines, size=100_000) self._content_cache: FastDictCache = FastDictCache(self.get_content, size=1_000) self.load_url(url) def window(self) -> Window: """Get the control's window.""" try: return self._window except AttributeError: for window in get_app().layout.find_all_windows(): if window.content == self: self._window = window return window return Window() def cursor_position(self) -> Point: """Get the cursor position.""" return self._cursor_position def cursor_position(self, value: Point) -> None: """Set the cursor position.""" changed = self._cursor_position != value self._cursor_position = value if changed: self.on_cursor_position_changed.fire() def get_dom(self, url: Path, x: bool = False) -> HTML: """Load a HTML page as renderable formatted text.""" markup = str( Datum( data=url.read_text(), format=(format_ := get_format(url, default="html")), path=url, ).convert( to="html", ) ) return HTML( markup=markup, base=url, mouse_handler=self._node_mouse_handler, paste_fixed=False, _initial_format=format_, defer_assets=False, on_change=lambda dom: self.invalidate(), ) def invalidate(self) -> None: """Trigger a redraw of the webview.""" self.stale = True self.rendered.fire() def dom(self) -> HTML: """Return the dom for the current URL.""" return self._dom_cache[self.url,] def title(self) -> str: """Return the title of the current HTML page.""" if self.loading: return self.url.name if dom := self.dom: return dom.title return "" def get_lines( self, dom: HTML, width: int, height: int, assets_loaded: bool = False ) -> list[StyleAndTextTuples]: """Render a HTML page as lines of formatted text.""" return list(split_lines(dom.render(width, height))) def load_url(self, url: str | Path, **kwargs: Any) -> None: """Load a new URL.""" save_to_history = kwargs.get("save_to_history", True) # Trigger "loading" view self.loading = True # Update navigation history if self.url and save_to_history: self.prev_stack.append(self.url) self.next_stack.clear() # Update url self.url = UPath(url) # Scroll to the top # self.window.vertical_scroll = 0 # TODO - save scroll in history self.cursor_position = Point(0, 0) # Signal that the webview has updated self.rendered.fire() def nav_prev(self) -> None: """Navigate forwards through the browser history.""" if self.url and self.prev_stack: self.next_stack.append(self.url) self.load_url(self.prev_stack.pop(), save_to_history=False) def nav_next(self) -> None: """Navigate backwards through the browser history.""" if self.url and self.next_stack: self.prev_stack.append(self.url) self.load_url(self.next_stack.pop(), save_to_history=False) def render(self, force: bool = False) -> None: """Render the HTML DOM in a thread.""" dom = self.dom async def _render() -> None: assert self.url is not None # Potentially redirect url self.url = parse_path(self.url) self.lines = list(split_lines(await dom._render(self.width, self.height))) # Reset all possible reasons for rendering self.loading = self.resizing = self.rendering = self.stale = False # Let the app know we're re-rerenderd and the output needs redrawing self.rendered.fire() if not self.rendering or force: self.rendering = True if self.render_task: self.render_task.cancel() self.render_task = asyncio.run_coroutine_threadsafe(_render(), get_loop()) def reset(self) -> None: """Reset the state of the control.""" def preferred_width(self, max_available_width: int) -> int | None: """Calculate and return the preferred width of the control.""" return None def preferred_height( self, width: int, max_available_height: int, wrap_lines: bool, get_line_prefix: GetLinePrefixCallable | None, ) -> int | None: """Calculate and return the preferred height of the control.""" return None def is_focusable(self) -> bool: """Tell whether this user control is focusable.""" return True def get_content( self, url: Path, loading: bool, resizing: bool, width: int, height: int, cursor_position: Point, assets_loaded: bool, ) -> UIContent: """Create a cacheable UIContent.""" dom = self._dom_cache[url,] if self.loading: lines = [ cast("StyleAndTextTuples", []), cast( "StyleAndTextTuples", [("", " " * ((width - 8) // 2)), ("class:loading", "Loading…")], ), ] else: lines = self.lines[:] def get_line(i: int) -> StyleAndTextTuples: try: line = lines[i] except IndexError: line = [] # Overlay fixed lines onto this line if not loading and dom.fixed: visible_line = max(0, i - self.window.vertical_scroll) fixed_lines = list(split_lines(dom.fixed_mask)) if visible_line < len(fixed_lines): # Paste the fixed line over the current line fixed_line = fixed_lines[visible_line] line = paste(fixed_line, line, 0, 0, transparent=True) return line return UIContent( get_line=get_line, line_count=len(lines), cursor_position=self.cursor_position, show_cursor=False, ) def create_content(self, width: int, height: int) -> UIContent: """Generate the content for this user control. Returns: A :class:`.UIContent` instance. """ # Trigger a re-render in the future if things have changed if self.stale or self.loading: self.render() if width != self.width: # or height != self.height: # self.resizing = True self.width = width self.height = height self.render() content = self._content_cache[ self.url, self.loading, self.resizing, width, height, self.cursor_position, self.dom.render_count, ] # Check for graphics in content self.graphic_processor.load(content) return content def _node_mouse_handler( self, node: Node, mouse_event: MouseEvent ) -> NotImplementedOrNone: """Handle click events.""" url = node.attrs.get("_link_path") title = node.attrs.get("title") if url: # TODO - Check for #anchor links and scroll accordingly if ( mouse_event.button == MouseButton.LEFT and mouse_event.event_type == MouseEventType.MOUSE_UP ): self.link_handler(url, save_to_history=True, new_tab=False) return None elif ( mouse_event.button == MouseButton.MIDDLE and mouse_event.event_type == MouseEventType.MOUSE_UP ): self.link_handler(url, save_to_history=False, new_tab=True) return None if (url or title) and mouse_event.event_type == MouseEventType.MOUSE_MOVE: self.status.clear() if title: self.status.append(str(title)) if url: self.status.append(str(url)) return None return NotImplemented def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone: """Handle mouse events. When `NotImplemented` is returned, it means that the given event is not handled by the `UIControl` itself. The `Window` or key bindings can decide to handle this event as scrolling or changing focus. Args: mouse_event: `MouseEvent` instance. Returns: NotImplemented if the UI does not need to be updates, None if it does """ # Focus on mouse down if mouse_event.event_type == MouseEventType.MOUSE_DOWN: if not (layout := get_app().layout).has_focus(self): layout.focus(self) return None return NotImplemented # if mouse_event.event_type == MouseEventType.MOUSE_MOVE: # self.cursor_position = mouse_event.position # if mouse_event.event_type == MouseEventType.MOUSE_UP: handler: MouseHandler | None = None try: content = self._content_cache[ self.url, self.loading, self.resizing, self.width, self.height, self.cursor_position, self.dom.render_count, ] line = content.get_line(mouse_event.position.y) except IndexError: return NotImplemented else: # Find position in the fragment list. xpos = mouse_event.position.x # Find mouse handler for this character. count = 0 for item in line: count += len(item[1]) if count > xpos: if len(item) >= 3: handler = item[2] if callable(handler): return handler(mouse_event) else: break if callable(handler): return handler if self.status: self.status.clear() return None return NotImplemented def content_width(self) -> int: """Return the width of the content.""" return max(fragment_list_width(line) for line in self.lines) def move_cursor_down(self) -> None: """Move the cursor down one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x, y=y + 1) def move_cursor_up(self) -> None: """Move the cursor up one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x, y=max(0, y - 1)) def move_cursor_left(self) -> None: """Move the cursor down one line.""" x, y = self.cursor_position self.cursor_position = Point(x=max(0, x - 1), y=y) def move_cursor_right(self) -> None: """Move the cursor up one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x + 1, y=y) def get_key_bindings(self) -> KeyBindingsBase | None: """Return key bindings that are specific for this user control. Returns: A :class:`.KeyBindings` object if some key bindings are specified, or `None` otherwise. """ return self.key_bindings def get_invalidate_events(self) -> Iterable[Event[object]]: """Return a list of `Event` objects, which can be a generator. the application collects all these events, in order to bind redraw handlers to these events. """ yield self.rendered yield self.on_cursor_position_changed if dom := self.dom: yield dom.on_update # ################################### Commands #################################### def _webview_nav_prev() -> None: """Navigate backwards in the browser history.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.nav_prev() def _webview_nav_next() -> None: """Navigate forwards in the browser history.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.nav_next() def _scroll_webview_left() -> None: """Scroll the display up one line.""" from euporie.core.widgets.display import DisplayWindow window = get_app().layout.current_window assert isinstance(window, DisplayWindow) window._scroll_left() def _scroll_webview_right() -> None: """Scroll the display down one line.""" from euporie.core.widgets.display import DisplayWindow window = get_app().layout.current_window assert isinstance(window, DisplayWindow) window._scroll_right() def _scroll_webview_up() -> None: """Scroll the display up one line.""" get_app().layout.current_window._scroll_up() def _scroll_webview_down() -> None: """Scroll the display down one line.""" get_app().layout.current_window._scroll_down() def _page_up_webview() -> None: """Scroll the display up one page.""" window = get_app().layout.current_window if window.render_info is not None: for _ in range(window.render_info.window_height): window._scroll_up() def _page_down_webview() -> None: """Scroll the display down one page.""" window = get_app().layout.current_window if window.render_info is not None: for _ in range(window.render_info.window_height): window._scroll_down() def _go_to_start_of_webview() -> None: """Scroll the display to the top.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.cursor_position = Point(0, 0) def _go_to_end_of_webview() -> None: """Scroll the display down one page.""" from euporie.web.widgets.webview import WebViewControl layout = get_app().layout current_control = layout.current_control window = layout.current_window if ( isinstance(current_control, WebViewControl) and window.render_info is not None ): current_control.cursor_position = Point( 0, window.render_info.ui_content.line_count - 1 ) # ################################# Key Bindings ################################## register_bindings( { "euporie.web.widgets.webview.WebViewControl": { "scroll-webview-left": "left", "scroll-webview-right": "right", "scroll-webview-up": ["up", "k"], "scroll-webview-down": ["down", "j"], "page-up-webview": "pageup", "page-down-webview": "pagedown", "go-to-start-of-webview": "home", "go-to-end-of-webview": "end", "webview-nav-prev": ("A-left"), "webview-nav-next": ("A-right"), } } ) def get_app() -> BaseApp: """Get the current active (running) Application.""" from euporie.core.app import BaseApp session = _current_app_session.get() if isinstance(session.app, BaseApp): return session.app # Use a baseapp as our "DummyApplication" return BaseApp() class WebViewControl(UIControl): """Web view displays. A control which displays rendered HTML content. """ _window: Window def __init__( self, url: str | Path = "about:blank", link_handler: Callable | None = None, ) -> None: """Create a new web-view control instance.""" self._cursor_position = Point(0, 0) self.loading = False self.resizing = False self.rendering = False self.stale = False self.lines: list[StyleAndTextTuples] = [] self.graphic_processor = GraphicProcessor(control=self) self.width = 0 self.height = 0 self.url: Path = UPath(url) self.status: list[AnyFormattedText] = [] self.link_handler = link_handler or self.load_url self.render_task: Future[None] | None = None self.rendered = Event(self) self.on_cursor_position_changed = Event(self) self.prev_stack: list[Path] = [] self.next_stack: list[Path] = [] # self.cursor_processor = CursorProcessor( # lambda: self.cursor_position, style="fg:red" # ) self.loop = asyncio.new_event_loop() self.render_thread = Thread(target=self.loop.run_forever, daemon=True) self.key_bindings = load_registered_bindings( "euporie.web.widgets.webview.WebViewControl" ) self._dom_cache: FastDictCache[tuple[Path], HTML] = FastDictCache( get_value=self.get_dom, size=100 ) self._line_cache: FastDictCache[ tuple[HTML, int, int], list[StyleAndTextTuples] ] = FastDictCache(get_value=self.get_lines, size=100_000) self._content_cache: FastDictCache = FastDictCache(self.get_content, size=1_000) self.load_url(url) def window(self) -> Window: """Get the control's window.""" try: return self._window except AttributeError: for window in get_app().layout.find_all_windows(): if window.content == self: self._window = window return window return Window() def cursor_position(self) -> Point: """Get the cursor position.""" return self._cursor_position def cursor_position(self, value: Point) -> None: """Set the cursor position.""" changed = self._cursor_position != value self._cursor_position = value if changed: self.on_cursor_position_changed.fire() def get_dom(self, url: Path, x: bool = False) -> HTML: """Load a HTML page as renderable formatted text.""" markup = str( Datum( data=url.read_text(), format=(format_ := get_format(url, default="html")), path=url, ).convert( to="html", ) ) return HTML( markup=markup, base=url, mouse_handler=self._node_mouse_handler, paste_fixed=False, _initial_format=format_, defer_assets=False, on_change=lambda dom: self.invalidate(), ) def invalidate(self) -> None: """Trigger a redraw of the webview.""" self.stale = True self.rendered.fire() def dom(self) -> HTML: """Return the dom for the current URL.""" return self._dom_cache[self.url,] def title(self) -> str: """Return the title of the current HTML page.""" if self.loading: return self.url.name if dom := self.dom: return dom.title return "" def get_lines( self, dom: HTML, width: int, height: int, assets_loaded: bool = False ) -> list[StyleAndTextTuples]: """Render a HTML page as lines of formatted text.""" return list(split_lines(dom.render(width, height))) def load_url(self, url: str | Path, **kwargs: Any) -> None: """Load a new URL.""" save_to_history = kwargs.get("save_to_history", True) # Trigger "loading" view self.loading = True # Update navigation history if self.url and save_to_history: self.prev_stack.append(self.url) self.next_stack.clear() # Update url self.url = UPath(url) # Scroll to the top # self.window.vertical_scroll = 0 # TODO - save scroll in history self.cursor_position = Point(0, 0) # Signal that the webview has updated self.rendered.fire() def nav_prev(self) -> None: """Navigate forwards through the browser history.""" if self.url and self.prev_stack: self.next_stack.append(self.url) self.load_url(self.prev_stack.pop(), save_to_history=False) def nav_next(self) -> None: """Navigate backwards through the browser history.""" if self.url and self.next_stack: self.prev_stack.append(self.url) self.load_url(self.next_stack.pop(), save_to_history=False) def render(self, force: bool = False) -> None: """Render the HTML DOM in a thread.""" dom = self.dom async def _render() -> None: assert self.url is not None # Potentially redirect url self.url = parse_path(self.url) self.lines = list(split_lines(await dom._render(self.width, self.height))) # Reset all possible reasons for rendering self.loading = self.resizing = self.rendering = self.stale = False # Let the app know we're re-rerenderd and the output needs redrawing self.rendered.fire() if not self.rendering or force: self.rendering = True if self.render_task: self.render_task.cancel() self.render_task = asyncio.run_coroutine_threadsafe(_render(), get_loop()) def reset(self) -> None: """Reset the state of the control.""" def preferred_width(self, max_available_width: int) -> int | None: """Calculate and return the preferred width of the control.""" return None def preferred_height( self, width: int, max_available_height: int, wrap_lines: bool, get_line_prefix: GetLinePrefixCallable | None, ) -> int | None: """Calculate and return the preferred height of the control.""" return None def is_focusable(self) -> bool: """Tell whether this user control is focusable.""" return True def get_content( self, url: Path, loading: bool, resizing: bool, width: int, height: int, cursor_position: Point, assets_loaded: bool, ) -> UIContent: """Create a cacheable UIContent.""" dom = self._dom_cache[url,] if self.loading: lines = [ cast("StyleAndTextTuples", []), cast( "StyleAndTextTuples", [("", " " * ((width - 8) // 2)), ("class:loading", "Loading…")], ), ] else: lines = self.lines[:] def get_line(i: int) -> StyleAndTextTuples: try: line = lines[i] except IndexError: line = [] # Overlay fixed lines onto this line if not loading and dom.fixed: visible_line = max(0, i - self.window.vertical_scroll) fixed_lines = list(split_lines(dom.fixed_mask)) if visible_line < len(fixed_lines): # Paste the fixed line over the current line fixed_line = fixed_lines[visible_line] line = paste(fixed_line, line, 0, 0, transparent=True) return line return UIContent( get_line=get_line, line_count=len(lines), cursor_position=self.cursor_position, show_cursor=False, ) def create_content(self, width: int, height: int) -> UIContent: """Generate the content for this user control. Returns: A :class:`.UIContent` instance. """ # Trigger a re-render in the future if things have changed if self.stale or self.loading: self.render() if width != self.width: # or height != self.height: # self.resizing = True self.width = width self.height = height self.render() content = self._content_cache[ self.url, self.loading, self.resizing, width, height, self.cursor_position, self.dom.render_count, ] # Check for graphics in content self.graphic_processor.load(content) return content def _node_mouse_handler( self, node: Node, mouse_event: MouseEvent ) -> NotImplementedOrNone: """Handle click events.""" url = node.attrs.get("_link_path") title = node.attrs.get("title") if url: # TODO - Check for #anchor links and scroll accordingly if ( mouse_event.button == MouseButton.LEFT and mouse_event.event_type == MouseEventType.MOUSE_UP ): self.link_handler(url, save_to_history=True, new_tab=False) return None elif ( mouse_event.button == MouseButton.MIDDLE and mouse_event.event_type == MouseEventType.MOUSE_UP ): self.link_handler(url, save_to_history=False, new_tab=True) return None if (url or title) and mouse_event.event_type == MouseEventType.MOUSE_MOVE: self.status.clear() if title: self.status.append(str(title)) if url: self.status.append(str(url)) return None return NotImplemented def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone: """Handle mouse events. When `NotImplemented` is returned, it means that the given event is not handled by the `UIControl` itself. The `Window` or key bindings can decide to handle this event as scrolling or changing focus. Args: mouse_event: `MouseEvent` instance. Returns: NotImplemented if the UI does not need to be updates, None if it does """ # Focus on mouse down if mouse_event.event_type == MouseEventType.MOUSE_DOWN: if not (layout := get_app().layout).has_focus(self): layout.focus(self) return None return NotImplemented # if mouse_event.event_type == MouseEventType.MOUSE_MOVE: # self.cursor_position = mouse_event.position # if mouse_event.event_type == MouseEventType.MOUSE_UP: handler: MouseHandler | None = None try: content = self._content_cache[ self.url, self.loading, self.resizing, self.width, self.height, self.cursor_position, self.dom.render_count, ] line = content.get_line(mouse_event.position.y) except IndexError: return NotImplemented else: # Find position in the fragment list. xpos = mouse_event.position.x # Find mouse handler for this character. count = 0 for item in line: count += len(item[1]) if count > xpos: if len(item) >= 3: handler = item[2] if callable(handler): return handler(mouse_event) else: break if callable(handler): return handler if self.status: self.status.clear() return None return NotImplemented def content_width(self) -> int: """Return the width of the content.""" return max(fragment_list_width(line) for line in self.lines) def move_cursor_down(self) -> None: """Move the cursor down one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x, y=y + 1) def move_cursor_up(self) -> None: """Move the cursor up one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x, y=max(0, y - 1)) def move_cursor_left(self) -> None: """Move the cursor down one line.""" x, y = self.cursor_position self.cursor_position = Point(x=max(0, x - 1), y=y) def move_cursor_right(self) -> None: """Move the cursor up one line.""" x, y = self.cursor_position self.cursor_position = Point(x=x + 1, y=y) def get_key_bindings(self) -> KeyBindingsBase | None: """Return key bindings that are specific for this user control. Returns: A :class:`.KeyBindings` object if some key bindings are specified, or `None` otherwise. """ return self.key_bindings def get_invalidate_events(self) -> Iterable[Event[object]]: """Return a list of `Event` objects, which can be a generator. the application collects all these events, in order to bind redraw handlers to these events. """ yield self.rendered yield self.on_cursor_position_changed if dom := self.dom: yield dom.on_update # ################################### Commands #################################### def _webview_nav_prev() -> None: """Navigate backwards in the browser history.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.nav_prev() def _webview_nav_next() -> None: """Navigate forwards in the browser history.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.nav_next() def _scroll_webview_left() -> None: """Scroll the display up one line.""" from euporie.core.widgets.display import DisplayWindow window = get_app().layout.current_window assert isinstance(window, DisplayWindow) window._scroll_left() def _scroll_webview_right() -> None: """Scroll the display down one line.""" from euporie.core.widgets.display import DisplayWindow window = get_app().layout.current_window assert isinstance(window, DisplayWindow) window._scroll_right() def _scroll_webview_up() -> None: """Scroll the display up one line.""" get_app().layout.current_window._scroll_up() def _scroll_webview_down() -> None: """Scroll the display down one line.""" get_app().layout.current_window._scroll_down() def _page_up_webview() -> None: """Scroll the display up one page.""" window = get_app().layout.current_window if window.render_info is not None: for _ in range(window.render_info.window_height): window._scroll_up() def _page_down_webview() -> None: """Scroll the display down one page.""" window = get_app().layout.current_window if window.render_info is not None: for _ in range(window.render_info.window_height): window._scroll_down() def _go_to_start_of_webview() -> None: """Scroll the display to the top.""" from euporie.web.widgets.webview import WebViewControl current_control = get_app().layout.current_control if isinstance(current_control, WebViewControl): current_control.cursor_position = Point(0, 0) def _go_to_end_of_webview() -> None: """Scroll the display down one page.""" from euporie.web.widgets.webview import WebViewControl layout = get_app().layout current_control = layout.current_control window = layout.current_window if ( isinstance(current_control, WebViewControl) and window.render_info is not None ): current_control.cursor_position = Point( 0, window.render_info.ui_content.line_count - 1 ) # ################################# Key Bindings ################################## register_bindings( { "euporie.web.widgets.webview.WebViewControl": { "scroll-webview-left": "left", "scroll-webview-right": "right", "scroll-webview-up": ["up", "k"], "scroll-webview-down": ["down", "j"], "page-up-webview": "pageup", "page-down-webview": "pagedown", "go-to-start-of-webview": "home", "go-to-end-of-webview": "end", "webview-nav-prev": ("A-left"), "webview-nav-next": ("A-right"), } } ) The provided code snippet includes necessary dependencies for implementing the `webview_has_focus` function. Write a Python function `def webview_has_focus() -> bool` to solve the following problem: Determine if there is a currently focused webview. Here is the function: def webview_has_focus() -> bool: """Determine if there is a currently focused webview.""" return isinstance(get_app().layout.current_control, WebViewControl)
Determine if there is a currently focused webview.
6,953
from __future__ import annotations import logging from typing import TYPE_CHECKING, cast from prompt_toolkit.application.current import get_app as ptk_get_app from prompt_toolkit.application.run_in_terminal import in_terminal from prompt_toolkit.filters.app import ( has_completions, is_done, is_searching, renderer_height_is_known, ) from prompt_toolkit.layout.containers import ( ConditionalContainer, FloatContainer, HSplit, VSplit, Window, ) from prompt_toolkit.layout.dimension import Dimension from euporie.console.tabs.console import Console from euporie.core import __logo__ from euporie.core.app import BaseApp from euporie.core.commands import add_cmd from euporie.core.config import add_setting from euporie.core.filters import has_dialog from euporie.core.layout.mouse import DisableMouseOnScroll from euporie.core.widgets.dialog import ( AboutDialog, NoKernelsDialog, SaveAsDialog, SelectKernelDialog, ShortcutsDialog, ) from euporie.core.widgets.pager import Pager from euporie.core.widgets.palette import CommandPalette from euporie.core.widgets.search import SearchBar from euporie.core.widgets.status import StatusBar class ConsoleApp(BaseApp): """Conole app. An interactive console which connects to Jupyter kernels and displays rich output in the terminal. """ name = "console" log_stdout_level = "ERROR" def __init__(self, **kwargs: Any) -> None: """Create a new euporie text user interface application instance.""" # Set default application options kwargs.setdefault("extend_renderer_height", True) kwargs.setdefault("title", "euporie-console") kwargs.setdefault("full_screen", False) kwargs.setdefault("leave_graphics", True) kwargs.setdefault("mouse_support", self.config.filter("mouse_support")) # Initialize the application super().__init__(**kwargs) self.search_bar = SearchBar() self.bindings_to_load += ["euporie.console.app.ConsoleApp"] self.tabs = [] self.pager = Pager() def _get_reserved_height(self) -> Dimension: if has_dialog(): return Dimension(min=15) elif has_completions(): return Dimension(min=5) else: return Dimension(min=1) def load_container(self) -> FloatContainer: """Return a container with all opened tabs.""" self.tabs = [Console(self)] assert self.pager is not None assert self.search_bar is not None assert self.tab is not None self.dialogs["command-palette"] = CommandPalette(self) self.dialogs["about"] = AboutDialog(self) self.dialogs["save-as"] = SaveAsDialog(self) self.dialogs["no-kernels"] = NoKernelsDialog(self) self.dialogs["change-kernel"] = SelectKernelDialog(self) self.dialogs["shortcuts"] = ShortcutsDialog(self) return FloatContainer( DisableMouseOnScroll( HSplit( [ self.tab, ConditionalContainer( HSplit( [ # Fill empty space below input Window( height=self._get_reserved_height, style="class:default", ), self.pager, self.search_bar, ConditionalContainer( VSplit( [ Window( char=f" {__logo__} ", height=1, width=3, style="class:menu,logo", dont_extend_width=True, ), StatusBar(), ] ), filter=~is_searching, ), ], ), filter=~self.redrawing & ~is_done & renderer_height_is_known, ), ] ) ), floats=self.floats, # type: ignore ) def exit( self, result: _AppResult | None = None, exception: BaseException | type[BaseException] | None = None, style: str = "", ) -> None: """Close all tabs on exit.""" for tab in self.tabs: tab.close() if result is not None: super().exit(result=result, style=style) elif exception is not None: super().exit(exception=exception, style=style) else: super().exit() # ################################### Commands #################################### async def _convert_to_notebook() -> None: """Convert the current console session to a notebook.""" from euporie.notebook.app import NotebookApp from euporie.notebook.tabs.notebook import Notebook app = get_app() nb_app = NotebookApp() for tab in app.tabs: if isinstance(tab, Console): nb = Notebook( app=nb_app, path=tab.path, kernel=tab.kernel, comms=tab.comms, json=tab.json, ) # Set the history to the console's history nb.history = tab.history # Add the current input nb.add(len(nb.json["cells"]) + 1, source=tab.input_box.buffer.text) # Add the new notebook to the notebook app nb_app.tabs.append(nb) # Tell notebook that the kernel has already started nb.kernel_started() async with in_terminal(): await nb_app.run_async() app.exit() # ################################### Settings #################################### add_setting( name="mouse_support", flags=["--mouse-support"], type_=bool, help_="Enable or disable mouse support", default=None, description=""" When set to True, mouse support is enabled. When set to False, mouse support is disabled. """, ) # ################################# Key Bindings ################################## # register_bindings({"euporie.console.app.ConsoleApp": {}}) The provided code snippet includes necessary dependencies for implementing the `get_app` function. Write a Python function `def get_app() -> ConsoleApp` to solve the following problem: Get the current application. Here is the function: def get_app() -> ConsoleApp: """Get the current application.""" return cast("ConsoleApp", ptk_get_app())
Get the current application.
6,954
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `check_output` function. Write a Python function `def check_output(*args: "str") -> "str"` to solve the following problem: Check the output of a command. Args: args: List of works in a command line string Here is the function: def check_output(*args: "str") -> "str": """Check the output of a command. Args: args: List of works in a command line string """ return subprocess.check_output(args, text=True).strip()
Check the output of a command. Args: args: List of works in a command line string
6,955
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `item` function. Write a Python function `def item(text: "str") -> "None"` to solve the following problem: Print a task. Here is the function: def item(text: "str") -> "None": """Print a task.""" sys.stdout.write(f"-> \x1b[1m{text}\x1b[0m\n")
Print a task.
6,956
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `error` function. Write a Python function `def error(text: "str") -> "None"` to solve the following problem: Print an error message. Here is the function: def error(text: "str") -> "None": """Print an error message.""" sys.stdout.write(f"\n \x1b[31mError:\x1b[0m {text}\n\n")
Print an error message.
6,957
import logging import shutil import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `status` function. Write a Python function `def status(value: "str") -> "None"` to solve the following problem: Print a status field at the end of a line. Here is the function: def status(value: "str") -> "None": """Print a status field at the end of a line.""" sys.stdout.write(f"\x1b[1F\x1b[9999C\x1b[{len(value) + 2}D ") if value == "FAIL": sys.stdout.write("\x1b[31m") else: sys.stdout.write("\x1b[32m") sys.stdout.write(f"{value}\x1b[0m\n")
Print a status field at the end of a line.
6,958
from __future__ import annotations import subprocess import sys from textwrap import dedent, indent from typing import TYPE_CHECKING, cast def format_action(action: argparse.Action) -> str: """Format an action as RST.""" s = "" type_ = "" if action.type and action.type != bool: action.type = cast("Callable", action.type) type_ = f"<{action.type.__name__}>" # typing: ignore if action.choices: type_ = f"{{{','.join(map(str, action.choices))}}}" flags = [f"{flag} {type_}".strip() for flag in action.option_strings] or [type_] nargs = " ..." if action.nargs == "*" else "" s += f""".. option:: {", ".join(flags)}{nargs} {action.help} """ return s The provided code snippet includes necessary dependencies for implementing the `format_parser` function. Write a Python function `def format_parser( title: str, parser: argparse.ArgumentParser, description: str = "" ) -> str` to solve the following problem: Format a parser's arguments as RST. Here is the function: def format_parser( title: str, parser: argparse.ArgumentParser, description: str = "" ) -> str: """Format a parser's arguments as RST.""" s = "" # s = "\n" # s += ("*" * len(title)) + "\n" + title + "\n" + ("*" * len(title)) + "\n\n" # s += description or dedent(parser.description or "").strip() # s += "\n\n" s += "\nUsage\n=====\n\n" s += ".. code-block:: console\n\n" usage = parser.format_usage() usage = usage[usage.startswith("usage: ") and len("usage: ") :] s += indent(f"$ {usage}", " ") s += "\n" positionals = [action for action in parser._actions if not action.option_strings] if positionals: s += "Positional Arguments\n====================\n\n" for action in positionals: s += format_action(action) optionals = [action for action in parser._actions if action.option_strings] if optionals: s += "Optional Arguments\n==================\n\n" for action in optionals: s += format_action(action) subcommands = [action for action in parser._actions if action.dest == "subcommand"] for action in subcommands: if isinstance(action.choices, dict): for name, subcommand in action.choices.items(): s += format_parser(f":option:`{name}` subcommand", subcommand) return s
Format a parser's arguments as RST.
6,959
import os from pathlib import Path from textwrap import dedent The provided code snippet includes necessary dependencies for implementing the `activate_virtualenv_in_precommit_hooks` function. Write a Python function `def activate_virtualenv_in_precommit_hooks() -> "None"` to solve the following problem: Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the hatch virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git. Here is the function: def activate_virtualenv_in_precommit_hooks() -> "None": """Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the hatch virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git. """ virtualenv = os.environ.get("VIRTUAL_ENV") if virtualenv is None: return hookdir = Path(".git") / "hooks" if not hookdir.is_dir(): return bindir = str((Path(virtualenv) / "bin").resolve()) for hook in hookdir.iterdir(): if hook.name.endswith(".sample") or not hook.is_file(): continue text = hook.read_text() if not ( Path("A") == Path("a") and bindir.lower() in text.lower() or bindir in text ): continue lines = text.splitlines() if not (lines[0].startswith("#!") and "bash" in lines[0].lower()): continue header = dedent( f""" VIRTUAL_ENV="{virtualenv}" PATH="{bindir}:$PATH" """ ) lines.insert(1, header) hook.write_text("\n".join(lines))
Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the hatch virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git.
6,960
from __future__ import annotations import sys from typing import TYPE_CHECKING from prompt_toolkit.input.vt100 import raw_mode from euporie.core.io import Vt100Parser from euporie.core.keys import Keys The provided code snippet includes necessary dependencies for implementing the `callback` function. Write a Python function `def callback(key_press: KeyPress) -> None` to solve the following problem: Run when a key press event is received. Here is the function: def callback(key_press: KeyPress) -> None: """Run when a key press event is received.""" print(key_press) if key_press.key == Keys.ControlC: print("\x1b[>4;0m") print("\x1b[<1u") sys.exit(0)
Run when a key press event is received.
6,961
from __future__ import annotations import subprocess import sys from textwrap import dedent, indent from euporie.core.commands import commands commands: dict[str, Command] = {} The provided code snippet includes necessary dependencies for implementing the `format_commands` function. Write a Python function `def format_commands() -> None` to solve the following problem: Format commands as RST. Here is the function: def format_commands() -> None: """Format commands as RST.""" for name, command in commands.items(): print(f".. option:: {name}\n") print(f":title: {command.title}") print(":description:") print(indent(dedent(command.description), " ")) print()
Format commands as RST.
6,962
import click import sys from typing import List def mutate_header(line) -> str: cveXXXXX = ' Status CVE-2021-XXXXX ' _, vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, cveXXXXX, comment, link])) def mutate_underline(line) -> str: cveXXXXX = ':---------------------:' _, vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, cveXXXXX, comment, link])) def mutate_record(line) -> str: cveXXXXX = ' ' _, vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link, _ = line.split('|') # Log4j 1.x is not impacted by CVE-2021-XXXXX if ('Fix' in cve4104 or 'Vulnerable' in cve4104) and 'Not vuln' in cve44228: cveXXXXX = 'Not vuln' # Software not using Log4j is not impacted by CVE-2021-XXXXX if 'Not vuln' in cve4104 and 'Not vuln' in cve44228 and 'Not vuln' in cve45046 and 'Not vuln' in cve45105: cveXXXXX = 'Not vuln' return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, cveXXXXX, comment, link])) def mutate(ctx, input): with sys.stdout as output: for line in input: try: # not a table, just copy if line[0] != '|': output.write(line) continue # table header, add header fields if '| Supplier' in line: output.write(mutate_header(line)) continue # table underline, add header fields if '|:----' in line: output.write(mutate_underline(line)) continue # table line, add cells output.write(mutate_record(line)) except ValueError as e: print("\nOffending line:", file=sys.stderr) print(line, file=sys.stderr) raise e
null
6,963
import click import sys from typing import List VALID_STATUS = [''] def mutate_header(line) -> str: cve45105 = ' Status CVE-2021-45105 ' _, vendor, product, version, cve4104, cve44228, cve45046, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link])) def mutate_underline(line) -> str: cve45105 = ':---------------------:' _, vendor, product, version, cve4104, cve44228, cve45046, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, cve45105, comment, link])) def mutate_record(line) -> str: cve45105 = ' ' _, vendor, product, version, cve4104, cve44228, cve45046, comment, link, _ = line.split('|') # Log4j 1.x is not impacted by CVE-2021-45105 if ('Fix' in cve4104 or 'Vulnerable' in cve4104) and 'Not vuln' in cve44228: cve45105 = ' Not vuln ' # Software not using Log4j is not impacted by CVE-2021-45105 if 'Not vuln' in cve4104 and 'Not vuln' in cve44228 and 'Not vuln' in cve45046: cve45105 = ' Not vuln ' s = sanitize_status_field return(table_line([vendor, product, version, s(cve4104), s(cve44228), s(cve45046), cve45105, comment, link])) def mutate(ctx, input): with sys.stdout as output: for line in input: try: # not a table, just copy if line[0] != '|': output.write(line) continue # initial status table, just copy if line.count('|') == 3: output.write(line) # read status table to fill list of valid status codes _, status, *_ = line.split('|') VALID_STATUS.append(status.strip()) continue # table header, add header fields if '| Supplier' in line: output.write(mutate_header(line)) continue # table underline, add header fields if '|:----' in line: output.write(mutate_underline(line)) continue # table line, add cells output.write(mutate_record(line)) except ValueError as e: print("\nOffending line:", file=sys.stderr) print(line, file=sys.stderr) raise e
null
6,964
import click import sys from typing import List def mutate_header(line) -> str: cve4104 = ' Status CVE-2021-4104 ' cve45046 = ' Status CVE-2021-45046 ' cve44228 = ' Status CVE-2021-44228 ' _, vendor, product, version, status, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, comment, link])) def mutate_underline(line) -> str: cve4104 = ':--------------------:' cve45046 = ':---------------------:' cve44228 = ':---------------------:' _, vendor, product, version, status, comment, link, _ = line.split('|') return(table_line([vendor, product, version, cve4104, cve44228, cve45046, comment, link])) def mutate_record(line) -> str: cve4104 = ' ' cve45046 = ' ' _, vendor, product, version, status, comment, link, _ = line.split('|') cve44228 = ' '+status.strip()+' ' if 'Fix' in cve44228: cve4104 = ' Not vuln ' if 'Not vuln' in cve44228: cve4104 = ' Not vuln ' cve45046 = ' Not vuln ' if 'Workaround' in cve44228: cve4104 = ' Not vuln ' return(table_line([vendor, product, version, cve4104, cve44228, cve45046, comment, link])) def mutate(ctx, input): with sys.stdout as output: for line in input: try: # not a table, just copy if line[0] != '|': output.write(line) continue # initial status table, just copy if line.count('|') == 3: output.write(line) continue # table header, add header fields if '| Supplier' in line: output.write(mutate_header(line)) continue # table underline, add header fields if '|:----' in line: output.write(mutate_underline(line)) continue # table line, add cells output.write(mutate_record(line)) except ValueError as e: print("\nOffending line:", file=sys.stderr) print(line, file=sys.stderr) raise e
null
6,965
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag def parse_record(record: List[Tag] = None) -> dict: """ Parse single tr record in Software list :return: Dictionary of parsed cell from record """ result = dict() link_index = len(HEADERS) - 1 for index, header in enumerate(HEADERS): # Parse links differently if index == link_index: if len(record) == link_index: result[header] = {} else: result[header] = parse_links(record[index].find_all('a')) else: # Ensure unicode in text is properly parsed result[header] = unicodedata.normalize("NFKD", record[index].text) return result The provided code snippet includes necessary dependencies for implementing the `parse_software_file` function. Write a Python function `def parse_software_file(path: Path) -> Iterator[dict]` to solve the following problem: Parse a single software list file :param path: path of file to parse :yield: a single parse record from file Here is the function: def parse_software_file(path: Path) -> Iterator[dict]: """ Parse a single software list file :param path: path of file to parse :yield: a single parse record from file """ # Parse Markdown to HTML and get soup with path.open('r') as f: content = f.read() html = mistune.html(content) soup = BeautifulSoup(html, 'html.parser') # Look for all tr columns with td fields, after first h3 header for row in soup.find_all('tr'): tds = row.find_all('td') if tds: # ensure empty tr are ignored yield parse_record(tds)
Parse a single software list file :param path: path of file to parse :yield: a single parse record from file
6,966
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag def json(ctx, output): py_json.dump(ctx.obj['records'], output)
null
6,967
import sys import csv as py_csv import json as py_json from pathlib import Path from typing import List, Iterator import click import mistune import unicodedata from bs4 import BeautifulSoup from bs4.element import Tag HEADERS = [ 'Supplier', 'Product', 'Version', 'Status CVE-2021-4104', 'Status CVE-2021-44228', 'Status CVE-2021-45046', 'Status CVE-2021-45105', 'Notes', 'Links' ] def csv(ctx, output): writer = py_csv.DictWriter(output, HEADERS) writer.writeheader() # cleanup links for record in ctx.obj['records']: record['Links'] = list(record['Links'].values()) writer.writerow(record)
null
6,968
import base64 import copy import json import logging import operator import re import uuid from decimal import Decimal from functools import reduce from itertools import chain from typing import Optional import posthog import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import ( Count, DecimalField, F, Max, Min, OuterRef, Prefetch, Q, Subquery, Sum, Value, ) from django.db.models.functions import Coalesce from django.db.utils import IntegrityError from django.http import HttpRequest, HttpResponseBadRequest, JsonResponse from django.views.decorators.csrf import csrf_exempt from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import ( OpenApiExample, OpenApiParameter, extend_schema, inline_serializer, ) from rest_framework import mixins, serializers, status, viewsets from rest_framework.decorators import ( action, api_view, authentication_classes, permission_classes, ) from rest_framework.exceptions import ValidationError from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from api.serializers.model_serializers import ( AddOnSubscriptionRecordCreateSerializer, AddOnSubscriptionRecordSerializer, AddOnSubscriptionRecordUpdateSerializer, CustomerBalanceAdjustmentCreateSerializer, CustomerBalanceAdjustmentFilterSerializer, CustomerBalanceAdjustmentSerializer, CustomerBalanceAdjustmentUpdateSerializer, CustomerCreateSerializer, CustomerSerializer, EventSerializer, InvoiceListFilterSerializer, InvoicePaymentSerializer, InvoiceSerializer, InvoiceUpdateSerializer, ListPlansFilterSerializer, ListPlanVersionsFilterSerializer, ListSubscriptionRecordFilter, PlanSerializer, SubscriptionFilterSerializer, SubscriptionRecordCancelSerializer, SubscriptionRecordCreateSerializer, SubscriptionRecordCreateSerializerOld, SubscriptionRecordFilterSerializer, SubscriptionRecordFilterSerializerDelete, SubscriptionRecordSerializer, SubscriptionRecordSwitchPlanSerializer, SubscriptionRecordUpdateSerializer, SubscriptionRecordUpdateSerializerOld, ) from api.serializers.nonmodel_serializers import ( ChangePrepaidUnitsSerializer, CustomerDeleteResponseSerializer, FeatureAccessRequestSerializer, FeatureAccessResponseSerializer, MetricAccessRequestSerializer, MetricAccessResponseSerializer, ) from metering_billing.auth.auth_utils import ( PermissionPolicyMixin, fast_api_key_validation_and_cache, ) from metering_billing.exceptions import ( DuplicateCustomer, ServerError, SwitchPlanDurationMismatch, SwitchPlanSamePlanException, ) from metering_billing.exceptions.exceptions import InvalidOperation, NotFoundException from metering_billing.invoice import generate_invoice from metering_billing.invoice_pdf import get_invoice_presigned_url from metering_billing.kafka.producer import Producer from metering_billing.models import ( ComponentChargeRecord, Customer, CustomerBalanceAdjustment, Event, Invoice, InvoiceLineItem, Metric, Plan, PlanComponent, PriceTier, RecurringCharge, SubscriptionRecord, Tag, ) from metering_billing.permissions import HasUserAPIKey, ValidOrganization from metering_billing.serializers.model_serializers import ( DraftInvoiceSerializer, MetricDetailSerializer, ) from metering_billing.serializers.request_serializers import ( DraftInvoiceRequestSerializer, PeriodRequestSerializer, ) from metering_billing.serializers.response_serializers import CostAnalysisSerializer from metering_billing.serializers.serializer_utils import ( AddOnUUIDField, AddOnVersionUUIDField, BalanceAdjustmentUUIDField, InvoiceUUIDField, MetricUUIDField, OrganizationUUIDField, PlanUUIDField, SlugRelatedFieldWithOrganizationPK, SubscriptionUUIDField, ) from metering_billing.utils import ( calculate_end_date, convert_to_date, convert_to_datetime, convert_to_decimal, dates_bwn_two_dts, make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, INVOICING_BEHAVIOR, METRIC_STATUS, PLAN_CUSTOM_TYPE, SUBSCRIPTION_STATUS, USAGE_BEHAVIOR, USAGE_BILLING_BEHAVIOR, ) from metering_billing.webhooks import ( customer_created_webhook, subscription_cancelled_webhook, subscription_created_webhook, ) def load_event(request: HttpRequest) -> Optional[dict]: def ingest_event(data: dict, customer_id: str, organization_pk: int) -> None: def fast_api_key_validation_and_cache(request): def track_event(request): result, success = fast_api_key_validation_and_cache(request) if not success: return result else: organization_pk = result try: event_list = load_event(request) except Exception as e: return HttpResponseBadRequest(f"Invalid event data: {e}") if not event_list: return HttpResponseBadRequest("No data provided") if not isinstance(event_list, list): if "batch" in event_list: event_list = event_list["batch"] else: event_list = [event_list] bad_events = {} now = now_utc() for data in event_list: customer_id = data.get("customer_id") idempotency_id = data.get("idempotency_id") time_created = data.get("time_created") if not idempotency_id: bad_events["no_idempotency_id"] = "No idempotency_id provided" continue if not customer_id: bad_events[idempotency_id] = "No customer_id provided" continue if not time_created: bad_events[idempotency_id] = "Invalid time_created" continue tc = parser.parse(time_created) # Check if the datetime object is naive if tc.tzinfo is None or tc.tzinfo.utcoffset(tc) is None: # If the datetime object is naive, replace its tzinfo with UTC tc = tc.replace(tzinfo=pytz.UTC) if not (now - relativedelta(days=30) <= tc <= now + relativedelta(days=1)): bad_events[ idempotency_id ] = "Time created too far in the past or future. Events must be within 30 days before or 1 day ahead of current time." continue data["time_created"] = tc.isoformat() try: transformed_event = ingest_event(data, customer_id, organization_pk) stream_events = { "organization_id": organization_pk, "event": transformed_event, } if kafka_producer: kafka_producer.produce(customer_id, stream_events) except Exception as e: bad_events[idempotency_id] = str(e) continue if len(bad_events) == len(event_list): return Response( {"success": "none", "failed_events": bad_events}, status=status.HTTP_400_BAD_REQUEST, ) elif len(bad_events) > 0: return JsonResponse( {"success": "some", "failed_events": bad_events}, status=status.HTTP_201_CREATED, ) else: return JsonResponse({"success": "all"}, status=status.HTTP_201_CREATED)
null
6,969
from __future__ import unicode_literals import logging import django from django.core import signals from django.core.cache.backends.base import BaseCache import django.db.backends.utils from django.db import OperationalError django.db.backends.utils.CursorWrapper.execute = execute_wrapper def get_cache(backend, **kwargs): from django.core import cache as dj_cache if django.VERSION <= (1, 6): cache = dj_cache.get_cache(backend, **kwargs) elif django.VERSION >= (3, 2): cache = dj_cache.caches.create_connection(backend) else: # Django 1.7 to 3.1 cache = dj_cache._create_cache(backend, **kwargs) # Some caches -- python-memcached in particular -- need to do a cleanup at the # end of a request cycle. If not implemented in a particular backend # cache.close is a no-op. Not available in Django 1.5 if hasattr(cache, "close"): signals.request_finished.connect(cache.close) return cache
null
6,970
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import load_dotenv from kafka import KafkaConsumer from kafka.admin import KafkaAdminClient, NewTopic from kafka.errors import TopicAlreadyExistsError from sentry_sdk.integrations.django import DjangoIntegration from svix.api import EventTypeIn, Svix, SvixOptions logger = logging.getLogger("django.server") def value_deserializer(value): try: return loads(value.decode("utf-8")) except Exception as e: logger.error("Value deserialization error:", e) return None
null
6,971
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import load_dotenv from kafka import KafkaConsumer from kafka.admin import KafkaAdminClient, NewTopic from kafka.errors import TopicAlreadyExistsError from sentry_sdk.integrations.django import DjangoIntegration from svix.api import EventTypeIn, Svix, SvixOptions logger = logging.getLogger("django.server") def key_deserializer(key): try: return key.decode("utf-8") except Exception as e: logger.error("Key deserialization error:", e) return None
null
6,972
import datetime import logging import os import re import uuid from datetime import timedelta, timezone from json import loads from pathlib import Path from urllib.parse import urlparse import dj_database_url import django_heroku import jwt import posthog import sentry_sdk from decouple import config from dotenv import load_dotenv from kafka import KafkaConsumer from kafka.admin import KafkaAdminClient, NewTopic from kafka.errors import TopicAlreadyExistsError from sentry_sdk.integrations.django import DjangoIntegration from svix.api import EventTypeIn, Svix, SvixOptions def immutable_file_test(path, url): # Match filename with 12 hex digits before the extension # e.g. app.db8f2edc0c8a.js return re.match(r"^.+\.[0-9a-f]{8,12}\..+$", url)
null
6,973
import logging from dataclasses import dataclass import sentry_sdk from django.conf import settings from metering_billing.models import Event from metering_billing.utils import now_utc from .singleton import Singleton class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=models.SET_NULL, related_name="+", null=True, blank=True ) cust_id = models.TextField(blank=True) uuidv5_customer_id = models.UUIDField() event_name = models.TextField( help_text="String name of the event, corresponds to definition in metrics", ) uuidv5_event_name = models.UUIDField() time_created = models.DateTimeField( help_text="The time that the event occured, represented as a datetime in RFC3339 in the UTC timezome." ) properties = models.JSONField( default=dict, blank=True, help_text="Extra metadata on the event that can be filtered and queried on in the metrics. All key value pairs should have string keys and values can be either strings or numbers. Place subscription filters in this object to specify which subscription the event should be tracked under", ) idempotency_id = models.TextField( default=event_uuid, help_text="A unique identifier for the specific event being passed in. Passing in a unique id allows Lotus to make sure no double counting occurs. We recommend using a UUID4. You can use the same idempotency_id again after 45 days.", primary_key=True, ) uuidv5_idempotency_id = models.UUIDField() inserted_at = models.DateTimeField(default=now_utc) objects = EventManager() class Meta: managed = False db_table = "metering_billing_usageevent" def __str__(self): return ( str(self.event_name)[:6] + "-" + str(self.cust_id)[:8] + "-" + str(self.time_created)[:10] + "-" + str(self.idempotency_id)[:6] ) def write_batch_events_to_db(buffer): now = now_utc() for org_pk, events_list in buffer.items(): ### Match Customer pk with customer_id amd fill in customer pk events_to_insert = [] for event in events_list: event["cust_id"] = event.pop("customer_id") events_to_insert.append(Event(**{**event, "inserted_at": now})) ## now insert events Event.objects.bulk_create(events_to_insert, ignore_conflicts=True)
null
6,974
import json import pycountry import requests import sentry_sdk from django.conf import settings from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import ( CRMIntegrationNotAllowed, CRMNotSupported, EnvironmentNotConnected, ) from metering_billing.models import ( Address, Customer, Invoice, UnifiedCRMCustomerIntegration, UnifiedCRMInvoiceIntegration, UnifiedCRMOrganizationIntegration, ) from metering_billing.permissions import ValidOrganization from rest_framework import mixins, serializers, status, viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from scourgify import normalize_address_record def send_invoice_to_salesforce(invoice, customer, accountId, access_token): headers = { "vessel-api-token": VESSEL_API_KEY, } url = "https://api.vessel.land/crm/note" body = { "lotus_url": VITE_API_URL + f"customers/{customer.customer_id}", "invoice_pdf": invoice.invoice_pdf, } note = { "accountId": accountId, "content": json.dumps(body), "isPrivate": False, "additional": { "Title": f"[LOTUS] Invoice on {invoice.issue_date.strftime('%Y-%m-%d')}", }, } payload = { "accessToken": access_token, "note": note, } response = requests.post(url, headers=headers, json=payload) try: response.raise_for_status() # raises exception when not a 2xx response except requests.exceptions.HTTPError as e: sentry_sdk.capture_exception(e) print(e) print(response.text) return unified_id = response.json()["id"] get_url = url + f"?accessToken={access_token}&id={unified_id}" response = requests.get( get_url, headers=headers, ) response_json = response.json() integration = UnifiedCRMInvoiceIntegration.objects.create( organization=invoice.organization, crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE, unified_note_id=unified_id, native_invoice_id=response_json["note"]["nativeId"], ) invoice.salesforce_integration = integration invoice.save() class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status class UnifiedCRMOrganizationIntegration(models.Model): class CRMProvider(models.IntegerChoices): SALESFORCE = (1, "salesforce") organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="unified_crm_organization_links", ) crm_provider = models.IntegerField(choices=CRMProvider.choices) access_token = models.TextField() native_org_url = models.TextField() native_org_id = models.TextField() connection_id = models.TextField() created = models.DateTimeField(default=now_utc) class Meta: constraints = [ UniqueConstraint( fields=[ "organization", "crm_provider", ], name="unique_crm_provider", ), ] def get_crm_provider_from_label(label): mapping = { UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.label: UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.value, } return mapping.get(label, label) def perform_sync(self): if ( self.crm_provider == UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ): self.perform_salesforce_sync() else: raise NotImplementedError("CRM type not supported") def perform_salesforce_sync(self): from metering_billing.views.crm_views import ( sync_customers_with_salesforce, sync_invoices_with_salesforce, ) sync_customers_with_salesforce(self.organization) sync_invoices_with_salesforce(self.organization) def sync_invoices_with_salesforce(organization): connection = organization.unified_crm_organization_links.get( crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ) access_token = connection.access_token customers_with_integration = organization.customers.filter( salesforce_integration__isnull=False ) invoices_from_customers = Invoice.objects.filter( customer__in=customers_with_integration ) for customer in customers_with_integration: invoices = invoices_from_customers.filter( customer=customer, salesforce_integration__isnull=True ) accountId = customer.salesforce_integration.unified_account_id if not accountId: continue for invoice in invoices: send_invoice_to_salesforce(invoice, customer, accountId, access_token)
null
6,975
import json import pycountry import requests import sentry_sdk from django.conf import settings from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import ( CRMIntegrationNotAllowed, CRMNotSupported, EnvironmentNotConnected, ) from metering_billing.models import ( Address, Customer, Invoice, UnifiedCRMCustomerIntegration, UnifiedCRMInvoiceIntegration, UnifiedCRMOrganizationIntegration, ) from metering_billing.permissions import ValidOrganization from rest_framework import mixins, serializers, status, viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from scourgify import normalize_address_record VESSEL_API_KEY = settings.VESSEL_API_KEY class Address(models.Model): organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="addresses" ) city = models.CharField( max_length=50, help_text="City, district, suburb, town, or village" ) country = models.CharField( max_length=2, help_text="Two-letter country code (ISO 3166-1 alpha-2)", validators=[MinLengthValidator(2), MaxLengthValidator(2)], choices=list([(x.alpha_2, x.name) for x in pycountry.countries]), ) line1 = models.TextField( max_length=100, help_text="Address line 1 (e.g., street, PO Box, or company name)", ) line2 = models.TextField( help_text="Address line 2 (e.g., apartment, suite, unit, or building)", null=True, ) postal_code = models.CharField( max_length=20, help_text="ZIP or postal code", ) state = models.CharField( max_length=30, help_text="State, county, province, or region", null=True, ) def __str__(self): return f"Address: {self.line1}, {self.city}, {self.state}, {self.postal_code}, {self.country}" class Customer(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="customers" ) customer_name = models.TextField( blank=True, help_text="The display name of the customer", null=True, ) email = models.EmailField( max_length=100, help_text="The primary email address of the customer, must be the same as the email address used to create the customer in the payment provider", null=True, ) customer_id = models.TextField( default=customer_uuid, help_text="The id provided when creating the customer, we suggest matching with your internal customer id in your backend", null=True, ) uuidv5_customer_id = models.UUIDField( help_text="The v5 UUID generated from the customer_id. This is used for efficient lookups in the database, specifically for the Events table", null=True, ) properties = models.JSONField( default=dict, null=True, help_text="Extra metadata for the customer" ) deleted = models.DateTimeField( null=True, help_text="The date the customer was deleted" ) # BILLING RELATED FIELDS default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="customers", null=True, blank=True, help_text="The currency the customer will be invoiced in", ) shipping_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="shipping_customers", null=True, blank=True, help_text="The shipping address for the customer", ) billing_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="billing_customers", null=True, blank=True, help_text="The billing address for the customer", ) # TAX RELATED FIELDS tax_providers = TaxProviderListField(default=[]) tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) # TIMEZONE FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) timezone_set = models.BooleanField(default=False) # PAYMENT PROCESSOR FIELDS payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) braintree_integration = models.ForeignKey( "BraintreeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) salesforce_integration = models.OneToOneField( "UnifiedCRMCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customer", ) # HISTORY FIELDS created = models.DateTimeField(default=now_utc) history = HistoricalRecords() objects = BaseCustomerManager() deleted_objects = DeletedCustomerManager() class Meta: constraints = [ UniqueConstraint(fields=["organization", "email"], name="unique_email"), UniqueConstraint( fields=["organization", "customer_id"], name="unique_customer_id" ), ] def __str__(self) -> str: return str(self.customer_name) + " " + str(self.customer_id) def save(self, *args, **kwargs): if not self.default_currency: try: self.default_currency = ( self.organization.default_currency or PricingUnit.objects.get( code="USD", organization=self.organization ) ) except PricingUnit.DoesNotExist: self.default_currency = None super(Customer, self).save(*args, **kwargs) def get_active_subscription_records(self): active_subscription_records = self.subscription_records.active().filter( fully_billed=False, ) return active_subscription_records def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_usage_and_revenue(self): customer_subscriptions = ( SubscriptionRecord.objects.active() .filter( customer=self, organization=self.organization, ) .prefetch_related("billing_plan__plan_components") .prefetch_related("billing_plan__plan_components__billable_metric") .select_related("billing_plan") ) subscription_usages = {"subscriptions": [], "sub_objects": []} for subscription in customer_subscriptions: sub_dict = subscription.get_usage_and_revenue() del sub_dict["components"] sub_dict["billing_plan_name"] = subscription.billing_plan.plan.plan_name subscription_usages["subscriptions"].append(sub_dict) subscription_usages["sub_objects"].append(subscription) return subscription_usages def get_active_sub_drafts_revenue(self): from metering_billing.invoice import generate_invoice total = 0 sub_records = self.get_active_subscription_records() if sub_records is not None and len(sub_records) > 0: invs = generate_invoice( sub_records, draft=True, charge_next_plan=True, ) total += sum([inv.amount for inv in invs]) for inv in invs: inv.delete() return total def get_currency_balance(self, currency): now = now_utc() balance = self.customer_balance_adjustments.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), effective_at__lte=now, amount_currency=currency, ).aggregate(balance=Sum("amount"))["balance"] or Decimal(0) return balance def get_outstanding_revenue(self): unpaid_invoice_amount_due = ( self.invoices.filter(payment_status=Invoice.PaymentStatus.UNPAID) .aggregate(unpaid_inv_amount=Sum("amount")) .get("unpaid_inv_amount") ) total_amount_due = unpaid_invoice_amount_due or 0 return total_amount_due def get_billing_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="billing") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.billing_address def get_shipping_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="shipping") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.shipping_address class UnifiedCRMOrganizationIntegration(models.Model): class CRMProvider(models.IntegerChoices): SALESFORCE = (1, "salesforce") organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="unified_crm_organization_links", ) crm_provider = models.IntegerField(choices=CRMProvider.choices) access_token = models.TextField() native_org_url = models.TextField() native_org_id = models.TextField() connection_id = models.TextField() created = models.DateTimeField(default=now_utc) class Meta: constraints = [ UniqueConstraint( fields=[ "organization", "crm_provider", ], name="unique_crm_provider", ), ] def get_crm_provider_from_label(label): mapping = { UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.label: UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.value, } return mapping.get(label, label) def perform_sync(self): if ( self.crm_provider == UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ): self.perform_salesforce_sync() else: raise NotImplementedError("CRM type not supported") def perform_salesforce_sync(self): from metering_billing.views.crm_views import ( sync_customers_with_salesforce, sync_invoices_with_salesforce, ) sync_customers_with_salesforce(self.organization) sync_invoices_with_salesforce(self.organization) class UnifiedCRMCustomerIntegration(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="unified_crm_customer_links", ) crm_provider = models.IntegerField( choices=UnifiedCRMOrganizationIntegration.CRMProvider.choices ) native_customer_id = models.TextField(null=True) unified_account_id = models.TextField() def __str__(self): return f"[{self.get_crm_provider_display()}] {self.native_customer_id} - {self.unified_account_id}" class Meta: constraints = [ UniqueConstraint( condition=Q(native_customer_id__isnull=False), fields=["organization", "crm_provider", "native_customer_id"], name="unique_crm_customer_id_per_type", ), ] def get_crm_url(self): if ( self.crm_provider == UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ): if self.native_customer_id is None: return None objectType = "Account" objectId = self.native_customer_id nativeOrgURL = self.organization.unified_crm_organization_links.get( crm_provider=self.crm_provider ).native_org_url return f"{nativeOrgURL}/lightning/r/{objectType}/{objectId}/view" else: raise NotImplementedError("CRM type not supported") def sync_customers_with_salesforce(organization): lotus_is_source = organization.lotus_is_customer_source_for_salesforce connection = organization.unified_crm_organization_links.get( crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ) access_token = connection.access_token headers = { "vessel-api-token": VESSEL_API_KEY, } url = f"https://api.vessel.land/crm/accounts?accessToken={access_token}&allFields=true" response = requests.get(url, headers=headers) response.raise_for_status() # raises exception when not a 2xx response accounts = response.json()["accounts"] customer_ids_set = {x["additional"].get("AccountNumber") for x in accounts} native_ids_set = {x["nativeId"] for x in accounts} if lotus_is_source: url = "https://api.vessel.land/crm/account" headers = { "Content-Type": "application/json", "vessel-api-token": VESSEL_API_KEY, } for customer in organization.customers.all(): payload = { "accessToken": access_token, "account": { "name": customer.customer_name, "email": customer.email, }, } if customer.shipping_address: payload["additional"] = {} payload["additional"]["ShippingAddress"] = { "street": customer.shipping_address.line1, "city": customer.shipping_address.city, "state": customer.shipping_address.state, "country": customer.shipping_address.country, "postalCode": customer.shipping_address.postal_code, } if customer.billing_address: if not payload.get("additional"): payload["additional"] = {} payload["additional"]["BillingAddress"] = { "street": customer.billing_address.line1, "city": customer.billing_address.city, "state": customer.billing_address.state, "country": customer.billing_address.country, "postalCode": customer.billing_address.postal_code, } if customer.salesforce_integration: response = requests.patch( url, headers=headers, data=json.dumps(payload) ) else: # not in salesforce! We create response = requests.post(url, headers=headers, data=json.dumps(payload)) unified_id = response.json()["id"] get_url = url + f"?accessToken={access_token}&id={unified_id}" response = requests.get( get_url, headers=headers, ) response_json = response.json() integration = UnifiedCRMCustomerIntegration.objects.create( organization=organization, crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE, unified_account_id=unified_id, native_customer_id=response_json["account"]["nativeId"], ) customer.salesforce_integration = integration customer.save() else: lotus_customers = organization.customers.filter( customer_id__in=customer_ids_set ) lotus_customer_integrations = organization.unified_crm_customer_links.filter( native_customer_id__in=native_ids_set ) for account in accounts: name = account["name"] internal_id = ( account["additional"].get("AccountNumber") or account["nativeId"] ) native_id = account["nativeId"] unified_id = account["id"] billing_address = account["additional"]["BillingAddress"] shipping_address = account["additional"]["ShippingAddress"] if billing_address: try: fuzzy_country = pycountry.countries.search_fuzzy( billing_address["country"] ) except Exception: fuzzy_country = None try: billing_address, _ = Address.objects.get_or_create( line1=billing_address["street"], city=billing_address["city"], state=billing_address["state"], country=fuzzy_country[0].alpha_2, postal_code=billing_address["postalCode"], ) except Exception: try: normalized = normalize_address_record(billing_address["street"]) billing_address, _ = Address.objects.get_or_create( line1=normalized["address_line_1"], line2=normalized["address_line_2"], city=normalized["city"], state=normalized["state"], country="US", postal_code=normalized["postal_code"], ) except Exception: billing_address = None if shipping_address: try: fuzzy_country = pycountry.countries.search_fuzzy( shipping_address["country"] ) except Exception: fuzzy_country = None try: shipping_address, _ = Address.objects.get_or_create( line1=shipping_address["street"], city=shipping_address["city"], state=shipping_address["state"], country=fuzzy_country[0].alpha_2, postal_code=shipping_address["postalCode"], ) except Exception: try: normalized = normalize_address_record( shipping_address["street"] ) shipping_address, _ = Address.objects.get_or_create( line1=normalized["address_line_1"], line2=normalized["address_line_2"], city=normalized["city"], state=normalized["state"], country="US", postal_code=normalized["postal_code"], ) except Exception: shipping_address = None integration = lotus_customer_integrations.filter( native_customer_id=native_id ).first() matching_customer = lotus_customers.filter(customer_id=internal_id).first() if integration: customer = integration.customer elif matching_customer: customer = matching_customer else: customer = None if customer is None: customer = Customer.objects.create( organization=organization, customer_id=internal_id, customer_name=name, billing_address=billing_address, shipping_address=shipping_address, ) else: customer.customer_name = name customer.billing_address = billing_address customer.shipping_address = shipping_address customer.save() customer_integration = customer.salesforce_integration if not customer_integration: customer_integration = UnifiedCRMCustomerIntegration.objects.create( organization=organization, crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE, native_customer_id=native_id, unified_account_id=unified_id, ) customer.salesforce_integration = customer_integration customer.save()
null
6,976
import logging from django.conf import settings from django.core.mail import BadHeaderError, EmailMultiAlternatives from drf_spectacular.utils import extend_schema, inline_serializer from metering_billing.exceptions import DuplicateCustomer from metering_billing.models import TeamInviteToken, User from metering_billing.permissions import ValidOrganization from metering_billing.utils import now_plus_day, now_utc from rest_framework import serializers, status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView DEFAULT_FROM_EMAIL = settings.DEFAULT_FROM_EMAIL logger = logging.getLogger("django.server") def send_invite_email(reset_url, organization_name, to): subject = f"Join {organization_name} in Lotus" body = f"Use this link to join {organization_name} team: {reset_url}" from_email = f"Lotus <{DEFAULT_FROM_EMAIL}>" html = """ <p>Register to <a href={url}>join {organization_name}</a> team</p>""".format( url=reset_url, organization_name=organization_name ) msg = EmailMultiAlternatives(subject, body, from_email, [to]) msg.attach_alternative(html, "text/html") msg.tags = ["join_team"] msg.track_clicks = True try: msg.send() except BadHeaderError: logger.error("Invalid header found.") return False return True return True
null
6,977
import stripe from django.conf import settings from django.views.decorators.csrf import csrf_exempt from rest_framework import status from rest_framework.decorators import ( api_view, authentication_classes, permission_classes, ) from rest_framework.response import Response from metering_billing.kafka.producer import Producer from metering_billing.models import Invoice from metering_billing.utils import now_utc from metering_billing.utils.enums import PAYMENT_PROCESSORS STRIPE_WEBHOOK_SECRET = settings.STRIPE_WEBHOOK_SECRET def _invoice_paid_handler(event): invoice = event["data"]["object"] id = invoice.id matching_invoice = Invoice.objects.filter( external_payment_obj_type=PAYMENT_PROCESSORS.STRIPE, external_payment_obj_id=id ).first() if matching_invoice: matching_invoice.payment_status = Invoice.PaymentStatus.PAID matching_invoice.save() if kafka_producer: kafka_producer.produce_invoice_pay_in_full( invoice=matching_invoice, payment_date=now_utc(), source=PAYMENT_PROCESSORS.STRIPE, ) def _invoice_updated_handler(event): invoice = event["data"]["object"] id = invoice.id matching_invoice = Invoice.objects.filter( external_payment_obj_type=PAYMENT_PROCESSORS.STRIPE, external_payment_obj_id=id ).first() if matching_invoice: matching_invoice.external_payment_obj_status = invoice.status matching_invoice.save() def stripe_webhook_endpoint(request): payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] event = None # Try to validate and create a local instance of the event try: event = stripe.Webhook.construct_event( payload, sig_header, STRIPE_WEBHOOK_SECRET ) except ValueError as e: return Response(f"Invalid payload: {e}", status=status.HTTP_400_BAD_REQUEST) except stripe.error.SignatureVerificationError as e: return Response(f"Invalid signature: {e}", status=status.HTTP_400_BAD_REQUEST) # Handle the checkout.session.completed event if event["type"] == "invoice.paid": _invoice_paid_handler(event) if event["type"] == "invoice.updated": _invoice_updated_handler(event) # Passed signature verification return Response(status=status.HTTP_200_OK)
null
6,978
def remove_invalid_subscription_methods(endpoints): # your modifications to the list of operations that are exposed in the schema to_remove = [] for path, path_regex, method, callback in endpoints: if (path == r"/api/subscriptions/" and method == "POST") or ( path == r"/api/subscriptions/{subscription_id}/" ): to_remove.append((path, path_regex, method, callback)) for item in to_remove: endpoints.remove(item) return endpoints
null
6,979
def remove_required_parent_plan_and_target_customer(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["Plan"]["required"] = [ x for x in schemas["Plan"]["required"] if x not in ["parent_plan", "target_customer"] ] return result
null
6,980
def remove_required_address_from_lw_cust_invoice(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["LightweightCustomerSerializerForInvoice"]["required"] = [ x for x in schemas["LightweightCustomerSerializerForInvoice"]["required"] if x not in ["address"] ] schemas["Seller"]["required"] = [ x for x in schemas["Seller"]["required"] if x not in ["address"] ] schemas["Customer"]["required"] = [ x for x in schemas["Customer"]["required"] if x not in ["address"] ] return result
null
6,981
def remove_required_external_payment_obj_type(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) schemas["LightweightInvoice"]["required"] = [ x for x in schemas["LightweightInvoice"]["required"] if x not in ["external_payment_obj_type"] ] return result
null
6,982
def add_external_payment_obj_type_to_required(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) if "external_payment_obj_type" not in schemas["LightweightInvoice"]["required"]: schemas["LightweightInvoice"]["required"].append("external_payment_obj_type") return result
null
6,983
def add_plan_id_parent_plan_target_customer_to_required(result, **kwargs): schemas = result.get("components", {}).get("schemas", {}) if "plan_id" not in schemas["Plan"]["required"]: schemas["Plan"]["required"].append("plan_id") if "parent_plan" not in schemas["Plan"]["required"]: schemas["Plan"]["required"].append("parent_plan") if "target_customer" not in schemas["Plan"]["required"]: schemas["Plan"]["required"].append("target_customer") return result
null
6,984
import abc import base64 import datetime import logging from decimal import Decimal from typing import Literal, Optional, Tuple from urllib.parse import urlencode import braintree import pytz import requests import sentry_sdk import stripe from django.conf import settings from django.core.cache import cache from django.db.models import F, Prefetch, Q from rest_framework import serializers, status from rest_framework.response import Response from metering_billing.serializers.payment_processor_serializers import ( PaymentProcesorPostResponseSerializer, ) from metering_billing.utils import ( convert_to_two_decimal_places, now_utc, parse_nested_response, ) from metering_billing.utils.enums import PAYMENT_PROCESSORS def base64_encode(data: str) -> str: string_bytes = data.encode("ascii") base64_bytes = base64.b64encode(string_bytes) base64_string = base64_bytes.decode("ascii") return base64_string
null
6,985
import logging from collections.abc import Iterable from decimal import Decimal import sentry_sdk from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q, Sum from django.db.models.query import QuerySet from metering_billing.kafka.producer import Producer from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.taxes import get_lotus_tax_rates, get_taxjar_tax_rates from metering_billing.utils import ( calculate_end_date, convert_to_datetime, date_as_min_dt, now_utc, ) from metering_billing.utils.enums import ( CHARGEABLE_ITEM_TYPE, CUSTOMER_BALANCE_ADJUSTMENT_STATUS, INVOICE_CHARGE_TIMING_TYPE, TAX_PROVIDER, ) from metering_billing.webhooks import invoice_created_webhook def generate_external_payment_obj(invoice): from metering_billing.models import UnifiedCRMOrganizationIntegration from metering_billing.views.crm_views import send_invoice_to_salesforce customer = invoice.customer pp = customer.payment_provider if pp in PAYMENT_PROCESSOR_MAP and PAYMENT_PROCESSOR_MAP[pp].working(): pp_connector = PAYMENT_PROCESSOR_MAP[pp] customer_conn = pp_connector.customer_connected(customer) org_conn = pp_connector.organization_connected(invoice.organization) if customer_conn and org_conn: external_id, external_status = pp_connector.create_payment_object(invoice) if external_id: invoice.external_payment_obj_id = external_id invoice.external_payment_obj_type = pp invoice.external_payment_obj_status = external_status invoice.save() return invoice if customer.salesforce_integration: connection = customer.organization.unified_crm_organization_links.get( crm_provider=UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ) access_token = connection.access_token accountId = customer.salesforce_integration.unified_account_id send_invoice_to_salesforce(invoice, customer, accountId, access_token) return None def calculate_due_date(issue_date, organization): due_date = issue_date grace_period = organization.payment_grace_period if grace_period: due_date += relativedelta(days=grace_period) return due_date def finalize_invoice_amount(invoice, draft): from metering_billing.models import Invoice invoice.amount = invoice.line_items.aggregate(tot=Sum("amount"))["tot"] or 0 if abs(invoice.amount) < 0.01 and not draft: invoice.payment_status = Invoice.PaymentStatus.PAID invoice.save() def invoice_created_webhook(invoice, organization): from api.serializers.model_serializers import InvoiceSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.filter(organization=organization) .prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.INVOICE_CREATED) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) invoice_data = InvoiceSerializer(invoice).data invoice_data = make_all_decimals_floats(invoice_data) invoice_data = make_all_dates_times_strings(invoice_data) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.INVOICE_CREATED, "payload": invoice_data, } try: svix.message.create( organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.INVOICE_CREATED, event_id=str(organization.organization_id.hex) + "_" + str(invoice_data["invoice_number"]) + "_" + "created", payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e) class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status class InvoiceLineItem(models.Model): invoice_line_item_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoice_line_items", null=True, ) name = models.CharField(max_length=100) start_date = models.DateTimeField(max_length=100, default=now_utc) end_date = models.DateTimeField(max_length=100, default=now_utc) quantity = models.DecimalField( decimal_places=10, max_digits=20, null=True, blank=True, validators=[MinValueValidator(0)], ) base = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Base price of the line item. This is the price before any adjustments are applied.", ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Amount of the line item. This is the price after any adjustments are applied.", ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="line_items", null=True, blank=True, ) billing_type = models.CharField( max_length=40, choices=INVOICE_CHARGE_TIMING_TYPE.choices, blank=True, null=True ) chargeable_item_type = models.CharField( max_length=40, choices=CHARGEABLE_ITEM_TYPE.choices, blank=True, null=True ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, null=True, related_name="line_items" ) associated_plan_version = models.ForeignKey( "PlanVersion", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_subscription_record = models.ForeignKey( "SubscriptionRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_billing_record = models.ForeignKey( "BillingRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) metadata = models.JSONField(default=dict, blank=True, null=True) def __str__(self): return self.name + " " + str(self.invoice.invoice_number) + f"[{self.base}]" def save(self, *args, **kwargs): self.amount = self.base + sum( [adjustment.amount for adjustment in self.adjustments.all()] ) super().save(*args, **kwargs) def generate_invoice_pdf_async(invoice_pk): from metering_billing.invoice_pdf import get_invoice_presigned_url from metering_billing.models import Invoice invoice = Invoice.objects.get(pk=invoice_pk) try: pdf_url_dict = get_invoice_presigned_url(invoice) pdf_url = pdf_url_dict.get("url") except Exception as e: logger.error("RAN INTO ERROR GENERATING PDF: {}".format(e)) pdf_url = None invoice.invoice_pdf = pdf_url invoice.save() The provided code snippet includes necessary dependencies for implementing the `generate_balance_adjustment_invoice` function. Write a Python function `def generate_balance_adjustment_invoice(balance_adjustment, draft=False)` to solve the following problem: Generate an invoice for a subscription. Here is the function: def generate_balance_adjustment_invoice(balance_adjustment, draft=False): """ Generate an invoice for a subscription. """ from metering_billing.models import Invoice, InvoiceLineItem from metering_billing.tasks import generate_invoice_pdf_async issue_date = balance_adjustment.created customer = balance_adjustment.customer organization = balance_adjustment.organization due_date = calculate_due_date(issue_date, organization) # create kwargs for invoice invoice_kwargs = { "issue_date": issue_date, "organization": organization, "customer": customer, "payment_status": Invoice.PaymentStatus.DRAFT if draft else Invoice.PaymentStatus.UNPAID, "currency": balance_adjustment.amount_paid_currency, "due_date": due_date, } # Create the invoice invoice = Invoice.objects.create(**invoice_kwargs) # Create the invoice line item InvoiceLineItem.objects.create( name=f"Credit Grant: {balance_adjustment.amount_paid_currency.symbol}{balance_adjustment.amount}", start_date=issue_date, end_date=issue_date, quantity=None, base=balance_adjustment.amount_paid, billing_type=INVOICE_CHARGE_TIMING_TYPE.ONE_TIME, chargeable_item_type=CHARGEABLE_ITEM_TYPE.ONE_TIME_CHARGE, invoice=invoice, organization=organization, ) finalize_invoice_amount(invoice, draft) if not draft: generate_external_payment_obj(invoice) try: generate_invoice_pdf_async.delay(invoice.pk) except Exception as e: sentry_sdk.capture_exception(e) invoice_created_webhook(invoice, organization) if kafka_producer: kafka_producer.produce_invoice(invoice) return invoice
Generate an invoice for a subscription.
6,986
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( LightweightCustomerSerializer, LightweightMetricSerializer, LightweightPlanVersionSerializer, ) from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP from metering_billing.invoice import generate_invoice from metering_billing.models import ( Analysis, APIToken, Backtest, BacktestSubstitution, CategoricalFilter, ComponentFixedCharge, Customer, CustomerBalanceAdjustment, CustomPricingUnitConversion, Event, ExternalPlanLink, Feature, Invoice, InvoiceLineItem, Metric, NumericFilter, Organization, Plan, PlanComponent, PlanVersion, PriceAdjustment, PriceTier, PricingUnit, Product, RecurringCharge, SubscriptionRecord, TeamInviteToken, User, WebhookEndpoint, WebhookTrigger, ) from metering_billing.tasks import run_backtest, run_generate_invoice from metering_billing.utils import ( convert_to_decimal, date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_decimals_strings, now_utc, round_all_decimals_to_two_places, ) from metering_billing.utils.enums import ( ANALYSIS_KPI, BACKTEST_KPI, EVENT_TYPE, EXPERIMENT_STATUS, METRIC_AGGREGATION, METRIC_GRANULARITY, METRIC_STATUS, METRIC_TYPE, PLAN_DURATION, ) logger = logging.getLogger("django.server") def create_pc_and_tiers( organization, plan_version, billable_metric, max_units=None, free_units=None, cost_per_batch=None, metric_units_per_batch=None, ): pc = PlanComponent.objects.create( plan_version=plan_version, billable_metric=billable_metric, organization=organization, ) range_start = 0 if free_units is not None: PriceTier.objects.create( plan_component=pc, range_start=0, range_end=free_units, type=PriceTier.PriceTierType.FREE, organization=organization, ) range_start = free_units if cost_per_batch is not None: PriceTier.objects.create( plan_component=pc, range_start=range_start, range_end=max_units, type=PriceTier.PriceTierType.PER_UNIT, cost_per_batch=cost_per_batch, metric_units_per_batch=metric_units_per_batch, organization=organization, batch_rounding_type=PriceTier.BatchRoundingType.NO_ROUNDING, ) def random_date(start, end, n): """Generate a random datetime between `start` and `end`""" if type(start) is datetime.date: start = date_as_min_dt(start, timezone=pytz.UTC) if type(end) is datetime.date: end = date_as_max_dt(end, timezone=pytz.UTC) for _ in range(n): dt = start + relativedelta( # Get a random amount of seconds between `start` and `end` seconds=random.randint(0, int((end - start).total_seconds())), ) yield dt def gaussian_users(n, mean=3, sd=1, mx=None): "Generate `n` latencies with a gaussian distribution" for _ in range(n): qty = round(random.gauss(mean, sd), 0) if mx is not None: qty = min(qty, mx) yield { "qty": int(max(qty, 1)), } def make_subscription_record( organization, customer, plan, start_date, is_new, ): sr = SubscriptionRecord.create_subscription_record( start_date=start_date, end_date=None, billing_plan=plan, customer=customer, organization=organization, subscription_filters=None, is_new=is_new, quantity=1, do_generate_invoice=False, ) return sr METRIC_HANDLER_MAP = { METRIC_TYPE.COUNTER: CounterHandler, METRIC_TYPE.GAUGE: GaugeHandler, METRIC_TYPE.RATE: RateHandler, METRIC_TYPE.CUSTOM: CustomHandler, } class Organization(models.Model): class OrganizationType(models.IntegerChoices): PRODUCTION = (1, "Production") DEVELOPMENT = (2, "Development") EXTERNAL_DEMO = (3, "Demo") INTERNAL_DEMO = (4, "Internal Demo") team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="organizations" ) organization_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization_name = models.TextField(blank=False, null=False) created = models.DateField(default=now_utc) organization_type = models.PositiveSmallIntegerField( choices=OrganizationType.choices, default=OrganizationType.DEVELOPMENT ) properties = models.JSONField(default=dict, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) # BILLING RELATED FIELDS default_payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) braintree_integration = models.ForeignKey( "BraintreeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="+", null=True, blank=True, help_text="The primary origin address for the organization", ) default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) # TAX RELATED FIELDS tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) tax_providers = TaxProviderListField(default=[TAX_PROVIDER.LOTUS]) # TIMEZONE RELATED FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) __original_timezone = None # SUBSCRIPTION RELATED FIELDS subscription_filter_keys = ArrayField( models.TextField(), default=list, blank=True, help_text="Allowed subscription filter keys", ) __original_subscription_filter_keys = None # PROVISIONING FIELDS webhooks_provisioned = models.BooleanField(default=False) currencies_provisioned = models.IntegerField(default=0) crm_settings_provisioned = models.BooleanField(default=False) # settings gen_cust_in_stripe_after_lotus = models.BooleanField(default=False) gen_cust_in_braintree_after_lotus = models.BooleanField(default=False) payment_grace_period = models.IntegerField(null=True, default=None) lotus_is_customer_source_for_salesforce = models.BooleanField(default=False) # HISTORY RELATED FIELDS history = HistoricalRecords() def __init__(self, *args, **kwargs): super(Organization, self).__init__(*args, **kwargs) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys class Meta: indexes = [ models.Index(fields=["organization_name"]), models.Index(fields=["organization_type"]), models.Index(fields=["organization_id"]), models.Index(fields=["team"]), ] def __str__(self): return self.organization_name def save(self, *args, **kwargs): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP new = self._state.adding is True # self._state.adding represents whether creating new instance or updating if self.timezone != self.__original_timezone and not new: num_updated = self.customers.filter(timezone_set=False).update( timezone=self.timezone ) if num_updated > 0: customer_ids = self.customers.filter(timezone_set=False).values_list( "id", flat=True ) customer_cache_keys = [f"tz_customer_{id}" for id in customer_ids] cache.delete_many(customer_cache_keys) if self.team is None: self.team = Team.objects.create(name=self.organization_name) if self.subscription_filter_keys is None: self.subscription_filter_keys = [] self.subscription_filter_keys = sorted( list( set(self.subscription_filter_keys).union( set(self.__original_subscription_filter_keys) ) ) ) super(Organization, self).save(*args, **kwargs) if self.subscription_filter_keys != self.__original_subscription_filter_keys: for metric in self.metrics.all(): METRIC_HANDLER_MAP[metric.metric_type].create_continuous_aggregate( metric, refresh=True ) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys if new: self.provision_currencies() if not self.default_currency: self.default_currency = PricingUnit.objects.get( organization=self, code="USD" ) self.save() if not self.webhooks_provisioned: self.provision_webhooks() def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_address(self) -> Address: if self.default_payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_organization_address(self) elif self.default_payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_organization_address(self) else: return self.address def provision_webhooks(self): if SVIX_CONNECTOR is not None and not self.webhooks_provisioned: logger.info("provisioning webhooks") svix = SVIX_CONNECTOR svix.application.create( ApplicationIn(uid=self.organization_id.hex, name=self.organization_name) ) self.webhooks_provisioned = True self.save() def provision_currencies(self): if SUPPORTED_CURRENCIES_VERSION != self.currencies_provisioned: for name, code, symbol in SUPPORTED_CURRENCIES: PricingUnit.objects.get_or_create( organization=self, code=code, name=name, symbol=symbol, custom=False ) PricingUnit.objects.filter( ~Q(code__in=[code for _, code, _ in SUPPORTED_CURRENCIES]), custom=False, organization=self, ).delete() self.currencies_provisioned = SUPPORTED_CURRENCIES_VERSION self.save() class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class WebhookTrigger(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_triggers", null=True, ) webhook_endpoint = models.ForeignKey( WebhookEndpoint, on_delete=models.CASCADE, related_name="triggers" ) trigger_name = models.CharField( choices=WEBHOOK_TRIGGER_EVENTS.choices, max_length=40 ) class Meta: indexes = [ models.Index( fields=["organization", "webhook_endpoint", "trigger_name"], name="unique_webhook_trigger", ) ] class User(AbstractUser): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="users", ) team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="users" ) email = models.EmailField(unique=True) history = HistoricalRecords() def save(self, *args, **kwargs): if not self.team and self.organization: self.team = self.organization.team super(User, self).save(*args, **kwargs) class Product(models.Model): """ This model is used to store the products that are available to be purchased. """ name = models.CharField(max_length=100, blank=False) description = models.TextField(null=True, blank=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="products" ) product_id = models.SlugField(default=product_uuid, max_length=100, unique=True) status = models.CharField(choices=PRODUCT_STATUS.choices, max_length=40) history = HistoricalRecords() class Meta: unique_together = ("organization", "product_id") def __str__(self): return f"{self.name}" class Customer(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="customers" ) customer_name = models.TextField( blank=True, help_text="The display name of the customer", null=True, ) email = models.EmailField( max_length=100, help_text="The primary email address of the customer, must be the same as the email address used to create the customer in the payment provider", null=True, ) customer_id = models.TextField( default=customer_uuid, help_text="The id provided when creating the customer, we suggest matching with your internal customer id in your backend", null=True, ) uuidv5_customer_id = models.UUIDField( help_text="The v5 UUID generated from the customer_id. This is used for efficient lookups in the database, specifically for the Events table", null=True, ) properties = models.JSONField( default=dict, null=True, help_text="Extra metadata for the customer" ) deleted = models.DateTimeField( null=True, help_text="The date the customer was deleted" ) # BILLING RELATED FIELDS default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="customers", null=True, blank=True, help_text="The currency the customer will be invoiced in", ) shipping_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="shipping_customers", null=True, blank=True, help_text="The shipping address for the customer", ) billing_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="billing_customers", null=True, blank=True, help_text="The billing address for the customer", ) # TAX RELATED FIELDS tax_providers = TaxProviderListField(default=[]) tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) # TIMEZONE FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) timezone_set = models.BooleanField(default=False) # PAYMENT PROCESSOR FIELDS payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) braintree_integration = models.ForeignKey( "BraintreeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) salesforce_integration = models.OneToOneField( "UnifiedCRMCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customer", ) # HISTORY FIELDS created = models.DateTimeField(default=now_utc) history = HistoricalRecords() objects = BaseCustomerManager() deleted_objects = DeletedCustomerManager() class Meta: constraints = [ UniqueConstraint(fields=["organization", "email"], name="unique_email"), UniqueConstraint( fields=["organization", "customer_id"], name="unique_customer_id" ), ] def __str__(self) -> str: return str(self.customer_name) + " " + str(self.customer_id) def save(self, *args, **kwargs): if not self.default_currency: try: self.default_currency = ( self.organization.default_currency or PricingUnit.objects.get( code="USD", organization=self.organization ) ) except PricingUnit.DoesNotExist: self.default_currency = None super(Customer, self).save(*args, **kwargs) def get_active_subscription_records(self): active_subscription_records = self.subscription_records.active().filter( fully_billed=False, ) return active_subscription_records def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_usage_and_revenue(self): customer_subscriptions = ( SubscriptionRecord.objects.active() .filter( customer=self, organization=self.organization, ) .prefetch_related("billing_plan__plan_components") .prefetch_related("billing_plan__plan_components__billable_metric") .select_related("billing_plan") ) subscription_usages = {"subscriptions": [], "sub_objects": []} for subscription in customer_subscriptions: sub_dict = subscription.get_usage_and_revenue() del sub_dict["components"] sub_dict["billing_plan_name"] = subscription.billing_plan.plan.plan_name subscription_usages["subscriptions"].append(sub_dict) subscription_usages["sub_objects"].append(subscription) return subscription_usages def get_active_sub_drafts_revenue(self): from metering_billing.invoice import generate_invoice total = 0 sub_records = self.get_active_subscription_records() if sub_records is not None and len(sub_records) > 0: invs = generate_invoice( sub_records, draft=True, charge_next_plan=True, ) total += sum([inv.amount for inv in invs]) for inv in invs: inv.delete() return total def get_currency_balance(self, currency): now = now_utc() balance = self.customer_balance_adjustments.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), effective_at__lte=now, amount_currency=currency, ).aggregate(balance=Sum("amount"))["balance"] or Decimal(0) return balance def get_outstanding_revenue(self): unpaid_invoice_amount_due = ( self.invoices.filter(payment_status=Invoice.PaymentStatus.UNPAID) .aggregate(unpaid_inv_amount=Sum("amount")) .get("unpaid_inv_amount") ) total_amount_due = unpaid_invoice_amount_due or 0 return total_amount_due def get_billing_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="billing") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.billing_address def get_shipping_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="shipping") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.shipping_address class CustomerBalanceAdjustment(models.Model): """ This model is used to store the customer balance adjustments. """ adjustment_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="+", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name="customer_balance_adjustments" ) amount = models.DecimalField(decimal_places=10, max_digits=20) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="adjustments", null=True, blank=True, ) description = models.TextField(null=True, blank=True) created = models.DateTimeField(default=now_utc) effective_at = models.DateTimeField(default=now_utc) expires_at = models.DateTimeField(null=True, blank=True) parent_adjustment = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="drawdowns", ) amount_paid = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0) ) amount_paid_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="paid_adjustments", null=True, blank=True, ) status = models.CharField( max_length=20, choices=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.choices, default=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) def __str__(self): return f"{self.customer.customer_name} {self.amount} {self.created}" class Meta: ordering = ["-created"] unique_together = ("customer", "created") indexes = [ models.Index( fields=["organization", "adjustment_id"] ), # for lookup for single models.Index( fields=["organization", "customer", "pricing_unit", "-expires_at"] ), # for lookup for drawdowns models.Index(fields=["status", "expires_at"]), # for lookup for expired ] def save(self, *args, **kwargs): new = self._state.adding is True if not new: orig = CustomerBalanceAdjustment.objects.get(pk=self.pk) if ( orig.amount != self.amount or orig.pricing_unit != self.pricing_unit or orig.created != self.created or orig.effective_at != self.effective_at or orig.parent_adjustment != self.parent_adjustment ): raise NotEditable( "Cannot update any fields in a balance adjustment other than status and description" ) if self.expires_at is not None and now_utc() > self.expires_at: raise NotEditable("Cannot change the expiry date to the past") if self.amount < 0: assert ( self.parent_adjustment is not None ), "If credit is negative, parent adjustment must be provided" if self.parent_adjustment: assert ( self.parent_adjustment.amount > 0 ), "Parent adjustment must be a credit adjustment" assert ( self.parent_adjustment.customer == self.customer ), "Parent adjustment must be for the same customer" assert self.amount < 0, "Child adjustment must be a debit adjustment" assert ( self.pricing_unit == self.parent_adjustment.pricing_unit ), "Child adjustment must be in the same currency as parent adjustment" assert self.parent_adjustment.get_remaining_balance() - self.amount >= 0, ( "Child adjustment must be less than or equal to the remaining balance of " "the parent adjustment" ) if not self.organization: self.organization = self.customer.organization if self.amount_paid is None or self.amount_paid == 0: self.amount_paid_currency = None if not self.pricing_unit: raise ValidationError("Pricing unit must be provided") super(CustomerBalanceAdjustment, self).save(*args, **kwargs) def get_remaining_balance(self): try: dd_aggregate = self.total_drawdowns except AttributeError: dd_aggregate = self.drawdowns.aggregate(drawdowns=Sum("amount"))[ "drawdowns" ] drawdowns = dd_aggregate or 0 return self.amount + drawdowns def zero_out(self, reason=None): if reason == "expired": fmt = self.expires_at.strftime("%Y-%m-%d %H:%M") description = f"Expiring remaining credit at {fmt} UTC" elif reason == "voided": fmt = now_utc().strftime("%Y-%m-%d %H:%M") description = f"Voiding remaining credit at {fmt} UTC" else: description = "Zeroing out remaining credit" remaining_balance = self.get_remaining_balance() if remaining_balance > 0: CustomerBalanceAdjustment.objects.create( organization=self.customer.organization, customer=self.customer, amount=-remaining_balance, pricing_unit=self.pricing_unit, parent_adjustment=self, description=description, ) self.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE self.save() def draw_down_amount(customer, amount, pricing_unit, description=""): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .annotate( cost_basis=Cast( Coalesce(F("amount_paid") / F("amount"), 0), FloatField() ) ) .order_by( F("expires_at").asc(nulls_last=True), F("cost_basis").desc(nulls_last=True), ) .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") + F("drawn_down_amount")) ) am = amount for adj in adjs: remaining_balance = adj.remaining_balance if remaining_balance <= 0: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() continue drawdown_amount = min(am, remaining_balance) CustomerBalanceAdjustment.objects.create( organization=customer.organization, customer=customer, amount=-drawdown_amount, pricing_unit=adj.pricing_unit, parent_adjustment=adj, description=description, ) if drawdown_amount == remaining_balance: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() am -= drawdown_amount if am == 0: break return am def get_pricing_unit_balance(customer, pricing_unit): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .prefetch_related("drawdowns") .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") - F("drawn_down_amount")) .aggregate(total_balance=Sum("remaining_balance"))["total_balance"] ) total_balance = adjs or 0 return total_balance class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=models.SET_NULL, related_name="+", null=True, blank=True ) cust_id = models.TextField(blank=True) uuidv5_customer_id = models.UUIDField() event_name = models.TextField( help_text="String name of the event, corresponds to definition in metrics", ) uuidv5_event_name = models.UUIDField() time_created = models.DateTimeField( help_text="The time that the event occured, represented as a datetime in RFC3339 in the UTC timezome." ) properties = models.JSONField( default=dict, blank=True, help_text="Extra metadata on the event that can be filtered and queried on in the metrics. All key value pairs should have string keys and values can be either strings or numbers. Place subscription filters in this object to specify which subscription the event should be tracked under", ) idempotency_id = models.TextField( default=event_uuid, help_text="A unique identifier for the specific event being passed in. Passing in a unique id allows Lotus to make sure no double counting occurs. We recommend using a UUID4. You can use the same idempotency_id again after 45 days.", primary_key=True, ) uuidv5_idempotency_id = models.UUIDField() inserted_at = models.DateTimeField(default=now_utc) objects = EventManager() class Meta: managed = False db_table = "metering_billing_usageevent" def __str__(self): return ( str(self.event_name)[:6] + "-" + str(self.cust_id)[:8] + "-" + str(self.time_created)[:10] + "-" + str(self.idempotency_id)[:6] ) class NumericFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="numeric_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField(max_length=10, choices=NUMERIC_FILTER_OPERATORS.choices) comparison_value = models.FloatField() class CategoricalFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="categorical_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField( max_length=10, choices=CATEGORICAL_FILTER_OPERATORS.choices ) comparison_value = models.JSONField() def __str__(self): return f"{self.property_name} {self.operator} {self.comparison_value}" class Metric(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="metrics", ) event_name = models.TextField( help_text="Name of the event that this metric is tracking." ) metric_type = models.CharField( max_length=20, choices=METRIC_TYPE.choices, default=METRIC_TYPE.COUNTER, help_text="The type of metric that this is. Please refer to our documentation for an explanation of the different types.", ) properties = models.JSONField(default=dict, blank=True, null=True) billable_metric_name = models.TextField(blank=True, null=True) metric_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) event_type = models.CharField( max_length=20, choices=EVENT_TYPE.choices, blank=True, null=True, help_text="Used only for metrics of type 'gauge'. Please refer to our documentation for an explanation of the different types.", ) # metric type specific usage_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.COUNT, help_text="The type of aggregation that should be used for this metric. Please refer to our documentation for an explanation of the different types.", ) billable_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.SUM, blank=True, null=True, ) property_name = models.TextField( blank=True, null=True, help_text="The name of the property of the event that should be used for this metric. Doesn't apply if the metric is of type 'counter' with an aggregation of count.", ) granularity = models.CharField( choices=METRIC_GRANULARITY.choices, default=METRIC_GRANULARITY.TOTAL, max_length=10, blank=True, null=True, help_text="The granularity of the metric. Only applies to metrics of type 'gauge' or 'rate'.", ) proration = models.CharField( choices=METRIC_GRANULARITY.choices, default=None, max_length=10, blank=True, null=True, help_text="The proration of the metric. Only applies to metrics of type 'gauge'.", ) is_cost_metric = models.BooleanField( default=False, help_text="Whether or not this metric is a cost metric (used to track costs to your business).", ) custom_sql = models.TextField( blank=True, null=True, help_text="A custom SQL query that can be used to define the metric. Please refer to our documentation for more information.", ) # filters numeric_filters = models.ManyToManyField(NumericFilter, blank=True) categorical_filters = models.ManyToManyField(CategoricalFilter, blank=True) # status status = models.CharField( choices=METRIC_STATUS.choices, max_length=40, default=METRIC_STATUS.ACTIVE ) mat_views_provisioned = models.BooleanField(default=False) # records history = HistoricalRecords() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "billable_metric_name"], condition=Q(status=METRIC_STATUS.ACTIVE), name="unique_org_billable_metric_name", ), ] + [ models.UniqueConstraint( fields=sorted( list( { "organization", "billable_metric_name", # nullable "event_name", "metric_type", "usage_aggregation_type", "billable_aggregation_type", # nullable "property_name", # nullable "granularity", # nullable "is_cost_metric", "custom_sql", # nullable } - {x for x in nullables} ) ), condition=Q( **{f"{nullable}__in": [None, ""] for nullable in sorted(nullables)} ) & Q(status=METRIC_STATUS.ACTIVE), name="uq_metric_w_null__" + "_".join( [ "_".join([x[:2] for x in nullable.split("_")]) for nullable in sorted(nullables) ] ), ) for nullables in itertools.chain( *map( lambda x: itertools.combinations( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], x, ), range( 0, len( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], ) + 1, ), ) ) ] indexes = [ models.Index(fields=["organization", "status"]), models.Index(fields=["organization", "is_cost_metric"]), models.Index(fields=["organization", "metric_id"]), ] def __str__(self): return self.billable_metric_name or "" def save(self, *args, **kwargs): super().save(*args, **kwargs) def delete_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.archive_metric(self) self.mat_views_provisioned = False self.save() def get_aggregation_type(self): return self.aggregation_type def get_billing_record_total_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_total_billable_usage(self, billing_record) return usage def get_billing_record_daily_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_daily_billable_usage(self, billing_record) return usage def get_billing_record_current_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_current_usage(self, billing_record) return usage def get_daily_total_usage( self, start_date: datetime.date, end_date: datetime.date, customer: Optional[Customer] = None, top_n: Optional[int] = None, ) -> dict[Union[Customer, Literal["Other"]], dict[datetime.date, Decimal]]: from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_daily_total_usage( self, start_date, end_date, customer, top_n ) return usage def refresh_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self, refresh=True) self.mat_views_provisioned = True self.save() def provision_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self) self.mat_views_provisioned = True self.save() class PriceTier(models.Model): class PriceTierType(models.IntegerChoices): FLAT = (1, _("flat")) PER_UNIT = (2, _("per_unit")) FREE = (3, _("free")) class BatchRoundingType(models.IntegerChoices): ROUND_UP = (1, _("round_up")) ROUND_DOWN = (2, _("round_down")) ROUND_NEAREST = (3, _("round_nearest")) NO_ROUNDING = (4, _("no_rounding")) organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="price_tiers", null=True ) plan_component = models.ForeignKey( "PlanComponent", on_delete=models.CASCADE, related_name="tiers", null=True, blank=True, ) type = models.PositiveSmallIntegerField(choices=PriceTierType.choices) range_start = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) range_end = models.DecimalField( max_digits=20, decimal_places=10, null=True, blank=True, validators=[MinValueValidator(0)], ) cost_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, validators=[MinValueValidator(0)], ) metric_units_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, default=1.0, validators=[MinValueValidator(0)], ) batch_rounding_type = models.PositiveSmallIntegerField( choices=BatchRoundingType.choices, blank=True, null=True, ) class Meta: constraints = [ models.CheckConstraint( check=Q(range_end__gte=F("range_start")) | Q(range_end__isnull=True), name="price_tier_type_valid", ), models.UniqueConstraint( fields=["organization", "plan_component", "range_start"], name="unique_price_tier", ), ] def save(self, *args, **kwargs): new = self._state.adding is True ranges = [ (tier["range_start"], tier["range_end"]) for tier in self.plan_component.tiers.order_by("range_start").values( "range_start", "range_end" ) ] if new: ranges = sorted( ranges + [(self.range_start, self.range_end)], key=lambda x: x[0] ) for i, (start, end) in enumerate(ranges): if i == 0: if start != 0: raise ValidationError("First tier must start at 0") else: diff = start - ranges[i - 1][1] if diff != Decimal(0) and diff != Decimal(1): raise ValidationError( "Tier ranges must be continuous or separated by 1" ) if i != len(ranges) - 1: if end is None: raise ValidationError("Only last tier can be open ended") super().save(*args, **kwargs) def calculate_revenue( self, usage: float, prev_tier_end=False, bulk_pricing_enabled=False ): # if division_factor is None: # division_factor = len(usage_dict) revenue = 0 discontinuous_range = ( prev_tier_end != self.range_start and prev_tier_end is not None ) # for usage in usage_dict.values(): usage = convert_to_decimal(usage) if ( bulk_pricing_enabled and self.range_end is not None and self.range_end <= usage ): return revenue if bulk_pricing_enabled: usage_in_range = self.range_start <= usage else: usage_in_range = ( self.range_start <= usage if discontinuous_range else self.range_start < usage or self.range_start == 0 ) if usage_in_range: if self.type == PriceTier.PriceTierType.FLAT: revenue += self.cost_per_batch return revenue if self.type == PriceTier.PriceTierType.PER_UNIT: if bulk_pricing_enabled: billable_units = usage elif self.range_end is not None: billable_units = min( usage - self.range_start, self.range_end - self.range_start ) else: billable_units = usage - self.range_start if discontinuous_range: billable_units += 1 billable_batches = billable_units / self.metric_units_per_batch if self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_UP: billable_batches = math.ceil(billable_batches) elif self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_DOWN: billable_batches = math.floor(billable_batches) elif ( self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_NEAREST ): billable_batches = round(billable_batches) revenue += self.cost_per_batch * billable_batches return revenue class PlanComponent(models.Model): class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="plan_components", null=True, ) usage_component_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) billable_metric = models.ForeignKey( Metric, on_delete=models.CASCADE, related_name="+", null=True, blank=True, ) plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="plan_components", null=True, blank=True, ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="components", null=True, blank=True, ) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) fixed_charge = models.OneToOneField( ComponentFixedCharge, on_delete=models.SET_NULL, related_name="component", null=True, ) bulk_pricing_enabled = models.BooleanField(default=False) def __str__(self): return str(self.billable_metric) def save(self, *args, **kwargs): if self.pricing_unit is None and self.plan_version is not None: self.pricing_unit = self.plan_version.currency super().save(*args, **kwargs) def convert_length_label_to_value(label): label_map = { PlanComponent.IntervalLengthType.DAY.label: PlanComponent.IntervalLengthType.DAY, PlanComponent.IntervalLengthType.WEEK.label: PlanComponent.IntervalLengthType.WEEK, PlanComponent.IntervalLengthType.MONTH.label: PlanComponent.IntervalLengthType.MONTH, PlanComponent.IntervalLengthType.YEAR.label: PlanComponent.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_component_invoicing_dates( self, subscription_record, override_start_date=None ): # FOR PLAN COMPONENTS start_date = override_start_date or subscription_record.start_date end_date = subscription_record.end_date if self.invoicing_interval_unit is None: return [end_date] unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", } interval_delta = relativedelta( **{ unit_map[self.invoicing_interval_unit]: self.invoicing_interval_count or 1 } ) invoicing_dates = [] invoicing_date = start_date while invoicing_date < end_date: invoicing_date += interval_delta append_date = min(invoicing_date, end_date) invoicing_dates.append(append_date) return invoicing_dates def get_component_reset_dates(self, subscription_record, override_start_date=None): # FOR PLAN COMPONENTS sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date if override_start_date: range_start_date = override_start_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): start = reset_dates[i] if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges def calculate_total_revenue( self, billing_record, prepaid_units=None ) -> UsageRevenueSummary: assert isinstance( billing_record, BillingRecord ), "billing_record must be a BillingRecord" billable_metric = self.billable_metric usage_qty = billable_metric.get_billing_record_total_billable_usage( billing_record ) revenue = self.tier_rating_function(usage_qty) latest_component_charge = self.component_charge_records.order_by( "-start_date" ).first() if latest_component_charge is not None: revenue_from_prepaid_units = self.tier_rating_function(prepaid_units) revenue = max(revenue - revenue_from_prepaid_units, 0) return {"revenue": revenue, "usage_qty": usage_qty} def tier_rating_function(self, usage_qty): revenue = 0 tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: # this is for determining whether this is a continuous or discontinuous range prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( usage_qty, prev_tier_end=prev_tier_end, bulk_pricing_enabled=self.bulk_pricing_enabled, ) else: tier_revenue = tier.calculate_revenue( usage_qty, bulk_pricing_enabled=self.bulk_pricing_enabled ) revenue += tier_revenue revenue = convert_to_decimal(revenue) return revenue def calculate_revenue_per_day( self, billing_record ) -> dict[datetime.datetime, UsageRevenueSummary]: assert isinstance(billing_record, BillingRecord) billable_metric = self.billable_metric usage_per_day = billable_metric.get_billing_record_daily_billable_usage( billing_record ) results = {} for period in dates_bwn_two_dts( billing_record.start_date, billing_record.end_date ): period = convert_to_date(period) results[period] = {"revenue": Decimal(0), "usage_qty": Decimal(0)} running_total_revenue = Decimal(0) running_total_usage = Decimal(0) for date, usage_qty in usage_per_day.items(): date = convert_to_date(date) usage_qty = convert_to_decimal(usage_qty) running_total_usage += usage_qty revenue = Decimal(0) tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( running_total_usage, prev_tier_end=prev_tier_end ) else: tier_revenue = tier.calculate_revenue(running_total_usage) revenue += convert_to_decimal(tier_revenue) date_revenue = revenue - running_total_revenue running_total_revenue += date_revenue if date in results: results[date]["revenue"] += date_revenue results[date]["usage_qty"] += usage_qty return results class Feature(models.Model): feature_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="features" ) feature_name = models.CharField(max_length=50, blank=False) feature_description = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "feature_name"], name="unique_feature" ) ] def __str__(self): return str(self.feature_name) class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status class InvoiceLineItem(models.Model): invoice_line_item_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoice_line_items", null=True, ) name = models.CharField(max_length=100) start_date = models.DateTimeField(max_length=100, default=now_utc) end_date = models.DateTimeField(max_length=100, default=now_utc) quantity = models.DecimalField( decimal_places=10, max_digits=20, null=True, blank=True, validators=[MinValueValidator(0)], ) base = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Base price of the line item. This is the price before any adjustments are applied.", ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Amount of the line item. This is the price after any adjustments are applied.", ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="line_items", null=True, blank=True, ) billing_type = models.CharField( max_length=40, choices=INVOICE_CHARGE_TIMING_TYPE.choices, blank=True, null=True ) chargeable_item_type = models.CharField( max_length=40, choices=CHARGEABLE_ITEM_TYPE.choices, blank=True, null=True ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, null=True, related_name="line_items" ) associated_plan_version = models.ForeignKey( "PlanVersion", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_subscription_record = models.ForeignKey( "SubscriptionRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_billing_record = models.ForeignKey( "BillingRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) metadata = models.JSONField(default=dict, blank=True, null=True) def __str__(self): return self.name + " " + str(self.invoice.invoice_number) + f"[{self.base}]" def save(self, *args, **kwargs): self.amount = self.base + sum( [adjustment.amount for adjustment in self.adjustments.all()] ) super().save(*args, **kwargs) class APIToken(AbstractAPIKey): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys" ) class Meta(AbstractAPIKey.Meta): verbose_name = "API Token" verbose_name_plural = "API Tokens" def __str__(self): return str(self.name) + " " + str(self.organization.organization_name) class TeamInviteToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_invite_token" ) team = models.ForeignKey( Team, on_delete=models.CASCADE, related_name="team_invite_token" ) email = models.EmailField() token = models.SlugField(max_length=250, default=uuid.uuid4) expire_at = models.DateTimeField(default=now_plus_day, null=False, blank=False) def __str__(self): return str(self.email) + " - " + str(self.team) class RecurringCharge(models.Model): class ChargeTimingType(models.IntegerChoices): IN_ADVANCE = (1, "in_advance") IN_ARREARS = (2, "in_arrears") class ChargeBehaviorType(models.IntegerChoices): PRORATE = (1, "prorate") CHARGE_FULL = (2, "full") class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") recurring_charge_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="recurring_charges", ) name = models.TextField() plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="recurring_charges", ) charge_timing = models.PositiveSmallIntegerField( choices=ChargeTimingType.choices, default=ChargeTimingType.IN_ADVANCE ) charge_behavior = models.PositiveSmallIntegerField( choices=ChargeBehaviorType.choices, default=ChargeBehaviorType.PRORATE ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="recurring_charges", null=True, ) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) def __str__(self): return self.name + " [" + str(self.plan_version) + "]" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "plan_version", "name"], name="unique_recurring_charge_name_in_plan_version", ) ] def convert_length_label_to_value(label): label_map = { RecurringCharge.IntervalLengthType.DAY.label: RecurringCharge.IntervalLengthType.DAY, RecurringCharge.IntervalLengthType.WEEK.label: RecurringCharge.IntervalLengthType.WEEK, RecurringCharge.IntervalLengthType.MONTH.label: RecurringCharge.IntervalLengthType.MONTH, RecurringCharge.IntervalLengthType.YEAR.label: RecurringCharge.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_recurring_charge_invoicing_dates( self, subscription_record, append_range_start=False ): # FOR RECURRIG CHARGES # first we get the actual star tdate and end date of this subscription. However, if this is an addon, we need to calculate the periods w.r.t the parent subscription sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date invoicing_interval_unit = self.invoicing_interval_unit invoicing_interval_count = self.invoicing_interval_count # if we don't have a sub-plan length invoicing interval, use the plan length if not invoicing_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. invoicing_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if invoicing_interval_unit == PLAN_DURATION.QUARTERLY: invoicing_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[invoicing_interval_unit]: invoicing_interval_count or 1} ) invoicing_dates = [] invoicing_date = range_start_date # now generate invoicing dates while invoicing_date < range_end_date: invoicing_date += interval_delta append_date = min(invoicing_date, range_end_date) invoicing_dates.append(append_date) # purge the ones that don't match up with the real duration, and add the start + end dates invoicing_dates = { x for x in invoicing_dates if x >= sr_start_date and x <= sr_end_date } if append_range_start: invoicing_dates = invoicing_dates | {sr_start_date} invoicing_dates = invoicing_dates | {sr_end_date} invoicing_dates = sorted(list(invoicing_dates)) return invoicing_dates def get_recurring_charge_reset_dates(self, subscription_record): # FOR RECURRIG CHARGES sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): if sr_start_date > reset_dates[i]: continue start = max(reset_dates[i], sr_start_date) if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges class PlanVersion(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plan_versions", ) version = models.PositiveSmallIntegerField(default=1) version_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) localized_name = models.TextField(null=True, blank=True, default=None) plan = models.ForeignKey("Plan", on_delete=models.CASCADE, related_name="versions") created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plan_versions", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) # BILLING SCHEDULE day_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(31)], null=True, blank=True, ) month_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True, ) replace_with = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) transition_to = models.ForeignKey( "Plan", on_delete=models.SET_NULL, null=True, blank=True, related_name="transition_from", ) addon_spec = models.OneToOneField( "AddOnSpecification", on_delete=models.SET_NULL, related_name="plan_version", null=True, blank=True, ) active_from = models.DateTimeField(null=True, default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # PRICING features = models.ManyToManyField(Feature, blank=True) price_adjustment = models.ForeignKey( "PriceAdjustment", on_delete=models.SET_NULL, null=True, blank=True ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="versions", null=True, blank=True, ) # MISC is_custom = models.BooleanField(default=False) target_customers = models.ManyToManyField(Customer, related_name="plan_versions") objects = PlanVersionManager() plan_versions = RegularPlanVersionManager() addon_versions = AddOnPlanVersionManager() deleted_objects = DeletedPlanVersionManager() class Meta: constraints = [ models.UniqueConstraint( fields=["plan", "version", "currency"], name="unique_plan_version_per_currency", condition=Q(is_custom=False), ), ] indexes = [ models.Index(fields=["organization", "plan"]), models.Index(fields=["organization", "version_id"]), ] def __str__(self) -> str: if self.localized_name is not None: return self.localized_name return str(self.plan) def num_active_subs(self): cnt = self.subscription_records.active().count() return cnt def is_active(self, time=None): if time is None: time = now_utc() return self.active_from <= time and ( self.active_to is None or self.active_to > time ) def get_status(self) -> PLAN_VERSION_STATUS: now = now_utc() if self.deleted is not None: return PLAN_VERSION_STATUS.DELETED if not self.active_from: return PLAN_VERSION_STATUS.INACTIVE if self.active_from <= now: if self.active_to is None or self.active_to > now: return PLAN_VERSION_STATUS.ACTIVE else: n_active_subs = self.num_active_subs() if self.replace_with is None: if n_active_subs > 0: # SHOULD NEVER HAPPEN. EXPIRED PLAN, ACTIVE SUBS, NO REPLACEMENT return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE elif self.replace_with == self: if n_active_subs > 0: return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE else: if n_active_subs > 0: return PLAN_VERSION_STATUS.RETIRING else: return PLAN_VERSION_STATUS.INACTIVE else: return PLAN_VERSION_STATUS.INACTIVE class PriceAdjustment(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="price_adjustments" ) price_adjustment_name = models.CharField(max_length=100) price_adjustment_description = models.TextField(blank=True, null=True) price_adjustment_type = models.CharField( max_length=40, choices=PRICE_ADJUSTMENT_TYPE.choices ) price_adjustment_amount = models.DecimalField( max_digits=20, decimal_places=10, ) def __str__(self): if self.price_adjustment_name != "": return str(self.price_adjustment_name) else: return ( str(round(self.price_adjustment_amount, 2)) + " " + str(self.price_adjustment_type) ) def apply(self, amount): if self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PERCENTAGE: return amount * (1 + self.price_adjustment_amount / 100) elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.FIXED: return amount + self.price_adjustment_amount elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PRICE_OVERRIDE: return self.price_adjustment_amount class Plan(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plans" ) plan_name = models.TextField(help_text="Name of the plan") plan_description = models.TextField( help_text="Description of the plan", blank=True, null=True ) plan_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plans", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) is_addon = models.BooleanField(default=False) # BILLING taxjar_code = models.TextField(max_length=30, null=True, blank=True) plan_duration = models.CharField( choices=PLAN_DURATION.choices, max_length=40, help_text="Duration of the plan", null=True, ) active_from = models.DateTimeField(default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # MISC tags = models.ManyToManyField("Tag", blank=True, related_name="plans") objects = BasePlanManager() plans = RegularPlanManager() addons = AddOnPlanManager() deleted_objects = DeletedPlanManager() history = HistoricalRecords() # USELESS RN parent_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product_plans", null=True, blank=True, help_text="The product that this plan belongs to", ) class Meta: indexes = [ models.Index(fields=["organization", "plan_id"]), ] def __str__(self): return self.plan_name def add_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) def remove_tags(self, tags): existing_tags = self.tags.all() tags_lower = [tag["tag_name"].lower() for tag in tags] for existing_tag in existing_tags: if existing_tag.tag_name.lower() in tags_lower: self.tags.remove(existing_tag) def set_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] new_tag_names_lower = [tag["tag_name"].lower() for tag in tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) for existing_tag in existing_tags: if existing_tag.tag_name.lower() not in new_tag_names_lower: self.tags.remove(existing_tag) def active_subs_by_version(self): versions = self.versions.all().prefetch_related("subscription_records") now = now_utc() versions_count = versions.annotate( active_subscriptions=Count( "subscription_record", filter=Q( subscription_record__start_date__lte=now, subscription_record__end_date__gte=now, ), output_field=models.IntegerField(), ) ) return versions_count def get_version_for_customer(self, customer) -> Optional[PlanVersion]: versions = self.versions.active().prefetch_related( "subscription_records", "target_customers" ) # rules are as follows: # 1. if there is only one version, return it # 2. custom plans, preferring the customer's preferred currency # 3. filter down to the customer's preferred currency # 4. filter down to the organization's preferred currency if versions.count() == 0: return None elif versions.count() == 1: return versions.first() else: customer_target_plans = customer.plan_versions.filter(plan=self) customer_target_plan_in_customer_currency = customer_target_plans.filter( currency=customer.default_currency ) customer_target_plan_in_org_currency = customer_target_plans.filter( currency=customer.organization.default_currency ) if customer_target_plans.count() == 1: return customer_target_plans.first() elif customer_target_plan_in_customer_currency.count() == 1: return customer_target_plan_in_customer_currency.first() elif customer_target_plan_in_customer_currency.count() > 1: return None # DO NOT randomly choose a plan if multiple match elif customer_target_plan_in_org_currency.count() == 1: return customer_target_plan_in_org_currency.first() elif customer_target_plan_in_org_currency.count() > 1: return None # if we get here that means there are no customer specific plans versions_in_customer_currency = versions.filter( currency=customer.default_currency ) if versions_in_customer_currency.count() == 1: return versions_in_customer_currency.first() elif versions_in_customer_currency.count() > 1: return None versions_in_org_currency = versions.filter( currency=customer.organization.default_currency ) if versions_in_org_currency.count() == 1: return versions_in_org_currency.first() elif versions_in_org_currency.count() > 1: return None return None class ExternalPlanLink(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="external_plan_links", ) plan = models.ForeignKey( Plan, on_delete=models.CASCADE, related_name="external_links" ) source = models.CharField(choices=PAYMENT_PROCESSORS.choices, max_length=40) external_plan_id = models.CharField(max_length=100) def __str__(self): return f"{self.plan} - {self.source} - {self.external_plan_id}" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "source", "external_plan_id"], name="unique_external_plan_link", ) ] class SubscriptionRecord(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="subscription_records", ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=False, related_name="subscription_records", help_text="The customer object associated with this subscription.", ) billing_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, null=True, related_name="subscription_records", related_query_name="subscription_record", help_text="The plan associated with this subscription.", ) usage_start_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) end_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) auto_renew = models.BooleanField( default=True, help_text="Whether the subscription automatically renews. Defaults to true.", ) is_new = models.BooleanField( default=True, help_text="Whether this subscription came from a renewal or from a first-time. Defaults to true on creation.", ) subscription_record_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) subscription_filters = ArrayField( ArrayField( models.TextField(blank=False, null=False), size=2, ), default=list, ) invoice_usage_charges = models.BooleanField(default=True) flat_fee_behavior = models.CharField( choices=FLAT_FEE_BEHAVIOR.choices, max_length=20, null=True, default=None ) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.CASCADE, related_name="addon_subscription_records", help_text="The parent subscription record.", ) quantity = models.PositiveIntegerField(default=1) metadata = models.JSONField(default=dict, blank=True) stripe_subscription_id = models.TextField(null=True, blank=True, default=None) # managers etc objects = SubscriptionRecordManager() addon_objects = AddOnSubscriptionRecordManager() base_objects = BaseSubscriptionRecordManager() stripe_objects = StripeSubscriptionRecordManager() history = HistoricalRecords() class Meta: constraints = [ CheckConstraint( check=Q(start_date__lte=F("end_date")), name="end_date_gte_start_date" ), CheckConstraint(check=Q(quantity__gt=0), name="quantity_gt_0"), # check if stripe subscription id is null, then billing plan is not null, and vice versa CheckConstraint( check=( Q(stripe_subscription_id__isnull=False) & Q(billing_plan__isnull=True) ) | ( Q(stripe_subscription_id__isnull=True) & Q(billing_plan__isnull=False) ), name="stripe_subscription_id_xor_billing_plan", ), ] def __str__(self): addon = "[ADDON] " if self.billing_plan.addon_spec else "" if self.stripe_subscription_id: plan_name = "Stripe Subscription {}".format(self.stripe_subscription_id) else: plan_name = self.billing_plan.plan.plan_name return f"{addon}{self.customer.customer_name} {plan_name} : {self.start_date.date()} to {self.end_date.date()}" def create_subscription_record( start_date, end_date, billing_plan, customer, organization, subscription_filters=None, is_new=True, quantity=1, component_fixed_charges_initial_units=None, do_generate_invoice=True, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } assert ( billing_plan.addon_spec is None ), "Cannot create a base subscription record with an addon plan" sr = SubscriptionRecord.objects.create( start_date=start_date, end_date=end_date, billing_plan=billing_plan, customer=customer, organization=organization, subscription_filters=subscription_filters, is_new=is_new, quantity=quantity, ) for component in sr.billing_plan.plan_components.all(): metric = component.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(component, **kwargs) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) if do_generate_invoice: generate_invoice(sr) return sr def create_addon_subscription_record( parent_subscription_record, addon_billing_plan, quantity=1, ): from metering_billing.invoice import generate_invoice now = now_utc() assert ( addon_billing_plan.addon_spec is not None ), "Cannot create an addon subscription record with a base plan" sr = SubscriptionRecord.objects.create( parent=parent_subscription_record, start_date=now, end_date=parent_subscription_record.end_date, billing_plan=addon_billing_plan, customer=parent_subscription_record.customer, organization=parent_subscription_record.organization, subscription_filters=parent_subscription_record.subscription_filters, is_new=True, quantity=quantity, auto_renew=addon_billing_plan.addon_spec.billing_frequency == AddOnSpecification.BillingFrequency.RECURRING, ) for component in sr.billing_plan.plan_components.all(): sr._create_component_billing_records(component) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) generate_invoice(sr) return sr def _create_component_billing_records( self, component, override_start_date=None, initial_units=None, ignore_prepaid=False, fail_on_no_prepaid=True, ): prepaid_charge = component.fixed_charge invoicing_dates = component.get_component_invoicing_dates( self, override_start_date ) reset_ranges = component.get_component_reset_dates(self, override_start_date) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, component=component, start_date=start_date, end_date=end_date, invoicing_dates=br_invoicing_dates, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) new_invoicing_dates = set(br_invoicing_dates) if prepaid_charge and not ignore_prepaid: units = initial_units or prepaid_charge.units if units is None and fail_on_no_prepaid: raise PrepaymentMissingUnits( "No units specified for prepayment. This is usually an input error but may possibly be caused by inconsistent state in the backend." ) if units: ComponentChargeRecord.objects.create( organization=self.organization, billing_record=br, component_charge=prepaid_charge, component=component, start_date=start_date, end_date=end_date, units=units, ) new_invoicing_dates |= {start_date} new_invoicing_dates = sorted(list(new_invoicing_dates)) if new_invoicing_dates != br_invoicing_dates: br.invoicing_dates = new_invoicing_dates br.next_invoicing_date = new_invoicing_dates[0] br.save() brs.append(br) return brs def _create_recurring_charge_billing_records(self, recurring_charge): # first thign we want to see is if we need to charge "in advance" at all, that will # affect the way we calculate the reset ranges and invociing dates append_range_start = False if ( recurring_charge.charge_timing == RecurringCharge.ChargeTimingType.IN_ADVANCE ): addon_spec = recurring_charge.plan_version.addon_spec if ( addon_spec and addon_spec.flat_fee_invoicing_behavior_on_attach == AddOnSpecification.FlatFeeInvoicingBehaviorOnAttach.INVOICE_ON_SUBSCRIPTION_END ): # this is the ONLY case where its in advance and we don't want to append the range start. in this case they explicitly do not want to charge the flat fee on attach append_range_start = False else: append_range_start = True invoicing_dates = recurring_charge.get_recurring_charge_invoicing_dates( self, append_range_start ) reset_ranges = recurring_charge.get_recurring_charge_reset_dates(self) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, recurring_charge=recurring_charge, invoicing_dates=br_invoicing_dates, start_date=start_date, end_date=end_date, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) brs.append(br) return brs def save(self, *args, **kwargs): if self.subscription_filters is None: self.subscription_filters = [] now = now_utc() timezone = self.customer.timezone if not self.end_date: day_anchor, month_anchor = ( self.billing_plan.day_anchor, self.billing_plan.month_anchor, ) self.end_date = calculate_end_date( self.billing_plan.plan.plan_duration, self.start_date, timezone, day_anchor=day_anchor, month_anchor=month_anchor, ) new = self._state.adding is True if new: new_filters = set(tuple(x) for x in self.subscription_filters) overlapping_subscriptions = SubscriptionRecord.objects.filter( Q(start_date__range=(self.start_date, self.end_date)) | Q(end_date__range=(self.start_date, self.end_date)), organization=self.organization, customer=self.customer, billing_plan=self.billing_plan, ) for subscription in overlapping_subscriptions: old_filters = set(tuple(x) for x in subscription.subscription_filters) if old_filters.issubset(new_filters) or new_filters.issubset( old_filters ): raise OverlappingPlans( f"Overlapping subscriptions with the same filters are not allowed. \n Plan: {self.billing_plan} \n Customer: {self.customer}. \n New dates: ({self.start_date, self.end_date}) \n New subscription_filters: {new_filters} \n Old dates: ({self.start_date, self.end_date}) \n Old subscription_filters: {list(old_filters)}" ) super(SubscriptionRecord, self).save(*args, **kwargs) if new: alerts = UsageAlert.objects.filter( organization=self.organization, plan_version=self.billing_plan ) now = now_utc() for alert in alerts: UsageAlertResult.objects.create( organization=self.organization, alert=alert, subscription_record=self, last_run_value=0, last_run_timestamp=now, ) def get_filters_dictionary(self): filters_dict = {f[0]: f[1] for f in self.subscription_filters} return filters_dict def amt_already_invoiced(self): billed_invoices = self.line_items.filter( ~Q(invoice__payment_status=Invoice.PaymentStatus.VOIDED) & ~Q(invoice__payment_status=Invoice.PaymentStatus.DRAFT), base__isnull=False, ).aggregate(tot=Sum("base"))["tot"] return billed_invoices or 0 def get_usage_and_revenue(self): sub_dict = {"components": []} # set up the billing plan for this subscription plan = self.billing_plan # set up other details of the subscription self.start_date self.end_date # extract other objects that we need when calculating usage self.customer plan_components_qs = plan.plan_components.all() # For each component of the plan, calculate usage/revenue for plan_component in plan_components_qs: plan_component_summary = plan_component.calculate_total_revenue(self) sub_dict["components"].append((plan_component.pk, plan_component_summary)) sub_dict["usage_amount_due"] = Decimal(0) for component_pk, component_dict in sub_dict["components"]: sub_dict["usage_amount_due"] += component_dict["revenue"] sub_dict["flat_amount_due"] = sum( x.amount for x in plan.recurring_charges.all() ) sub_dict["total_amount_due"] = ( sub_dict["flat_amount_due"] + sub_dict["usage_amount_due"] ) return sub_dict def cancel_subscription( self, bill_usage=True, flat_fee_behavior=FLAT_FEE_BEHAVIOR.CHARGE_FULL, invoice_now=True, ): from metering_billing.invoice import generate_invoice now = now_utc() if self.end_date <= now: logger.info("Subscription already ended.") raise SubscriptionAlreadyEnded self.flat_fee_behavior = flat_fee_behavior self.invoice_usage_charges = bill_usage self.auto_renew = False self.end_date = now self.save() for billing_record in self.billing_records.all(): billing_record.cancel_billing_record(now) addon_srs = [] for addon_sr in self.addon_subscription_records.filter(end_date__gt=now): addon_sr.cancel_subscription( bill_usage=bill_usage, flat_fee_behavior=flat_fee_behavior, invoice_now=False, ) addon_srs.append(addon_sr) srs = [self] + addon_srs if invoice_now: generate_invoice(srs) def turn_off_auto_renew(self): self.auto_renew = False self.save() def _billing_record_cancel_protocol(billing_record, cancel_date, invoice_now=True): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass else: # this means it's currently active billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now ) def _check_should_transfer_cancel_if_not( billing_record, cancel_date, invoice_now=True ): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() return False elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass return False return True def switch_plan( self, new_version, transfer_usage=True, invoice_now=True, component_fixed_charges_initial_units=None, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } # when switching a plan, there's a few things we need to take into account: # 1. flat fees dont transfer. Just end them. # 2. what does it mean for usage to transfer? Does it just mean the billing records for the old plan are cancelled and new ones are created for the new plan with a start date the same as previously? In the case we used to charge for x but no longer do, then perhaps in that case we do charge? If we weren;t doing the whole reset frequency thing anymore it would be awesome because we could just switch which plan component it points at and have the already billed for be a part of that. now = now_utc() sr = SubscriptionRecord.objects.create( organization=self.organization, customer=self.customer, billing_plan=new_version, start_date=now + relativedelta(microseconds=1), end_date=self.end_date, auto_renew=self.auto_renew, ) # current recurring_charge billing records must be canceled + billed for billing_record in self.billing_records.filter( recurring_charge__isnull=False, fully_billed=False ): # this is common enough that we made a method for it SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) # and now we generate the new recurring_charge billing records for recurring_charge in new_version.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) # same for component based billing records # so we're going to have to create a new billing record for each component, except if the metric coincides in the old plan and the new plan, then if transfer usage is true we have to do some wizardry to accomplish this # first a set of components we'll create from scratch... if we transfer usage from anywhere we'll remove it from this set pcs_to_create_charges_for = set(new_version.plan_components.all()) # dict of metrics for convenience new_version_metrics_map = { x.billable_metric: x for x in pcs_to_create_charges_for } for billing_record in self.billing_records.filter( component__isnull=False, fully_billed=False ): component = billing_record.component # if not transferring usage, simple, just cancel the billing record same as above if not transfer_usage: SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) else: metric = component.billable_metric if metric in new_version_metrics_map: # if the metric is in the new plan, we perform the surgery to switch the billing record to the new plan. Don't create from scratch. transfer = SubscriptionRecord._check_should_transfer_cancel_if_not( billing_record, now, invoice_now=invoice_now ) if transfer: new_component = new_version_metrics_map[metric] pcs_to_create_charges_for.remove(new_component) new_billing_records = sr._create_component_billing_records( new_component, override_start_date=billing_record.start_date, ignore_prepaid=True, ) override_billing_record = new_billing_records[0] # heres the surgery... open to improvements... this allows us to keep # info about what's been paid already though which is nice billing_record.subscription = sr billing_record.billing_plan = new_version billing_record.component = override_billing_record.component billing_record.start_date = override_billing_record.start_date billing_record.end_date = override_billing_record.end_date billing_record.unadjusted_duration_microseconds = ( override_billing_record.unadjusted_duration_microseconds ) billing_record.invoicing_dates = ( override_billing_record.invoicing_dates ) billing_record.next_invoicing_date = ( override_billing_record.next_invoicing_date ) billing_record.fully_billed = ( override_billing_record.fully_billed ) billing_record.save() charge_records = ( billing_record.component_charge_records.all().order_by( "start_date" ) ) for k, component_charge_record in enumerate(charge_records): new_component = override_billing_record.component component_charge_record.component = new_component component_charge_record.component_charge = ( new_component.charges.all().first() ) if k == len(charge_records) - 1: component_charge_record.end_date = ( billing_record.end_date ) component_charge_record.save() override_billing_record.delete() else: # if the metric is not in the new plan, we cancel the billing record SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) for pc in pcs_to_create_charges_for: metric = pc.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(pc, **kwargs) self.end_date = now self.auto_renew = False self.save() generate_invoice([self, sr]) return sr def calculate_earned_revenue_per_day(self): return_dict = {} for billing_record in self.billing_records.all(): br_dict = billing_record.calculate_earned_revenue_per_day() for key in br_dict: if key not in return_dict: return_dict[key] = br_dict[key] else: return_dict[key] += br_dict[key] return return_dict def delete_subscription(self, delete_time=None): if delete_time is None: delete_time = now_utc() self.end_date = delete_time self.auto_renew = False for billing_record in self.billing_records.all(): if billing_record.start_date >= delete_time: # straight up delete it billing_record.delete() else: # essentially all we have to do is set everythign as already billed # this means we won't generate invoices for it anymore billing_record.end_date = min(billing_record.end_date, delete_time) billing_record.fully_billed = True billing_record.save() for addon_subscription in self.addon_subscription_records.all(): addon_subscription.delete_subscription(delete_time=delete_time) self.save() class Backtest(models.Model): """ This model is used to store the results of a backtest. """ backtest_name = models.TextField() start_date = models.DateField() end_date = models.DateField() organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtests" ) time_created = models.DateTimeField(default=now_utc) backtest_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) kpis = models.JSONField(default=list) backtest_results = models.JSONField(default=dict, blank=True) status = models.CharField( choices=EXPERIMENT_STATUS.choices, default=EXPERIMENT_STATUS.RUNNING, max_length=40, ) def __str__(self): return f"{self.backtest_name} - {self.start_date}" class BacktestSubstitution(models.Model): """ This model is used to substitute a backtest for a live trading session. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtest_substitutions", null=True, ) backtest = models.ForeignKey( Backtest, on_delete=models.CASCADE, related_name="backtest_substitutions" ) original_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) new_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) def __str__(self): return f"{self.backtest}" class PricingUnit(models.Model): """ This model is used to store pricing units for a plan. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="pricing_units", ) code = models.CharField(max_length=10) name = models.TextField() symbol = models.CharField(max_length=10) custom = models.BooleanField(default=False) def __str__(self): ret = f"{self.code}" if self.symbol: ret += f"({self.symbol})" return ret class Meta: constraints = [ UniqueConstraint( fields=["organization", "code"], name="unique_code_per_org" ), UniqueConstraint( fields=["organization", "name"], name="unique_name_per_org" ), ] class CustomPricingUnitConversion(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="custom_pricing_unit_conversions", null=True, ) plan_version = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="pricing_unit_conversions" ) from_unit = models.ForeignKey( PricingUnit, on_delete=models.CASCADE, related_name="+" ) from_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) to_unit = models.ForeignKey(PricingUnit, on_delete=models.CASCADE, related_name="+") to_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) def run_backtest(backtest_id): from metering_billing.models import Backtest, PlanComponent, SubscriptionRecord try: backtest = Backtest.objects.get(backtest_id=backtest_id) backtest_substitutions = backtest.backtest_substitutions.all() queries = [Q(billing_plan=x.original_plan) for x in backtest_substitutions] query = queries.pop() start_date = date_as_min_dt(backtest.start_date, timezone=pytz.UTC) end_date = date_as_max_dt(backtest.end_date, timezone=pytz.UTC) for item in queries: query |= item all_subs_time_period = ( SubscriptionRecord.objects.filter( query, start_date__lte=end_date, end_date__gte=start_date, end_date__lte=end_date, organization=backtest.organization, ) .prefetch_related("billing_plan") .prefetch_related("billing_plan__plan_components") ) all_results = { "substitution_results": [], } logger.info(f"Running backtest for {len(backtest_substitutions)} substitutions") for subst in backtest_substitutions: outer_results = { "substitution_name": f"{str(subst.original_plan)} --> {str(subst.new_plan)}", "original_plan": { "plan_name": str(subst.original_plan), "plan_id": PlanVersionUUIDField().to_representation( subst.original_plan.version_id ), "plan_revenue": Decimal(0), }, "new_plan": { "plan_name": str(subst.new_plan), "plan_id": PlanVersionUUIDField().to_representation( subst.new_plan.version_id ), "plan_revenue": Decimal(0), }, } # since we can have at most one new plan per old plan, the old plan uniquely # identifies the substitutiont subst_subscriptions = all_subs_time_period.filter( billing_plan=subst.original_plan ) inner_results = { "cumulative_revenue": {}, "revenue_by_metric": {}, "top_customers": {}, } for sub in subst_subscriptions: # create if not seen customer = sub.customer if customer not in inner_results["top_customers"]: inner_results["top_customers"][customer] = { "original_plan_revenue": Decimal(0), "new_plan_revenue": Decimal(0), } end_date = sub.end_date if end_date not in inner_results["cumulative_revenue"]: inner_results["cumulative_revenue"][end_date] = { "original_plan_revenue": Decimal(0), "new_plan_revenue": Decimal(0), } ## PROCESS OLD SUB old_usage_revenue = sub.get_usage_and_revenue() # cumulative revenue inner_results["cumulative_revenue"][end_date][ "original_plan_revenue" ] += old_usage_revenue["total_amount_due"] # customer revenue inner_results["top_customers"][customer][ "original_plan_revenue" ] += old_usage_revenue["total_amount_due"] # per metric for component_pk, component_dict in old_usage_revenue["components"]: metric = PlanComponent.objects.get(pk=component_pk).billable_metric metric_name = metric.billable_metric_name if metric_name not in inner_results["revenue_by_metric"]: inner_results["revenue_by_metric"][metric_name] = { "original_plan_revenue": Decimal(0), "new_plan_revenue": Decimal(0), } inner_results["revenue_by_metric"][metric_name][ "original_plan_revenue" ] += component_dict["revenue"] if "flat_fees" not in inner_results["revenue_by_metric"]: inner_results["revenue_by_metric"]["flat_fees"] = { "original_plan_revenue": Decimal(0), "new_plan_revenue": Decimal(0), } inner_results["revenue_by_metric"]["flat_fees"][ "original_plan_revenue" ] += old_usage_revenue["flat_amount_due"] ## PROCESS NEW SUB sub.billing_plan = subst.new_plan sub.save() new_usage_revenue = sub.get_usage_and_revenue() # revert it so we don't accidentally change the past lol sub.billing_plan = subst.original_plan sub.save() # cumulative revenue inner_results["cumulative_revenue"][end_date][ "new_plan_revenue" ] += new_usage_revenue["total_amount_due"] # customer revenue inner_results["top_customers"][customer][ "new_plan_revenue" ] += new_usage_revenue["total_amount_due"] # per metric for component_pk, component_dict in new_usage_revenue["components"]: metric = PlanComponent.objects.get(pk=component_pk).billable_metric metric_name = metric.billable_metric_name if metric_name not in inner_results["revenue_by_metric"]: inner_results["revenue_by_metric"][metric_name] = { "new_plan_revenue": Decimal(0), "original_plan_revenue": Decimal(0), } inner_results["revenue_by_metric"][metric_name][ "new_plan_revenue" ] += component_dict["revenue"] inner_results["revenue_by_metric"]["flat_fees"][ "new_plan_revenue" ] += new_usage_revenue["flat_amount_due"] # change cumulative revenue to be cumulative and in fronted format cum_rev_dict_list = [] cum_rev = inner_results.pop("cumulative_revenue") cum_rev_lst = sorted(cum_rev.items(), key=lambda x: x[0], reverse=True) date_cumrev_list = [] for date, cum_rev_dict in cum_rev_lst: date_cumrev_list.append((date.date(), cum_rev_dict)) cum_rev_lst = date_cumrev_list try: every_date = list( dates_bwn_two_dts(cum_rev_lst[-1][0], cum_rev_lst[0][0]) ) except IndexError: every_date = [] if cum_rev_lst: date, rev_dict = cum_rev_lst.pop(-1) last_dict = {**rev_dict, "date": date} else: rev_dict = {} for date in every_date: if ( date < cum_rev_lst[-1][0] ): # have not reached the next data point yet, dont add new_dict = last_dict.copy() new_dict["date"] = date elif ( date == cum_rev_lst[-1][0] ): # have reached the next data point, add it date, rev_dict = cum_rev_lst.pop() new_dict = {**rev_dict, "date": date} new_dict["original_plan_revenue"] += last_dict[ "original_plan_revenue" ] new_dict["new_plan_revenue"] += last_dict["new_plan_revenue"] last_dict = new_dict else: raise Exception("should not be greater than the most recent date") cum_rev_dict_list.append(new_dict) inner_results["cumulative_revenue"] = cum_rev_dict_list # change metric revenue to be in frontend format metric_rev = inner_results.pop("revenue_by_metric") metric_rev = [ {**rev_dict, "metric_name": metric_name} for metric_name, rev_dict in metric_rev.items() ] inner_results["revenue_by_metric"] = metric_rev # change top customers to be in frontend format top_cust_dict = {} top_cust = inner_results.pop("top_customers") top_original = sorted( top_cust.items(), key=lambda x: x[1]["original_plan_revenue"], reverse=True, )[:5] top_cust_dict["original_plan_revenue"] = [ { "customer_id": customer.customer_id, "customer_name": customer.customer_name, "value": rev_dict.get("original_plan_revenue", 0), } for customer, rev_dict in top_original ] top_new = sorted( top_cust.items(), key=lambda x: x[1]["new_plan_revenue"], reverse=True )[:5] top_cust_dict["new_plan_revenue"] = [ { "customer_id": customer.customer_id, "customer_name": customer.customer_name, "value": rev_dict.get("new_plan_revenue", 0), } for customer, rev_dict in top_new ] all_pct_change = [] for customer, rev_dict in top_cust.items(): try: pct_change = ( rev_dict.get("new_plan_revenue", 0) / rev_dict.get("original_plan_revenue", 0) - 1 ) except ZeroDivisionError: pct_change = None all_pct_change.append((customer, pct_change)) all_pct_change = sorted( [tup for tup in all_pct_change if tup[1] is not None], key=lambda x: x[1], ) top_cust_dict["biggest_pct_increase"] = [ { "customer_id": customer.customer_id, "customer_name": customer.customer_name, "value": pct_change, } for customer, pct_change in all_pct_change[-5:] ][::-1] top_cust_dict["biggest_pct_decrease"] = [ { "customer_id": customer.customer_id, "customer_name": customer.customer_name, "value": pct_change, } for customer, pct_change in all_pct_change[:5] ] inner_results["top_customers"] = top_cust_dict # now add the inner results to the outer results outer_results["results"] = inner_results try: outer_results["original_plan"]["plan_revenue"] = inner_results[ "cumulative_revenue" ][-1]["original_plan_revenue"] except IndexError: outer_results["original_plan"]["plan_revenue"] = Decimal(0) try: outer_results["new_plan"]["plan_revenue"] = inner_results[ "cumulative_revenue" ][-1]["new_plan_revenue"] except IndexError: outer_results["new_plan"]["plan_revenue"] = Decimal(0) try: outer_results["pct_revenue_change"] = ( outer_results["new_plan"]["plan_revenue"] / outer_results["original_plan"]["plan_revenue"] - 1 ) except (ZeroDivisionError, InvalidOperation): outer_results["pct_revenue_change"] = None all_results["substitution_results"].append(outer_results) all_results["original_plans_revenue"] = sum( x["original_plan"]["plan_revenue"] for x in all_results["substitution_results"] ) all_results["new_plans_revenue"] = sum( x["new_plan"]["plan_revenue"] for x in all_results["substitution_results"] ) try: all_results["pct_revenue_change"] = ( all_results["new_plans_revenue"] / all_results["original_plans_revenue"] - 1 ) except (ZeroDivisionError, InvalidOperation): all_results["pct_revenue_change"] = None all_results = make_all_decimals_floats(all_results) all_results = make_all_datetimes_dates(all_results) all_results = make_all_dates_times_strings(all_results) serializer = AllSubstitutionResultsSerializer(data=all_results) try: serializer.is_valid(raise_exception=True) except Exception: logger.error("errors", serializer.errors, "all results", all_results) raise Exception results = make_all_dates_times_strings(serializer.validated_data) backtest.backtest_results = results backtest.status = EXPERIMENT_STATUS.COMPLETED backtest.save() except Exception as e: backtest.status = EXPERIMENT_STATUS.FAILED backtest.save() raise e def run_generate_invoice(subscription_record_pk_set, **kwargs): from metering_billing.invoice import generate_invoice from metering_billing.models import SubscriptionRecord subscription_record_set = SubscriptionRecord.objects.filter( pk__in=subscription_record_pk_set, ) generate_invoice(subscription_record_set, **kwargs) def setup_demo3( organization_name, username=None, email=None, password=None, mode="create", org_type=Organization.OrganizationType.EXTERNAL_DEMO, ): if mode == "create": try: org = Organization.objects.get(organization_name=organization_name) team = org.team Event.objects.filter(organization=org).delete() org.delete() if team is not None: team.delete() logger.info("[DEMO3]: Deleted existing organization, replacing") except Organization.DoesNotExist: logger.info("[DEMO3]: creating from scratch") try: user = User.objects.get(username=username, email=email) except Exception: user = User.objects.create_user( username=username, email=email, password=password ) if user.organization is None: organization, _ = Organization.objects.get_or_create( organization_name=organization_name ) organization.organization_type = org_type user.organization = organization user.team = organization.team user.save() organization.save() elif mode == "regenerate": organization = Organization.objects.get(organization_name=organization_name) user = organization.users.all().first() WebhookEndpoint.objects.filter(organization=organization).delete() WebhookTrigger.objects.filter(organization=organization).delete() PlanVersion.objects.filter(organization=organization).delete() Plan.objects.filter( organization=organization, parent_plan__isnull=False ).delete() Plan.objects.filter(organization=organization).delete() Customer.objects.filter(organization=organization).delete() Event.objects.filter(organization=organization).delete() Metric.objects.filter(organization=organization).delete() Product.objects.filter(organization=organization).delete() CustomerBalanceAdjustment.objects.filter(organization=organization).delete() Feature.objects.filter(organization=organization).delete() Invoice.objects.filter(organization=organization).delete() APIToken.objects.filter(organization=organization).delete() TeamInviteToken.objects.filter(organization=organization).delete() PriceAdjustment.objects.filter(organization=organization).delete() ExternalPlanLink.objects.filter(organization=organization).delete() SubscriptionRecord.objects.filter(organization=organization).delete() Backtest.objects.filter(organization=organization).delete() PricingUnit.objects.filter(organization=organization).delete() NumericFilter.objects.filter(organization=organization).delete() CategoricalFilter.objects.filter(organization=organization).delete() PriceTier.objects.filter(organization=organization).delete() PlanComponent.objects.filter(organization=organization).delete() InvoiceLineItem.objects.filter(organization=organization).delete() BacktestSubstitution.objects.filter(organization=organization).delete() CustomPricingUnitConversion.objects.filter(organization=organization).delete() if user is None: organization.delete() return organization = user.organization big_customers = [] for _ in range(1): customer = Customer.objects.create( organization=organization, customer_name="BigCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) big_customers.append(customer) medium_customers = [] for _ in range(2): customer = Customer.objects.create( organization=organization, customer_name="MediumCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) medium_customers.append(customer) small_customers = [] for _ in range(5): customer = Customer.objects.create( organization=organization, customer_name="SmallCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) small_customers.append(customer) metrics_map = {} for property_name, usage_aggregation_type, billable_metric_name, name in zip( [None, "words", "compute_time", "language", "subsection"], ["count", "sum", "sum", "unique", "unique"], ["API Calls", "Words", "Compute Time", "Unique Languages", "Content Types"], ["calls", "sum_words", "sum_compute", "unique_lang", "unique_subsections"], ): validated_data = { "organization": organization, "event_name": "generate_text", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.COUNTER, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric(validated_data) metrics_map[name] = metric for property_name, usage_aggregation_type, billable_metric_name, name in zip( ["qty"], ["max"], ["User Seats"], ["num_seats"] ): validated_data = { "organization": organization, "event_name": "log_num_seats", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.GAUGE, "event_type": EVENT_TYPE.TOTAL, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric(validated_data) metrics_map[name] = metric for property_name, usage_aggregation_type, billable_metric_name, name in zip( ["cost"], ["sum"], ["Compute Cost"], ["compute_cost"] ): validated_data = { "organization": organization, "event_name": "computation", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.COUNTER, "is_cost_metric": True, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric(validated_data) assert metric is not None metrics_map[name] = metric metrics_map["calls"] sum_words = metrics_map["sum_words"] sum_compute = metrics_map["sum_compute"] metrics_map["unique_lang"] metrics_map["unique_subsections"] num_seats = metrics_map["num_seats"] metrics_map["compute_cost"] # SET THE BILLING PLANS plan = Plan.objects.create( plan_name="Free Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) free_bp = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=free_bp, amount=0, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=free_bp.currency, ) create_pc_and_tiers( organization, plan_version=free_bp, billable_metric=sum_words, free_units=2_000 ) create_pc_and_tiers( organization, plan_version=free_bp, billable_metric=num_seats, free_units=1 ) plan.save() plan = Plan.objects.create( plan_name="10K Words Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_10_og = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_10_og, amount=49, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_10_og.currency, ) create_pc_and_tiers( organization, plan_version=bp_10_og, billable_metric=sum_words, free_units=10_000, ) create_pc_and_tiers( organization, plan_version=bp_10_og, billable_metric=num_seats, free_units=5 ) plan.save() plan = Plan.objects.create( plan_name="25K Words Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_25_og = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_25_og, amount=99, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_25_og.currency, ) create_pc_and_tiers( organization, plan_version=bp_25_og, billable_metric=sum_words, free_units=25_000, ) create_pc_and_tiers( organization, plan_version=bp_25_og, billable_metric=num_seats, free_units=5 ) plan.save() plan = Plan.objects.create( plan_name="50K Words Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_50_og = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_50_og, amount=279, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_50_og.currency, ) create_pc_and_tiers( organization, plan_version=bp_50_og, billable_metric=sum_words, free_units=50_000, ) create_pc_and_tiers( organization, plan_version=bp_50_og, billable_metric=num_seats, free_units=5 ) plan.save() plan = Plan.objects.create( plan_name="10K Words Plan - UB Compute + Seats", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_10_compute_seats = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_10_compute_seats, amount=19, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_10_compute_seats.currency, ) create_pc_and_tiers( organization, plan_version=bp_10_compute_seats, billable_metric=sum_words, free_units=10_000, ) create_pc_and_tiers( organization, plan_version=bp_10_compute_seats, billable_metric=sum_compute, free_units=75, cost_per_batch=0.33, metric_units_per_batch=10, ) create_pc_and_tiers( organization, plan_version=bp_10_compute_seats, billable_metric=num_seats, free_units=None, cost_per_batch=10, metric_units_per_batch=1, ) plan.save() plan = Plan.objects.create( plan_name="25K Words Plan - UB Compute + Seats", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_25_compute_seats = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_25_compute_seats, amount=59, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_25_compute_seats.currency, ) create_pc_and_tiers( organization, plan_version=bp_25_compute_seats, billable_metric=sum_words, free_units=25_000, ) create_pc_and_tiers( organization, plan_version=bp_25_compute_seats, billable_metric=sum_compute, free_units=100, cost_per_batch=0.47, metric_units_per_batch=10, ) create_pc_and_tiers( organization, plan_version=bp_25_compute_seats, billable_metric=num_seats, free_units=None, cost_per_batch=12, metric_units_per_batch=1, ) plan.save() plan = Plan.objects.create( plan_name="50K Words Plan - UB Compute + Seats", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_50_compute_seats = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_50_compute_seats, amount=179, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_50_compute_seats.currency, ) create_pc_and_tiers( organization, plan_version=bp_50_compute_seats, billable_metric=sum_words, free_units=50_000, ) create_pc_and_tiers( organization, plan_version=bp_50_compute_seats, billable_metric=sum_compute, free_units=200, cost_per_batch=0.67, metric_units_per_batch=10, ) create_pc_and_tiers( organization, plan_version=bp_50_compute_seats, billable_metric=num_seats, free_units=None, cost_per_batch=10, metric_units_per_batch=1, ) plan.save() six_months_ago = now_utc() - relativedelta(months=6) - relativedelta(days=5) for cust_set_name, cust_set in [ ("big", big_customers), ("medium", medium_customers), ("small", small_customers), ]: plan_dict = { "big": { 0: bp_10_compute_seats, 1: bp_25_compute_seats, 2: bp_50_compute_seats, 3: bp_50_compute_seats, 4: bp_50_compute_seats, 5: bp_50_compute_seats, }, "medium": { 0: bp_10_compute_seats, 1: bp_10_compute_seats, 2: bp_25_compute_seats, 3: bp_25_compute_seats, 4: bp_25_compute_seats, 5: bp_25_compute_seats, }, "small": { 0: free_bp, 1: free_bp, 2: bp_10_compute_seats, 3: bp_10_compute_seats, 4: bp_10_compute_seats, 5: bp_10_compute_seats, }, } for i, customer in enumerate(cust_set): beginning = six_months_ago offset = np.random.randint(0, 30) beginning = beginning + relativedelta(days=offset) for months in range(6): sub_start = beginning + relativedelta(months=months) plan = plan_dict[cust_set_name][months] languages = [ "en", "es", "fr", "de", "it", "pt", "ru", ] if cust_set_name == "big": users_mean, users_sd = 4.5, 0.5 scale = ( 1.1 if plan == bp_10_og else (0.95 if plan == bp_25_og else 0.80) ) ct_mean, ct_sd = 0.1, 0.02 elif cust_set_name == "medium": languages = languages[:5] scale = ( 1.2 if plan == bp_10_compute_seats else (1 if plan == bp_25_compute_seats else 0.85) ) ct_mean, ct_sd = 0.075, 0.01 elif cust_set_name == "small": languages = languages[:1] scale = ( 1.4 if plan == bp_10_compute_seats else (1.1 if plan == bp_25_compute_seats else 0.95) ) ct_mean, ct_sd = 0.065, 0.01 sr = make_subscription_record( organization=organization, customer=customer, plan=plan, start_date=sub_start, is_new=months == 0, ) tot_word_limit = float( max( x.range_end for x in plan.plan_components.get( billable_metric=sum_words ).tiers.all() ) ) word_limit = tot_word_limit - np.random.randint(0, tot_word_limit * 0.2) word_count = 0 while word_count < word_limit: event_words = random.gauss(325, 60) if word_count + event_words > word_limit: break compute_time = event_words * random.gauss(0.1, 0.02) language = random.choice(languages) subsection = ( 1 if plan == free_bp else np.random.exponential(scale=scale) ) subsection = str(subsection // 1) for tc in random_date(sr.start_date, sr.end_date, 1): tc = tc Event.objects.create( organization=organization, event_name="generate_text", time_created=tc, idempotency_id=str(uuid.uuid4().hex), properties={ "language": language, "subsection": subsection, "compute_time": compute_time, "words": event_words, }, cust_id=customer.customer_id, ) Event.objects.create( organization=organization, event_name="computation", time_created=tc, idempotency_id=str(uuid.uuid4().hex), properties={ "cost": abs(compute_time * random.gauss(ct_mean, ct_sd)), }, cust_id=customer.customer_id, ) word_count += event_words max_users = max( x.range_end for x in plan.plan_components.get( billable_metric=num_seats ).tiers.all() ) n = max(int(random.gauss(6, 1.5) // 1), 1) baker.make( Event, organization=organization, event_name="log_num_seats", properties=gaussian_users(n, users_mean, users_sd, max_users), time_created=random_date(sr.start_date, sr.end_date, n), idempotency_id=itertools.cycle( [str(uuid.uuid4().hex) for _ in range(n)] ), _quantity=n, cust_id=customer.customer_id, ) next_plan = ( bp_10_compute_seats if months + 1 == 0 else ( bp_25_compute_seats if months + 1 == 1 else bp_50_compute_seats ) ) if months == 0: try: run_generate_invoice.delay( [sr.pk], issue_date=sr.start_date, ) except Exception as e: print(e) pass if months != 5: cur_replace_with = sr.billing_plan.replace_with sr.billing_plan.replace_with = next_plan sr.save() try: run_generate_invoice.delay( [sr.pk], issue_date=sr.end_date, charge_next_plan=True ) except Exception as e: print(e) pass sr.billing_plan.replace_with = cur_replace_with sr.save() now = now_utc() backtest = Backtest.objects.create( backtest_name=organization, start_date="2022-08-01", end_date="2022-11-01", organization=organization, time_created=now, kpis=[BACKTEST_KPI.TOTAL_REVENUE], ) BacktestSubstitution.objects.create( backtest=backtest, original_plan=bp_10_compute_seats, new_plan=bp_10_og, organization=organization, ) try: run_backtest.delay(backtest.backtest_id) except Exception as e: print(e) pass return user
null
6,987
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( LightweightCustomerSerializer, LightweightMetricSerializer, LightweightPlanVersionSerializer, ) from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP from metering_billing.invoice import generate_invoice from metering_billing.models import ( Analysis, APIToken, Backtest, BacktestSubstitution, CategoricalFilter, ComponentFixedCharge, Customer, CustomerBalanceAdjustment, CustomPricingUnitConversion, Event, ExternalPlanLink, Feature, Invoice, InvoiceLineItem, Metric, NumericFilter, Organization, Plan, PlanComponent, PlanVersion, PriceAdjustment, PriceTier, PricingUnit, Product, RecurringCharge, SubscriptionRecord, TeamInviteToken, User, WebhookEndpoint, WebhookTrigger, ) from metering_billing.tasks import run_backtest, run_generate_invoice from metering_billing.utils import ( convert_to_decimal, date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_decimals_strings, now_utc, round_all_decimals_to_two_places, ) from metering_billing.utils.enums import ( ANALYSIS_KPI, BACKTEST_KPI, EVENT_TYPE, EXPERIMENT_STATUS, METRIC_AGGREGATION, METRIC_GRANULARITY, METRIC_STATUS, METRIC_TYPE, PLAN_DURATION, ) logger = logging.getLogger("django.server") def create_pc_and_tiers( organization, plan_version, billable_metric, max_units=None, free_units=None, cost_per_batch=None, metric_units_per_batch=None, ): pc = PlanComponent.objects.create( plan_version=plan_version, billable_metric=billable_metric, organization=organization, ) range_start = 0 if free_units is not None: PriceTier.objects.create( plan_component=pc, range_start=0, range_end=free_units, type=PriceTier.PriceTierType.FREE, organization=organization, ) range_start = free_units if cost_per_batch is not None: PriceTier.objects.create( plan_component=pc, range_start=range_start, range_end=max_units, type=PriceTier.PriceTierType.PER_UNIT, cost_per_batch=cost_per_batch, metric_units_per_batch=metric_units_per_batch, organization=organization, batch_rounding_type=PriceTier.BatchRoundingType.NO_ROUNDING, ) def random_date(start, end, n): """Generate a random datetime between `start` and `end`""" if type(start) is datetime.date: start = date_as_min_dt(start, timezone=pytz.UTC) if type(end) is datetime.date: end = date_as_max_dt(end, timezone=pytz.UTC) for _ in range(n): dt = start + relativedelta( # Get a random amount of seconds between `start` and `end` seconds=random.randint(0, int((end - start).total_seconds())), ) yield dt def gaussian_users(n, mean=3, sd=1, mx=None): "Generate `n` latencies with a gaussian distribution" for _ in range(n): qty = round(random.gauss(mean, sd), 0) if mx is not None: qty = min(qty, mx) yield { "qty": int(max(qty, 1)), } def make_subscription_record( organization, customer, plan, start_date, is_new, ): sr = SubscriptionRecord.create_subscription_record( start_date=start_date, end_date=None, billing_plan=plan, customer=customer, organization=organization, subscription_filters=None, is_new=is_new, quantity=1, do_generate_invoice=False, ) return sr METRIC_HANDLER_MAP = { METRIC_TYPE.COUNTER: CounterHandler, METRIC_TYPE.GAUGE: GaugeHandler, METRIC_TYPE.RATE: RateHandler, METRIC_TYPE.CUSTOM: CustomHandler, } class Organization(models.Model): class OrganizationType(models.IntegerChoices): PRODUCTION = (1, "Production") DEVELOPMENT = (2, "Development") EXTERNAL_DEMO = (3, "Demo") INTERNAL_DEMO = (4, "Internal Demo") team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="organizations" ) organization_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization_name = models.TextField(blank=False, null=False) created = models.DateField(default=now_utc) organization_type = models.PositiveSmallIntegerField( choices=OrganizationType.choices, default=OrganizationType.DEVELOPMENT ) properties = models.JSONField(default=dict, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) # BILLING RELATED FIELDS default_payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) braintree_integration = models.ForeignKey( "BraintreeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="+", null=True, blank=True, help_text="The primary origin address for the organization", ) default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) # TAX RELATED FIELDS tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) tax_providers = TaxProviderListField(default=[TAX_PROVIDER.LOTUS]) # TIMEZONE RELATED FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) __original_timezone = None # SUBSCRIPTION RELATED FIELDS subscription_filter_keys = ArrayField( models.TextField(), default=list, blank=True, help_text="Allowed subscription filter keys", ) __original_subscription_filter_keys = None # PROVISIONING FIELDS webhooks_provisioned = models.BooleanField(default=False) currencies_provisioned = models.IntegerField(default=0) crm_settings_provisioned = models.BooleanField(default=False) # settings gen_cust_in_stripe_after_lotus = models.BooleanField(default=False) gen_cust_in_braintree_after_lotus = models.BooleanField(default=False) payment_grace_period = models.IntegerField(null=True, default=None) lotus_is_customer_source_for_salesforce = models.BooleanField(default=False) # HISTORY RELATED FIELDS history = HistoricalRecords() def __init__(self, *args, **kwargs): super(Organization, self).__init__(*args, **kwargs) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys class Meta: indexes = [ models.Index(fields=["organization_name"]), models.Index(fields=["organization_type"]), models.Index(fields=["organization_id"]), models.Index(fields=["team"]), ] def __str__(self): return self.organization_name def save(self, *args, **kwargs): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP new = self._state.adding is True # self._state.adding represents whether creating new instance or updating if self.timezone != self.__original_timezone and not new: num_updated = self.customers.filter(timezone_set=False).update( timezone=self.timezone ) if num_updated > 0: customer_ids = self.customers.filter(timezone_set=False).values_list( "id", flat=True ) customer_cache_keys = [f"tz_customer_{id}" for id in customer_ids] cache.delete_many(customer_cache_keys) if self.team is None: self.team = Team.objects.create(name=self.organization_name) if self.subscription_filter_keys is None: self.subscription_filter_keys = [] self.subscription_filter_keys = sorted( list( set(self.subscription_filter_keys).union( set(self.__original_subscription_filter_keys) ) ) ) super(Organization, self).save(*args, **kwargs) if self.subscription_filter_keys != self.__original_subscription_filter_keys: for metric in self.metrics.all(): METRIC_HANDLER_MAP[metric.metric_type].create_continuous_aggregate( metric, refresh=True ) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys if new: self.provision_currencies() if not self.default_currency: self.default_currency = PricingUnit.objects.get( organization=self, code="USD" ) self.save() if not self.webhooks_provisioned: self.provision_webhooks() def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_address(self) -> Address: if self.default_payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_organization_address(self) elif self.default_payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_organization_address(self) else: return self.address def provision_webhooks(self): if SVIX_CONNECTOR is not None and not self.webhooks_provisioned: logger.info("provisioning webhooks") svix = SVIX_CONNECTOR svix.application.create( ApplicationIn(uid=self.organization_id.hex, name=self.organization_name) ) self.webhooks_provisioned = True self.save() def provision_currencies(self): if SUPPORTED_CURRENCIES_VERSION != self.currencies_provisioned: for name, code, symbol in SUPPORTED_CURRENCIES: PricingUnit.objects.get_or_create( organization=self, code=code, name=name, symbol=symbol, custom=False ) PricingUnit.objects.filter( ~Q(code__in=[code for _, code, _ in SUPPORTED_CURRENCIES]), custom=False, organization=self, ).delete() self.currencies_provisioned = SUPPORTED_CURRENCIES_VERSION self.save() class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class WebhookTrigger(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_triggers", null=True, ) webhook_endpoint = models.ForeignKey( WebhookEndpoint, on_delete=models.CASCADE, related_name="triggers" ) trigger_name = models.CharField( choices=WEBHOOK_TRIGGER_EVENTS.choices, max_length=40 ) class Meta: indexes = [ models.Index( fields=["organization", "webhook_endpoint", "trigger_name"], name="unique_webhook_trigger", ) ] class User(AbstractUser): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="users", ) team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="users" ) email = models.EmailField(unique=True) history = HistoricalRecords() def save(self, *args, **kwargs): if not self.team and self.organization: self.team = self.organization.team super(User, self).save(*args, **kwargs) class Product(models.Model): """ This model is used to store the products that are available to be purchased. """ name = models.CharField(max_length=100, blank=False) description = models.TextField(null=True, blank=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="products" ) product_id = models.SlugField(default=product_uuid, max_length=100, unique=True) status = models.CharField(choices=PRODUCT_STATUS.choices, max_length=40) history = HistoricalRecords() class Meta: unique_together = ("organization", "product_id") def __str__(self): return f"{self.name}" class Customer(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="customers" ) customer_name = models.TextField( blank=True, help_text="The display name of the customer", null=True, ) email = models.EmailField( max_length=100, help_text="The primary email address of the customer, must be the same as the email address used to create the customer in the payment provider", null=True, ) customer_id = models.TextField( default=customer_uuid, help_text="The id provided when creating the customer, we suggest matching with your internal customer id in your backend", null=True, ) uuidv5_customer_id = models.UUIDField( help_text="The v5 UUID generated from the customer_id. This is used for efficient lookups in the database, specifically for the Events table", null=True, ) properties = models.JSONField( default=dict, null=True, help_text="Extra metadata for the customer" ) deleted = models.DateTimeField( null=True, help_text="The date the customer was deleted" ) # BILLING RELATED FIELDS default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="customers", null=True, blank=True, help_text="The currency the customer will be invoiced in", ) shipping_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="shipping_customers", null=True, blank=True, help_text="The shipping address for the customer", ) billing_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="billing_customers", null=True, blank=True, help_text="The billing address for the customer", ) # TAX RELATED FIELDS tax_providers = TaxProviderListField(default=[]) tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) # TIMEZONE FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) timezone_set = models.BooleanField(default=False) # PAYMENT PROCESSOR FIELDS payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) braintree_integration = models.ForeignKey( "BraintreeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) salesforce_integration = models.OneToOneField( "UnifiedCRMCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customer", ) # HISTORY FIELDS created = models.DateTimeField(default=now_utc) history = HistoricalRecords() objects = BaseCustomerManager() deleted_objects = DeletedCustomerManager() class Meta: constraints = [ UniqueConstraint(fields=["organization", "email"], name="unique_email"), UniqueConstraint( fields=["organization", "customer_id"], name="unique_customer_id" ), ] def __str__(self) -> str: return str(self.customer_name) + " " + str(self.customer_id) def save(self, *args, **kwargs): if not self.default_currency: try: self.default_currency = ( self.organization.default_currency or PricingUnit.objects.get( code="USD", organization=self.organization ) ) except PricingUnit.DoesNotExist: self.default_currency = None super(Customer, self).save(*args, **kwargs) def get_active_subscription_records(self): active_subscription_records = self.subscription_records.active().filter( fully_billed=False, ) return active_subscription_records def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_usage_and_revenue(self): customer_subscriptions = ( SubscriptionRecord.objects.active() .filter( customer=self, organization=self.organization, ) .prefetch_related("billing_plan__plan_components") .prefetch_related("billing_plan__plan_components__billable_metric") .select_related("billing_plan") ) subscription_usages = {"subscriptions": [], "sub_objects": []} for subscription in customer_subscriptions: sub_dict = subscription.get_usage_and_revenue() del sub_dict["components"] sub_dict["billing_plan_name"] = subscription.billing_plan.plan.plan_name subscription_usages["subscriptions"].append(sub_dict) subscription_usages["sub_objects"].append(subscription) return subscription_usages def get_active_sub_drafts_revenue(self): from metering_billing.invoice import generate_invoice total = 0 sub_records = self.get_active_subscription_records() if sub_records is not None and len(sub_records) > 0: invs = generate_invoice( sub_records, draft=True, charge_next_plan=True, ) total += sum([inv.amount for inv in invs]) for inv in invs: inv.delete() return total def get_currency_balance(self, currency): now = now_utc() balance = self.customer_balance_adjustments.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), effective_at__lte=now, amount_currency=currency, ).aggregate(balance=Sum("amount"))["balance"] or Decimal(0) return balance def get_outstanding_revenue(self): unpaid_invoice_amount_due = ( self.invoices.filter(payment_status=Invoice.PaymentStatus.UNPAID) .aggregate(unpaid_inv_amount=Sum("amount")) .get("unpaid_inv_amount") ) total_amount_due = unpaid_invoice_amount_due or 0 return total_amount_due def get_billing_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="billing") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.billing_address def get_shipping_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="shipping") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.shipping_address class CustomerBalanceAdjustment(models.Model): """ This model is used to store the customer balance adjustments. """ adjustment_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="+", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name="customer_balance_adjustments" ) amount = models.DecimalField(decimal_places=10, max_digits=20) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="adjustments", null=True, blank=True, ) description = models.TextField(null=True, blank=True) created = models.DateTimeField(default=now_utc) effective_at = models.DateTimeField(default=now_utc) expires_at = models.DateTimeField(null=True, blank=True) parent_adjustment = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="drawdowns", ) amount_paid = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0) ) amount_paid_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="paid_adjustments", null=True, blank=True, ) status = models.CharField( max_length=20, choices=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.choices, default=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) def __str__(self): return f"{self.customer.customer_name} {self.amount} {self.created}" class Meta: ordering = ["-created"] unique_together = ("customer", "created") indexes = [ models.Index( fields=["organization", "adjustment_id"] ), # for lookup for single models.Index( fields=["organization", "customer", "pricing_unit", "-expires_at"] ), # for lookup for drawdowns models.Index(fields=["status", "expires_at"]), # for lookup for expired ] def save(self, *args, **kwargs): new = self._state.adding is True if not new: orig = CustomerBalanceAdjustment.objects.get(pk=self.pk) if ( orig.amount != self.amount or orig.pricing_unit != self.pricing_unit or orig.created != self.created or orig.effective_at != self.effective_at or orig.parent_adjustment != self.parent_adjustment ): raise NotEditable( "Cannot update any fields in a balance adjustment other than status and description" ) if self.expires_at is not None and now_utc() > self.expires_at: raise NotEditable("Cannot change the expiry date to the past") if self.amount < 0: assert ( self.parent_adjustment is not None ), "If credit is negative, parent adjustment must be provided" if self.parent_adjustment: assert ( self.parent_adjustment.amount > 0 ), "Parent adjustment must be a credit adjustment" assert ( self.parent_adjustment.customer == self.customer ), "Parent adjustment must be for the same customer" assert self.amount < 0, "Child adjustment must be a debit adjustment" assert ( self.pricing_unit == self.parent_adjustment.pricing_unit ), "Child adjustment must be in the same currency as parent adjustment" assert self.parent_adjustment.get_remaining_balance() - self.amount >= 0, ( "Child adjustment must be less than or equal to the remaining balance of " "the parent adjustment" ) if not self.organization: self.organization = self.customer.organization if self.amount_paid is None or self.amount_paid == 0: self.amount_paid_currency = None if not self.pricing_unit: raise ValidationError("Pricing unit must be provided") super(CustomerBalanceAdjustment, self).save(*args, **kwargs) def get_remaining_balance(self): try: dd_aggregate = self.total_drawdowns except AttributeError: dd_aggregate = self.drawdowns.aggregate(drawdowns=Sum("amount"))[ "drawdowns" ] drawdowns = dd_aggregate or 0 return self.amount + drawdowns def zero_out(self, reason=None): if reason == "expired": fmt = self.expires_at.strftime("%Y-%m-%d %H:%M") description = f"Expiring remaining credit at {fmt} UTC" elif reason == "voided": fmt = now_utc().strftime("%Y-%m-%d %H:%M") description = f"Voiding remaining credit at {fmt} UTC" else: description = "Zeroing out remaining credit" remaining_balance = self.get_remaining_balance() if remaining_balance > 0: CustomerBalanceAdjustment.objects.create( organization=self.customer.organization, customer=self.customer, amount=-remaining_balance, pricing_unit=self.pricing_unit, parent_adjustment=self, description=description, ) self.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE self.save() def draw_down_amount(customer, amount, pricing_unit, description=""): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .annotate( cost_basis=Cast( Coalesce(F("amount_paid") / F("amount"), 0), FloatField() ) ) .order_by( F("expires_at").asc(nulls_last=True), F("cost_basis").desc(nulls_last=True), ) .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") + F("drawn_down_amount")) ) am = amount for adj in adjs: remaining_balance = adj.remaining_balance if remaining_balance <= 0: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() continue drawdown_amount = min(am, remaining_balance) CustomerBalanceAdjustment.objects.create( organization=customer.organization, customer=customer, amount=-drawdown_amount, pricing_unit=adj.pricing_unit, parent_adjustment=adj, description=description, ) if drawdown_amount == remaining_balance: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() am -= drawdown_amount if am == 0: break return am def get_pricing_unit_balance(customer, pricing_unit): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .prefetch_related("drawdowns") .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") - F("drawn_down_amount")) .aggregate(total_balance=Sum("remaining_balance"))["total_balance"] ) total_balance = adjs or 0 return total_balance class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=models.SET_NULL, related_name="+", null=True, blank=True ) cust_id = models.TextField(blank=True) uuidv5_customer_id = models.UUIDField() event_name = models.TextField( help_text="String name of the event, corresponds to definition in metrics", ) uuidv5_event_name = models.UUIDField() time_created = models.DateTimeField( help_text="The time that the event occured, represented as a datetime in RFC3339 in the UTC timezome." ) properties = models.JSONField( default=dict, blank=True, help_text="Extra metadata on the event that can be filtered and queried on in the metrics. All key value pairs should have string keys and values can be either strings or numbers. Place subscription filters in this object to specify which subscription the event should be tracked under", ) idempotency_id = models.TextField( default=event_uuid, help_text="A unique identifier for the specific event being passed in. Passing in a unique id allows Lotus to make sure no double counting occurs. We recommend using a UUID4. You can use the same idempotency_id again after 45 days.", primary_key=True, ) uuidv5_idempotency_id = models.UUIDField() inserted_at = models.DateTimeField(default=now_utc) objects = EventManager() class Meta: managed = False db_table = "metering_billing_usageevent" def __str__(self): return ( str(self.event_name)[:6] + "-" + str(self.cust_id)[:8] + "-" + str(self.time_created)[:10] + "-" + str(self.idempotency_id)[:6] ) class NumericFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="numeric_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField(max_length=10, choices=NUMERIC_FILTER_OPERATORS.choices) comparison_value = models.FloatField() class CategoricalFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="categorical_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField( max_length=10, choices=CATEGORICAL_FILTER_OPERATORS.choices ) comparison_value = models.JSONField() def __str__(self): return f"{self.property_name} {self.operator} {self.comparison_value}" class Metric(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="metrics", ) event_name = models.TextField( help_text="Name of the event that this metric is tracking." ) metric_type = models.CharField( max_length=20, choices=METRIC_TYPE.choices, default=METRIC_TYPE.COUNTER, help_text="The type of metric that this is. Please refer to our documentation for an explanation of the different types.", ) properties = models.JSONField(default=dict, blank=True, null=True) billable_metric_name = models.TextField(blank=True, null=True) metric_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) event_type = models.CharField( max_length=20, choices=EVENT_TYPE.choices, blank=True, null=True, help_text="Used only for metrics of type 'gauge'. Please refer to our documentation for an explanation of the different types.", ) # metric type specific usage_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.COUNT, help_text="The type of aggregation that should be used for this metric. Please refer to our documentation for an explanation of the different types.", ) billable_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.SUM, blank=True, null=True, ) property_name = models.TextField( blank=True, null=True, help_text="The name of the property of the event that should be used for this metric. Doesn't apply if the metric is of type 'counter' with an aggregation of count.", ) granularity = models.CharField( choices=METRIC_GRANULARITY.choices, default=METRIC_GRANULARITY.TOTAL, max_length=10, blank=True, null=True, help_text="The granularity of the metric. Only applies to metrics of type 'gauge' or 'rate'.", ) proration = models.CharField( choices=METRIC_GRANULARITY.choices, default=None, max_length=10, blank=True, null=True, help_text="The proration of the metric. Only applies to metrics of type 'gauge'.", ) is_cost_metric = models.BooleanField( default=False, help_text="Whether or not this metric is a cost metric (used to track costs to your business).", ) custom_sql = models.TextField( blank=True, null=True, help_text="A custom SQL query that can be used to define the metric. Please refer to our documentation for more information.", ) # filters numeric_filters = models.ManyToManyField(NumericFilter, blank=True) categorical_filters = models.ManyToManyField(CategoricalFilter, blank=True) # status status = models.CharField( choices=METRIC_STATUS.choices, max_length=40, default=METRIC_STATUS.ACTIVE ) mat_views_provisioned = models.BooleanField(default=False) # records history = HistoricalRecords() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "billable_metric_name"], condition=Q(status=METRIC_STATUS.ACTIVE), name="unique_org_billable_metric_name", ), ] + [ models.UniqueConstraint( fields=sorted( list( { "organization", "billable_metric_name", # nullable "event_name", "metric_type", "usage_aggregation_type", "billable_aggregation_type", # nullable "property_name", # nullable "granularity", # nullable "is_cost_metric", "custom_sql", # nullable } - {x for x in nullables} ) ), condition=Q( **{f"{nullable}__in": [None, ""] for nullable in sorted(nullables)} ) & Q(status=METRIC_STATUS.ACTIVE), name="uq_metric_w_null__" + "_".join( [ "_".join([x[:2] for x in nullable.split("_")]) for nullable in sorted(nullables) ] ), ) for nullables in itertools.chain( *map( lambda x: itertools.combinations( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], x, ), range( 0, len( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], ) + 1, ), ) ) ] indexes = [ models.Index(fields=["organization", "status"]), models.Index(fields=["organization", "is_cost_metric"]), models.Index(fields=["organization", "metric_id"]), ] def __str__(self): return self.billable_metric_name or "" def save(self, *args, **kwargs): super().save(*args, **kwargs) def delete_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.archive_metric(self) self.mat_views_provisioned = False self.save() def get_aggregation_type(self): return self.aggregation_type def get_billing_record_total_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_total_billable_usage(self, billing_record) return usage def get_billing_record_daily_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_daily_billable_usage(self, billing_record) return usage def get_billing_record_current_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_current_usage(self, billing_record) return usage def get_daily_total_usage( self, start_date: datetime.date, end_date: datetime.date, customer: Optional[Customer] = None, top_n: Optional[int] = None, ) -> dict[Union[Customer, Literal["Other"]], dict[datetime.date, Decimal]]: from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_daily_total_usage( self, start_date, end_date, customer, top_n ) return usage def refresh_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self, refresh=True) self.mat_views_provisioned = True self.save() def provision_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self) self.mat_views_provisioned = True self.save() class PriceTier(models.Model): class PriceTierType(models.IntegerChoices): FLAT = (1, _("flat")) PER_UNIT = (2, _("per_unit")) FREE = (3, _("free")) class BatchRoundingType(models.IntegerChoices): ROUND_UP = (1, _("round_up")) ROUND_DOWN = (2, _("round_down")) ROUND_NEAREST = (3, _("round_nearest")) NO_ROUNDING = (4, _("no_rounding")) organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="price_tiers", null=True ) plan_component = models.ForeignKey( "PlanComponent", on_delete=models.CASCADE, related_name="tiers", null=True, blank=True, ) type = models.PositiveSmallIntegerField(choices=PriceTierType.choices) range_start = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) range_end = models.DecimalField( max_digits=20, decimal_places=10, null=True, blank=True, validators=[MinValueValidator(0)], ) cost_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, validators=[MinValueValidator(0)], ) metric_units_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, default=1.0, validators=[MinValueValidator(0)], ) batch_rounding_type = models.PositiveSmallIntegerField( choices=BatchRoundingType.choices, blank=True, null=True, ) class Meta: constraints = [ models.CheckConstraint( check=Q(range_end__gte=F("range_start")) | Q(range_end__isnull=True), name="price_tier_type_valid", ), models.UniqueConstraint( fields=["organization", "plan_component", "range_start"], name="unique_price_tier", ), ] def save(self, *args, **kwargs): new = self._state.adding is True ranges = [ (tier["range_start"], tier["range_end"]) for tier in self.plan_component.tiers.order_by("range_start").values( "range_start", "range_end" ) ] if new: ranges = sorted( ranges + [(self.range_start, self.range_end)], key=lambda x: x[0] ) for i, (start, end) in enumerate(ranges): if i == 0: if start != 0: raise ValidationError("First tier must start at 0") else: diff = start - ranges[i - 1][1] if diff != Decimal(0) and diff != Decimal(1): raise ValidationError( "Tier ranges must be continuous or separated by 1" ) if i != len(ranges) - 1: if end is None: raise ValidationError("Only last tier can be open ended") super().save(*args, **kwargs) def calculate_revenue( self, usage: float, prev_tier_end=False, bulk_pricing_enabled=False ): # if division_factor is None: # division_factor = len(usage_dict) revenue = 0 discontinuous_range = ( prev_tier_end != self.range_start and prev_tier_end is not None ) # for usage in usage_dict.values(): usage = convert_to_decimal(usage) if ( bulk_pricing_enabled and self.range_end is not None and self.range_end <= usage ): return revenue if bulk_pricing_enabled: usage_in_range = self.range_start <= usage else: usage_in_range = ( self.range_start <= usage if discontinuous_range else self.range_start < usage or self.range_start == 0 ) if usage_in_range: if self.type == PriceTier.PriceTierType.FLAT: revenue += self.cost_per_batch return revenue if self.type == PriceTier.PriceTierType.PER_UNIT: if bulk_pricing_enabled: billable_units = usage elif self.range_end is not None: billable_units = min( usage - self.range_start, self.range_end - self.range_start ) else: billable_units = usage - self.range_start if discontinuous_range: billable_units += 1 billable_batches = billable_units / self.metric_units_per_batch if self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_UP: billable_batches = math.ceil(billable_batches) elif self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_DOWN: billable_batches = math.floor(billable_batches) elif ( self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_NEAREST ): billable_batches = round(billable_batches) revenue += self.cost_per_batch * billable_batches return revenue class PlanComponent(models.Model): class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="plan_components", null=True, ) usage_component_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) billable_metric = models.ForeignKey( Metric, on_delete=models.CASCADE, related_name="+", null=True, blank=True, ) plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="plan_components", null=True, blank=True, ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="components", null=True, blank=True, ) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) fixed_charge = models.OneToOneField( ComponentFixedCharge, on_delete=models.SET_NULL, related_name="component", null=True, ) bulk_pricing_enabled = models.BooleanField(default=False) def __str__(self): return str(self.billable_metric) def save(self, *args, **kwargs): if self.pricing_unit is None and self.plan_version is not None: self.pricing_unit = self.plan_version.currency super().save(*args, **kwargs) def convert_length_label_to_value(label): label_map = { PlanComponent.IntervalLengthType.DAY.label: PlanComponent.IntervalLengthType.DAY, PlanComponent.IntervalLengthType.WEEK.label: PlanComponent.IntervalLengthType.WEEK, PlanComponent.IntervalLengthType.MONTH.label: PlanComponent.IntervalLengthType.MONTH, PlanComponent.IntervalLengthType.YEAR.label: PlanComponent.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_component_invoicing_dates( self, subscription_record, override_start_date=None ): # FOR PLAN COMPONENTS start_date = override_start_date or subscription_record.start_date end_date = subscription_record.end_date if self.invoicing_interval_unit is None: return [end_date] unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", } interval_delta = relativedelta( **{ unit_map[self.invoicing_interval_unit]: self.invoicing_interval_count or 1 } ) invoicing_dates = [] invoicing_date = start_date while invoicing_date < end_date: invoicing_date += interval_delta append_date = min(invoicing_date, end_date) invoicing_dates.append(append_date) return invoicing_dates def get_component_reset_dates(self, subscription_record, override_start_date=None): # FOR PLAN COMPONENTS sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date if override_start_date: range_start_date = override_start_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): start = reset_dates[i] if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges def calculate_total_revenue( self, billing_record, prepaid_units=None ) -> UsageRevenueSummary: assert isinstance( billing_record, BillingRecord ), "billing_record must be a BillingRecord" billable_metric = self.billable_metric usage_qty = billable_metric.get_billing_record_total_billable_usage( billing_record ) revenue = self.tier_rating_function(usage_qty) latest_component_charge = self.component_charge_records.order_by( "-start_date" ).first() if latest_component_charge is not None: revenue_from_prepaid_units = self.tier_rating_function(prepaid_units) revenue = max(revenue - revenue_from_prepaid_units, 0) return {"revenue": revenue, "usage_qty": usage_qty} def tier_rating_function(self, usage_qty): revenue = 0 tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: # this is for determining whether this is a continuous or discontinuous range prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( usage_qty, prev_tier_end=prev_tier_end, bulk_pricing_enabled=self.bulk_pricing_enabled, ) else: tier_revenue = tier.calculate_revenue( usage_qty, bulk_pricing_enabled=self.bulk_pricing_enabled ) revenue += tier_revenue revenue = convert_to_decimal(revenue) return revenue def calculate_revenue_per_day( self, billing_record ) -> dict[datetime.datetime, UsageRevenueSummary]: assert isinstance(billing_record, BillingRecord) billable_metric = self.billable_metric usage_per_day = billable_metric.get_billing_record_daily_billable_usage( billing_record ) results = {} for period in dates_bwn_two_dts( billing_record.start_date, billing_record.end_date ): period = convert_to_date(period) results[period] = {"revenue": Decimal(0), "usage_qty": Decimal(0)} running_total_revenue = Decimal(0) running_total_usage = Decimal(0) for date, usage_qty in usage_per_day.items(): date = convert_to_date(date) usage_qty = convert_to_decimal(usage_qty) running_total_usage += usage_qty revenue = Decimal(0) tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( running_total_usage, prev_tier_end=prev_tier_end ) else: tier_revenue = tier.calculate_revenue(running_total_usage) revenue += convert_to_decimal(tier_revenue) date_revenue = revenue - running_total_revenue running_total_revenue += date_revenue if date in results: results[date]["revenue"] += date_revenue results[date]["usage_qty"] += usage_qty return results class Feature(models.Model): feature_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="features" ) feature_name = models.CharField(max_length=50, blank=False) feature_description = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "feature_name"], name="unique_feature" ) ] def __str__(self): return str(self.feature_name) class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status class InvoiceLineItem(models.Model): invoice_line_item_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoice_line_items", null=True, ) name = models.CharField(max_length=100) start_date = models.DateTimeField(max_length=100, default=now_utc) end_date = models.DateTimeField(max_length=100, default=now_utc) quantity = models.DecimalField( decimal_places=10, max_digits=20, null=True, blank=True, validators=[MinValueValidator(0)], ) base = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Base price of the line item. This is the price before any adjustments are applied.", ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Amount of the line item. This is the price after any adjustments are applied.", ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="line_items", null=True, blank=True, ) billing_type = models.CharField( max_length=40, choices=INVOICE_CHARGE_TIMING_TYPE.choices, blank=True, null=True ) chargeable_item_type = models.CharField( max_length=40, choices=CHARGEABLE_ITEM_TYPE.choices, blank=True, null=True ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, null=True, related_name="line_items" ) associated_plan_version = models.ForeignKey( "PlanVersion", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_subscription_record = models.ForeignKey( "SubscriptionRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_billing_record = models.ForeignKey( "BillingRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) metadata = models.JSONField(default=dict, blank=True, null=True) def __str__(self): return self.name + " " + str(self.invoice.invoice_number) + f"[{self.base}]" def save(self, *args, **kwargs): self.amount = self.base + sum( [adjustment.amount for adjustment in self.adjustments.all()] ) super().save(*args, **kwargs) class APIToken(AbstractAPIKey): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys" ) class Meta(AbstractAPIKey.Meta): verbose_name = "API Token" verbose_name_plural = "API Tokens" def __str__(self): return str(self.name) + " " + str(self.organization.organization_name) class TeamInviteToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_invite_token" ) team = models.ForeignKey( Team, on_delete=models.CASCADE, related_name="team_invite_token" ) email = models.EmailField() token = models.SlugField(max_length=250, default=uuid.uuid4) expire_at = models.DateTimeField(default=now_plus_day, null=False, blank=False) def __str__(self): return str(self.email) + " - " + str(self.team) class RecurringCharge(models.Model): class ChargeTimingType(models.IntegerChoices): IN_ADVANCE = (1, "in_advance") IN_ARREARS = (2, "in_arrears") class ChargeBehaviorType(models.IntegerChoices): PRORATE = (1, "prorate") CHARGE_FULL = (2, "full") class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") recurring_charge_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="recurring_charges", ) name = models.TextField() plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="recurring_charges", ) charge_timing = models.PositiveSmallIntegerField( choices=ChargeTimingType.choices, default=ChargeTimingType.IN_ADVANCE ) charge_behavior = models.PositiveSmallIntegerField( choices=ChargeBehaviorType.choices, default=ChargeBehaviorType.PRORATE ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="recurring_charges", null=True, ) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) def __str__(self): return self.name + " [" + str(self.plan_version) + "]" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "plan_version", "name"], name="unique_recurring_charge_name_in_plan_version", ) ] def convert_length_label_to_value(label): label_map = { RecurringCharge.IntervalLengthType.DAY.label: RecurringCharge.IntervalLengthType.DAY, RecurringCharge.IntervalLengthType.WEEK.label: RecurringCharge.IntervalLengthType.WEEK, RecurringCharge.IntervalLengthType.MONTH.label: RecurringCharge.IntervalLengthType.MONTH, RecurringCharge.IntervalLengthType.YEAR.label: RecurringCharge.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_recurring_charge_invoicing_dates( self, subscription_record, append_range_start=False ): # FOR RECURRIG CHARGES # first we get the actual star tdate and end date of this subscription. However, if this is an addon, we need to calculate the periods w.r.t the parent subscription sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date invoicing_interval_unit = self.invoicing_interval_unit invoicing_interval_count = self.invoicing_interval_count # if we don't have a sub-plan length invoicing interval, use the plan length if not invoicing_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. invoicing_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if invoicing_interval_unit == PLAN_DURATION.QUARTERLY: invoicing_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[invoicing_interval_unit]: invoicing_interval_count or 1} ) invoicing_dates = [] invoicing_date = range_start_date # now generate invoicing dates while invoicing_date < range_end_date: invoicing_date += interval_delta append_date = min(invoicing_date, range_end_date) invoicing_dates.append(append_date) # purge the ones that don't match up with the real duration, and add the start + end dates invoicing_dates = { x for x in invoicing_dates if x >= sr_start_date and x <= sr_end_date } if append_range_start: invoicing_dates = invoicing_dates | {sr_start_date} invoicing_dates = invoicing_dates | {sr_end_date} invoicing_dates = sorted(list(invoicing_dates)) return invoicing_dates def get_recurring_charge_reset_dates(self, subscription_record): # FOR RECURRIG CHARGES sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): if sr_start_date > reset_dates[i]: continue start = max(reset_dates[i], sr_start_date) if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges class PlanVersion(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plan_versions", ) version = models.PositiveSmallIntegerField(default=1) version_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) localized_name = models.TextField(null=True, blank=True, default=None) plan = models.ForeignKey("Plan", on_delete=models.CASCADE, related_name="versions") created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plan_versions", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) # BILLING SCHEDULE day_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(31)], null=True, blank=True, ) month_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True, ) replace_with = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) transition_to = models.ForeignKey( "Plan", on_delete=models.SET_NULL, null=True, blank=True, related_name="transition_from", ) addon_spec = models.OneToOneField( "AddOnSpecification", on_delete=models.SET_NULL, related_name="plan_version", null=True, blank=True, ) active_from = models.DateTimeField(null=True, default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # PRICING features = models.ManyToManyField(Feature, blank=True) price_adjustment = models.ForeignKey( "PriceAdjustment", on_delete=models.SET_NULL, null=True, blank=True ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="versions", null=True, blank=True, ) # MISC is_custom = models.BooleanField(default=False) target_customers = models.ManyToManyField(Customer, related_name="plan_versions") objects = PlanVersionManager() plan_versions = RegularPlanVersionManager() addon_versions = AddOnPlanVersionManager() deleted_objects = DeletedPlanVersionManager() class Meta: constraints = [ models.UniqueConstraint( fields=["plan", "version", "currency"], name="unique_plan_version_per_currency", condition=Q(is_custom=False), ), ] indexes = [ models.Index(fields=["organization", "plan"]), models.Index(fields=["organization", "version_id"]), ] def __str__(self) -> str: if self.localized_name is not None: return self.localized_name return str(self.plan) def num_active_subs(self): cnt = self.subscription_records.active().count() return cnt def is_active(self, time=None): if time is None: time = now_utc() return self.active_from <= time and ( self.active_to is None or self.active_to > time ) def get_status(self) -> PLAN_VERSION_STATUS: now = now_utc() if self.deleted is not None: return PLAN_VERSION_STATUS.DELETED if not self.active_from: return PLAN_VERSION_STATUS.INACTIVE if self.active_from <= now: if self.active_to is None or self.active_to > now: return PLAN_VERSION_STATUS.ACTIVE else: n_active_subs = self.num_active_subs() if self.replace_with is None: if n_active_subs > 0: # SHOULD NEVER HAPPEN. EXPIRED PLAN, ACTIVE SUBS, NO REPLACEMENT return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE elif self.replace_with == self: if n_active_subs > 0: return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE else: if n_active_subs > 0: return PLAN_VERSION_STATUS.RETIRING else: return PLAN_VERSION_STATUS.INACTIVE else: return PLAN_VERSION_STATUS.INACTIVE class PriceAdjustment(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="price_adjustments" ) price_adjustment_name = models.CharField(max_length=100) price_adjustment_description = models.TextField(blank=True, null=True) price_adjustment_type = models.CharField( max_length=40, choices=PRICE_ADJUSTMENT_TYPE.choices ) price_adjustment_amount = models.DecimalField( max_digits=20, decimal_places=10, ) def __str__(self): if self.price_adjustment_name != "": return str(self.price_adjustment_name) else: return ( str(round(self.price_adjustment_amount, 2)) + " " + str(self.price_adjustment_type) ) def apply(self, amount): if self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PERCENTAGE: return amount * (1 + self.price_adjustment_amount / 100) elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.FIXED: return amount + self.price_adjustment_amount elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PRICE_OVERRIDE: return self.price_adjustment_amount class Plan(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plans" ) plan_name = models.TextField(help_text="Name of the plan") plan_description = models.TextField( help_text="Description of the plan", blank=True, null=True ) plan_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plans", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) is_addon = models.BooleanField(default=False) # BILLING taxjar_code = models.TextField(max_length=30, null=True, blank=True) plan_duration = models.CharField( choices=PLAN_DURATION.choices, max_length=40, help_text="Duration of the plan", null=True, ) active_from = models.DateTimeField(default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # MISC tags = models.ManyToManyField("Tag", blank=True, related_name="plans") objects = BasePlanManager() plans = RegularPlanManager() addons = AddOnPlanManager() deleted_objects = DeletedPlanManager() history = HistoricalRecords() # USELESS RN parent_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product_plans", null=True, blank=True, help_text="The product that this plan belongs to", ) class Meta: indexes = [ models.Index(fields=["organization", "plan_id"]), ] def __str__(self): return self.plan_name def add_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) def remove_tags(self, tags): existing_tags = self.tags.all() tags_lower = [tag["tag_name"].lower() for tag in tags] for existing_tag in existing_tags: if existing_tag.tag_name.lower() in tags_lower: self.tags.remove(existing_tag) def set_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] new_tag_names_lower = [tag["tag_name"].lower() for tag in tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) for existing_tag in existing_tags: if existing_tag.tag_name.lower() not in new_tag_names_lower: self.tags.remove(existing_tag) def active_subs_by_version(self): versions = self.versions.all().prefetch_related("subscription_records") now = now_utc() versions_count = versions.annotate( active_subscriptions=Count( "subscription_record", filter=Q( subscription_record__start_date__lte=now, subscription_record__end_date__gte=now, ), output_field=models.IntegerField(), ) ) return versions_count def get_version_for_customer(self, customer) -> Optional[PlanVersion]: versions = self.versions.active().prefetch_related( "subscription_records", "target_customers" ) # rules are as follows: # 1. if there is only one version, return it # 2. custom plans, preferring the customer's preferred currency # 3. filter down to the customer's preferred currency # 4. filter down to the organization's preferred currency if versions.count() == 0: return None elif versions.count() == 1: return versions.first() else: customer_target_plans = customer.plan_versions.filter(plan=self) customer_target_plan_in_customer_currency = customer_target_plans.filter( currency=customer.default_currency ) customer_target_plan_in_org_currency = customer_target_plans.filter( currency=customer.organization.default_currency ) if customer_target_plans.count() == 1: return customer_target_plans.first() elif customer_target_plan_in_customer_currency.count() == 1: return customer_target_plan_in_customer_currency.first() elif customer_target_plan_in_customer_currency.count() > 1: return None # DO NOT randomly choose a plan if multiple match elif customer_target_plan_in_org_currency.count() == 1: return customer_target_plan_in_org_currency.first() elif customer_target_plan_in_org_currency.count() > 1: return None # if we get here that means there are no customer specific plans versions_in_customer_currency = versions.filter( currency=customer.default_currency ) if versions_in_customer_currency.count() == 1: return versions_in_customer_currency.first() elif versions_in_customer_currency.count() > 1: return None versions_in_org_currency = versions.filter( currency=customer.organization.default_currency ) if versions_in_org_currency.count() == 1: return versions_in_org_currency.first() elif versions_in_org_currency.count() > 1: return None return None class ExternalPlanLink(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="external_plan_links", ) plan = models.ForeignKey( Plan, on_delete=models.CASCADE, related_name="external_links" ) source = models.CharField(choices=PAYMENT_PROCESSORS.choices, max_length=40) external_plan_id = models.CharField(max_length=100) def __str__(self): return f"{self.plan} - {self.source} - {self.external_plan_id}" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "source", "external_plan_id"], name="unique_external_plan_link", ) ] class SubscriptionRecord(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="subscription_records", ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=False, related_name="subscription_records", help_text="The customer object associated with this subscription.", ) billing_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, null=True, related_name="subscription_records", related_query_name="subscription_record", help_text="The plan associated with this subscription.", ) usage_start_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) end_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) auto_renew = models.BooleanField( default=True, help_text="Whether the subscription automatically renews. Defaults to true.", ) is_new = models.BooleanField( default=True, help_text="Whether this subscription came from a renewal or from a first-time. Defaults to true on creation.", ) subscription_record_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) subscription_filters = ArrayField( ArrayField( models.TextField(blank=False, null=False), size=2, ), default=list, ) invoice_usage_charges = models.BooleanField(default=True) flat_fee_behavior = models.CharField( choices=FLAT_FEE_BEHAVIOR.choices, max_length=20, null=True, default=None ) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.CASCADE, related_name="addon_subscription_records", help_text="The parent subscription record.", ) quantity = models.PositiveIntegerField(default=1) metadata = models.JSONField(default=dict, blank=True) stripe_subscription_id = models.TextField(null=True, blank=True, default=None) # managers etc objects = SubscriptionRecordManager() addon_objects = AddOnSubscriptionRecordManager() base_objects = BaseSubscriptionRecordManager() stripe_objects = StripeSubscriptionRecordManager() history = HistoricalRecords() class Meta: constraints = [ CheckConstraint( check=Q(start_date__lte=F("end_date")), name="end_date_gte_start_date" ), CheckConstraint(check=Q(quantity__gt=0), name="quantity_gt_0"), # check if stripe subscription id is null, then billing plan is not null, and vice versa CheckConstraint( check=( Q(stripe_subscription_id__isnull=False) & Q(billing_plan__isnull=True) ) | ( Q(stripe_subscription_id__isnull=True) & Q(billing_plan__isnull=False) ), name="stripe_subscription_id_xor_billing_plan", ), ] def __str__(self): addon = "[ADDON] " if self.billing_plan.addon_spec else "" if self.stripe_subscription_id: plan_name = "Stripe Subscription {}".format(self.stripe_subscription_id) else: plan_name = self.billing_plan.plan.plan_name return f"{addon}{self.customer.customer_name} {plan_name} : {self.start_date.date()} to {self.end_date.date()}" def create_subscription_record( start_date, end_date, billing_plan, customer, organization, subscription_filters=None, is_new=True, quantity=1, component_fixed_charges_initial_units=None, do_generate_invoice=True, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } assert ( billing_plan.addon_spec is None ), "Cannot create a base subscription record with an addon plan" sr = SubscriptionRecord.objects.create( start_date=start_date, end_date=end_date, billing_plan=billing_plan, customer=customer, organization=organization, subscription_filters=subscription_filters, is_new=is_new, quantity=quantity, ) for component in sr.billing_plan.plan_components.all(): metric = component.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(component, **kwargs) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) if do_generate_invoice: generate_invoice(sr) return sr def create_addon_subscription_record( parent_subscription_record, addon_billing_plan, quantity=1, ): from metering_billing.invoice import generate_invoice now = now_utc() assert ( addon_billing_plan.addon_spec is not None ), "Cannot create an addon subscription record with a base plan" sr = SubscriptionRecord.objects.create( parent=parent_subscription_record, start_date=now, end_date=parent_subscription_record.end_date, billing_plan=addon_billing_plan, customer=parent_subscription_record.customer, organization=parent_subscription_record.organization, subscription_filters=parent_subscription_record.subscription_filters, is_new=True, quantity=quantity, auto_renew=addon_billing_plan.addon_spec.billing_frequency == AddOnSpecification.BillingFrequency.RECURRING, ) for component in sr.billing_plan.plan_components.all(): sr._create_component_billing_records(component) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) generate_invoice(sr) return sr def _create_component_billing_records( self, component, override_start_date=None, initial_units=None, ignore_prepaid=False, fail_on_no_prepaid=True, ): prepaid_charge = component.fixed_charge invoicing_dates = component.get_component_invoicing_dates( self, override_start_date ) reset_ranges = component.get_component_reset_dates(self, override_start_date) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, component=component, start_date=start_date, end_date=end_date, invoicing_dates=br_invoicing_dates, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) new_invoicing_dates = set(br_invoicing_dates) if prepaid_charge and not ignore_prepaid: units = initial_units or prepaid_charge.units if units is None and fail_on_no_prepaid: raise PrepaymentMissingUnits( "No units specified for prepayment. This is usually an input error but may possibly be caused by inconsistent state in the backend." ) if units: ComponentChargeRecord.objects.create( organization=self.organization, billing_record=br, component_charge=prepaid_charge, component=component, start_date=start_date, end_date=end_date, units=units, ) new_invoicing_dates |= {start_date} new_invoicing_dates = sorted(list(new_invoicing_dates)) if new_invoicing_dates != br_invoicing_dates: br.invoicing_dates = new_invoicing_dates br.next_invoicing_date = new_invoicing_dates[0] br.save() brs.append(br) return brs def _create_recurring_charge_billing_records(self, recurring_charge): # first thign we want to see is if we need to charge "in advance" at all, that will # affect the way we calculate the reset ranges and invociing dates append_range_start = False if ( recurring_charge.charge_timing == RecurringCharge.ChargeTimingType.IN_ADVANCE ): addon_spec = recurring_charge.plan_version.addon_spec if ( addon_spec and addon_spec.flat_fee_invoicing_behavior_on_attach == AddOnSpecification.FlatFeeInvoicingBehaviorOnAttach.INVOICE_ON_SUBSCRIPTION_END ): # this is the ONLY case where its in advance and we don't want to append the range start. in this case they explicitly do not want to charge the flat fee on attach append_range_start = False else: append_range_start = True invoicing_dates = recurring_charge.get_recurring_charge_invoicing_dates( self, append_range_start ) reset_ranges = recurring_charge.get_recurring_charge_reset_dates(self) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, recurring_charge=recurring_charge, invoicing_dates=br_invoicing_dates, start_date=start_date, end_date=end_date, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) brs.append(br) return brs def save(self, *args, **kwargs): if self.subscription_filters is None: self.subscription_filters = [] now = now_utc() timezone = self.customer.timezone if not self.end_date: day_anchor, month_anchor = ( self.billing_plan.day_anchor, self.billing_plan.month_anchor, ) self.end_date = calculate_end_date( self.billing_plan.plan.plan_duration, self.start_date, timezone, day_anchor=day_anchor, month_anchor=month_anchor, ) new = self._state.adding is True if new: new_filters = set(tuple(x) for x in self.subscription_filters) overlapping_subscriptions = SubscriptionRecord.objects.filter( Q(start_date__range=(self.start_date, self.end_date)) | Q(end_date__range=(self.start_date, self.end_date)), organization=self.organization, customer=self.customer, billing_plan=self.billing_plan, ) for subscription in overlapping_subscriptions: old_filters = set(tuple(x) for x in subscription.subscription_filters) if old_filters.issubset(new_filters) or new_filters.issubset( old_filters ): raise OverlappingPlans( f"Overlapping subscriptions with the same filters are not allowed. \n Plan: {self.billing_plan} \n Customer: {self.customer}. \n New dates: ({self.start_date, self.end_date}) \n New subscription_filters: {new_filters} \n Old dates: ({self.start_date, self.end_date}) \n Old subscription_filters: {list(old_filters)}" ) super(SubscriptionRecord, self).save(*args, **kwargs) if new: alerts = UsageAlert.objects.filter( organization=self.organization, plan_version=self.billing_plan ) now = now_utc() for alert in alerts: UsageAlertResult.objects.create( organization=self.organization, alert=alert, subscription_record=self, last_run_value=0, last_run_timestamp=now, ) def get_filters_dictionary(self): filters_dict = {f[0]: f[1] for f in self.subscription_filters} return filters_dict def amt_already_invoiced(self): billed_invoices = self.line_items.filter( ~Q(invoice__payment_status=Invoice.PaymentStatus.VOIDED) & ~Q(invoice__payment_status=Invoice.PaymentStatus.DRAFT), base__isnull=False, ).aggregate(tot=Sum("base"))["tot"] return billed_invoices or 0 def get_usage_and_revenue(self): sub_dict = {"components": []} # set up the billing plan for this subscription plan = self.billing_plan # set up other details of the subscription self.start_date self.end_date # extract other objects that we need when calculating usage self.customer plan_components_qs = plan.plan_components.all() # For each component of the plan, calculate usage/revenue for plan_component in plan_components_qs: plan_component_summary = plan_component.calculate_total_revenue(self) sub_dict["components"].append((plan_component.pk, plan_component_summary)) sub_dict["usage_amount_due"] = Decimal(0) for component_pk, component_dict in sub_dict["components"]: sub_dict["usage_amount_due"] += component_dict["revenue"] sub_dict["flat_amount_due"] = sum( x.amount for x in plan.recurring_charges.all() ) sub_dict["total_amount_due"] = ( sub_dict["flat_amount_due"] + sub_dict["usage_amount_due"] ) return sub_dict def cancel_subscription( self, bill_usage=True, flat_fee_behavior=FLAT_FEE_BEHAVIOR.CHARGE_FULL, invoice_now=True, ): from metering_billing.invoice import generate_invoice now = now_utc() if self.end_date <= now: logger.info("Subscription already ended.") raise SubscriptionAlreadyEnded self.flat_fee_behavior = flat_fee_behavior self.invoice_usage_charges = bill_usage self.auto_renew = False self.end_date = now self.save() for billing_record in self.billing_records.all(): billing_record.cancel_billing_record(now) addon_srs = [] for addon_sr in self.addon_subscription_records.filter(end_date__gt=now): addon_sr.cancel_subscription( bill_usage=bill_usage, flat_fee_behavior=flat_fee_behavior, invoice_now=False, ) addon_srs.append(addon_sr) srs = [self] + addon_srs if invoice_now: generate_invoice(srs) def turn_off_auto_renew(self): self.auto_renew = False self.save() def _billing_record_cancel_protocol(billing_record, cancel_date, invoice_now=True): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass else: # this means it's currently active billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now ) def _check_should_transfer_cancel_if_not( billing_record, cancel_date, invoice_now=True ): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() return False elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass return False return True def switch_plan( self, new_version, transfer_usage=True, invoice_now=True, component_fixed_charges_initial_units=None, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } # when switching a plan, there's a few things we need to take into account: # 1. flat fees dont transfer. Just end them. # 2. what does it mean for usage to transfer? Does it just mean the billing records for the old plan are cancelled and new ones are created for the new plan with a start date the same as previously? In the case we used to charge for x but no longer do, then perhaps in that case we do charge? If we weren;t doing the whole reset frequency thing anymore it would be awesome because we could just switch which plan component it points at and have the already billed for be a part of that. now = now_utc() sr = SubscriptionRecord.objects.create( organization=self.organization, customer=self.customer, billing_plan=new_version, start_date=now + relativedelta(microseconds=1), end_date=self.end_date, auto_renew=self.auto_renew, ) # current recurring_charge billing records must be canceled + billed for billing_record in self.billing_records.filter( recurring_charge__isnull=False, fully_billed=False ): # this is common enough that we made a method for it SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) # and now we generate the new recurring_charge billing records for recurring_charge in new_version.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) # same for component based billing records # so we're going to have to create a new billing record for each component, except if the metric coincides in the old plan and the new plan, then if transfer usage is true we have to do some wizardry to accomplish this # first a set of components we'll create from scratch... if we transfer usage from anywhere we'll remove it from this set pcs_to_create_charges_for = set(new_version.plan_components.all()) # dict of metrics for convenience new_version_metrics_map = { x.billable_metric: x for x in pcs_to_create_charges_for } for billing_record in self.billing_records.filter( component__isnull=False, fully_billed=False ): component = billing_record.component # if not transferring usage, simple, just cancel the billing record same as above if not transfer_usage: SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) else: metric = component.billable_metric if metric in new_version_metrics_map: # if the metric is in the new plan, we perform the surgery to switch the billing record to the new plan. Don't create from scratch. transfer = SubscriptionRecord._check_should_transfer_cancel_if_not( billing_record, now, invoice_now=invoice_now ) if transfer: new_component = new_version_metrics_map[metric] pcs_to_create_charges_for.remove(new_component) new_billing_records = sr._create_component_billing_records( new_component, override_start_date=billing_record.start_date, ignore_prepaid=True, ) override_billing_record = new_billing_records[0] # heres the surgery... open to improvements... this allows us to keep # info about what's been paid already though which is nice billing_record.subscription = sr billing_record.billing_plan = new_version billing_record.component = override_billing_record.component billing_record.start_date = override_billing_record.start_date billing_record.end_date = override_billing_record.end_date billing_record.unadjusted_duration_microseconds = ( override_billing_record.unadjusted_duration_microseconds ) billing_record.invoicing_dates = ( override_billing_record.invoicing_dates ) billing_record.next_invoicing_date = ( override_billing_record.next_invoicing_date ) billing_record.fully_billed = ( override_billing_record.fully_billed ) billing_record.save() charge_records = ( billing_record.component_charge_records.all().order_by( "start_date" ) ) for k, component_charge_record in enumerate(charge_records): new_component = override_billing_record.component component_charge_record.component = new_component component_charge_record.component_charge = ( new_component.charges.all().first() ) if k == len(charge_records) - 1: component_charge_record.end_date = ( billing_record.end_date ) component_charge_record.save() override_billing_record.delete() else: # if the metric is not in the new plan, we cancel the billing record SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) for pc in pcs_to_create_charges_for: metric = pc.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(pc, **kwargs) self.end_date = now self.auto_renew = False self.save() generate_invoice([self, sr]) return sr def calculate_earned_revenue_per_day(self): return_dict = {} for billing_record in self.billing_records.all(): br_dict = billing_record.calculate_earned_revenue_per_day() for key in br_dict: if key not in return_dict: return_dict[key] = br_dict[key] else: return_dict[key] += br_dict[key] return return_dict def delete_subscription(self, delete_time=None): if delete_time is None: delete_time = now_utc() self.end_date = delete_time self.auto_renew = False for billing_record in self.billing_records.all(): if billing_record.start_date >= delete_time: # straight up delete it billing_record.delete() else: # essentially all we have to do is set everythign as already billed # this means we won't generate invoices for it anymore billing_record.end_date = min(billing_record.end_date, delete_time) billing_record.fully_billed = True billing_record.save() for addon_subscription in self.addon_subscription_records.all(): addon_subscription.delete_subscription(delete_time=delete_time) self.save() class Backtest(models.Model): """ This model is used to store the results of a backtest. """ backtest_name = models.TextField() start_date = models.DateField() end_date = models.DateField() organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtests" ) time_created = models.DateTimeField(default=now_utc) backtest_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) kpis = models.JSONField(default=list) backtest_results = models.JSONField(default=dict, blank=True) status = models.CharField( choices=EXPERIMENT_STATUS.choices, default=EXPERIMENT_STATUS.RUNNING, max_length=40, ) def __str__(self): return f"{self.backtest_name} - {self.start_date}" class BacktestSubstitution(models.Model): """ This model is used to substitute a backtest for a live trading session. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtest_substitutions", null=True, ) backtest = models.ForeignKey( Backtest, on_delete=models.CASCADE, related_name="backtest_substitutions" ) original_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) new_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) def __str__(self): return f"{self.backtest}" class PricingUnit(models.Model): """ This model is used to store pricing units for a plan. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="pricing_units", ) code = models.CharField(max_length=10) name = models.TextField() symbol = models.CharField(max_length=10) custom = models.BooleanField(default=False) def __str__(self): ret = f"{self.code}" if self.symbol: ret += f"({self.symbol})" return ret class Meta: constraints = [ UniqueConstraint( fields=["organization", "code"], name="unique_code_per_org" ), UniqueConstraint( fields=["organization", "name"], name="unique_name_per_org" ), ] class CustomPricingUnitConversion(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="custom_pricing_unit_conversions", null=True, ) plan_version = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="pricing_unit_conversions" ) from_unit = models.ForeignKey( PricingUnit, on_delete=models.CASCADE, related_name="+" ) from_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) to_unit = models.ForeignKey(PricingUnit, on_delete=models.CASCADE, related_name="+") to_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) def run_generate_invoice(subscription_record_pk_set, **kwargs): from metering_billing.invoice import generate_invoice from metering_billing.models import SubscriptionRecord subscription_record_set = SubscriptionRecord.objects.filter( pk__in=subscription_record_pk_set, ) generate_invoice(subscription_record_set, **kwargs) def setup_demo4( organization_name, username=None, email=None, password=None, mode="create", org_type=Organization.OrganizationType.EXTERNAL_DEMO, ): if mode == "create": try: org = Organization.objects.get(organization_name=organization_name) Event.objects.filter(organization=org).delete() org.delete() logger.info("[DEMO4]: Deleted existing organization, replacing") except Organization.DoesNotExist: logger.info("[DEMO4]: creating from scratch") try: user = User.objects.get(username=username, email=email) except Exception: user = User.objects.create_user( username=username, email=email, password=password ) if user.organization is None: organization, _ = Organization.objects.get_or_create( organization_name=organization_name ) organization.organization_type = org_type user.organization = organization user.save() organization.save() elif mode == "regenerate": organization = Organization.objects.get(organization_name=organization_name) user = organization.users.all().first() WebhookEndpoint.objects.filter(organization=organization).delete() WebhookTrigger.objects.filter(organization=organization).delete() PlanVersion.objects.filter(organization=organization).delete() Plan.objects.filter(organization=organization).delete() Customer.objects.filter(organization=organization).delete() Event.objects.filter(organization=organization).delete() Metric.objects.filter(organization=organization).delete() Product.objects.filter(organization=organization).delete() CustomerBalanceAdjustment.objects.filter(organization=organization).delete() Feature.objects.filter(organization=organization).delete() Invoice.objects.filter(organization=organization).delete() APIToken.objects.filter(organization=organization).delete() TeamInviteToken.objects.filter(organization=organization).delete() PriceAdjustment.objects.filter(organization=organization).delete() ExternalPlanLink.objects.filter(organization=organization).delete() SubscriptionRecord.objects.filter(organization=organization).delete() Backtest.objects.filter(organization=organization).delete() PricingUnit.objects.filter(organization=organization).delete() NumericFilter.objects.filter(organization=organization).delete() CategoricalFilter.objects.filter(organization=organization).delete() PriceTier.objects.filter(organization=organization).delete() PlanComponent.objects.filter(organization=organization).delete() InvoiceLineItem.objects.filter(organization=organization).delete() BacktestSubstitution.objects.filter(organization=organization).delete() CustomPricingUnitConversion.objects.filter(organization=organization).delete() if user is None: organization.delete() return organization = user.organization big_customers = [] for _ in range(1): customer = Customer.objects.create( organization=organization, customer_name="BigCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) big_customers.append(customer) medium_customers = [] for _ in range(2): customer = Customer.objects.create( organization=organization, customer_name="MediumCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) medium_customers.append(customer) small_customers = [] for _ in range(4): customer = Customer.objects.create( organization=organization, customer_name="SmallCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) small_customers.append(customer) metrics_map = {} for property_name, usage_aggregation_type, billable_metric_name, name in zip( [None, "user_id"], ["count", "unique"], ["Analytics Events", "Unique Users Tracked"], ["calls", "unique_users"], ): validated_data = { "organization": organization, "event_name": "analytics_event", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.COUNTER, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric(validated_data) metrics_map[name] = metric for property_name, usage_aggregation_type, billable_metric_name, name in zip( [None, "recording_length"], [ "count", "sum", ], ["Session Recordings", "Session Recording Time"], ["session_recordings", "sum_time"], ): validated_data = { "organization": organization, "event_name": "session_recording", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.COUNTER, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric(validated_data) metrics_map[name] = metric for property_name, usage_aggregation_type, billable_metric_name, name in zip( ["qty"], ["max"], ["User Seats"], ["num_seats"] ): validated_data = { "organization": organization, "event_name": "log_num_seats", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.GAUGE, "event_type": EVENT_TYPE.TOTAL, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric(validated_data) metrics_map[name] = metric for property_name, usage_aggregation_type, billable_metric_name, name in zip( ["cost"], ["sum"], ["Server Costs"], ["server_costs"] ): validated_data = { "organization": organization, "event_name": "server_cost_logging", "property_name": property_name, "usage_aggregation_type": usage_aggregation_type, "billable_metric_name": billable_metric_name, "metric_type": METRIC_TYPE.COUNTER, "is_cost_metric": True, } metric = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric(validated_data) assert metric is not None metrics_map[name] = metric calls = metrics_map["calls"] metrics_map["unique_users"] session_recordings = metrics_map["session_recordings"] sum_time = metrics_map["sum_time"] num_seats = metrics_map["num_seats"] # SET THE BILLING PLANS plan = Plan.objects.create( plan_name="Free Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) free_bp = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=free_bp, amount=0, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=free_bp.currency, ) create_pc_and_tiers( organization, plan_version=free_bp, billable_metric=calls, free_units=50 ) create_pc_and_tiers( organization, plan_version=free_bp, billable_metric=num_seats, free_units=1, max_units=1, ) plan.save() plan = Plan.objects.create( plan_name="Events-only - Basic", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_basic_events = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_basic_events, amount=29, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_basic_events.currency, ) create_pc_and_tiers( organization, plan_version=bp_basic_events, billable_metric=calls, free_units=10, max_units=100, cost_per_batch=0.20, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_basic_events, billable_metric=num_seats, free_units=3, ) plan.save() plan = Plan.objects.create( plan_name="Events-only - Pro", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_pro_events = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_pro_events, amount=69, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_pro_events.currency, ) create_pc_and_tiers( organization, plan_version=bp_pro_events, billable_metric=calls, free_units=100, max_units=500, cost_per_batch=0.25, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_pro_events, billable_metric=num_seats, free_units=5, ) plan.save() plan = Plan.objects.create( plan_name="Events + Recordings - Basic", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_basic_both = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_basic_both, amount=59, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_basic_both.currency, ) create_pc_and_tiers( organization, plan_version=bp_basic_both, billable_metric=calls, free_units=10, max_units=100, cost_per_batch=0.20, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_basic_both, billable_metric=session_recordings, cost_per_batch=0.35, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_basic_both, billable_metric=num_seats, free_units=3, ) plan.save() plan = Plan.objects.create( plan_name="Events + Recordings - Pro", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_pro_both = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_pro_both, amount=119, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_pro_both.currency, ) create_pc_and_tiers( organization, plan_version=bp_pro_both, billable_metric=calls, free_units=100, max_units=500, cost_per_batch=0.25, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_pro_both, billable_metric=session_recordings, cost_per_batch=0.35, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_pro_both, billable_metric=num_seats, free_units=5, ) plan.save() plan = Plan.objects.create( plan_name="Experimental - Events + Recording Time", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) bp_experimental = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=bp_experimental, amount=89, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=bp_experimental.currency, ) create_pc_and_tiers( organization, plan_version=bp_experimental, billable_metric=calls, free_units=100, max_units=500, cost_per_batch=0.25, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_experimental, billable_metric=sum_time, cost_per_batch=0.35 / 60, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=bp_experimental, billable_metric=num_seats, free_units=5, ) plan.save() six_months_ago = now_utc() - relativedelta(months=6) - relativedelta(days=5) for cust_set_name, cust_set in [ ("big", big_customers), ("medium", medium_customers), ("small", small_customers), ]: plan_dict = { "big": { 0: bp_basic_both, 1: bp_basic_both, 2: bp_pro_both, 3: bp_pro_both, 4: bp_pro_both, 5: bp_pro_both, }, "medium": { 0: bp_basic_events, 1: bp_basic_both, 2: bp_pro_events, 3: bp_pro_events, 4: bp_pro_events, 5: bp_pro_events, }, "small": { 0: free_bp, 1: free_bp, 2: bp_basic_events, 3: bp_basic_events, 4: bp_basic_events, 5: bp_basic_events, }, } for i, customer in enumerate(cust_set): beginning = six_months_ago offset = np.random.randint(0, 30) beginning = beginning + relativedelta(days=offset) for months in range(6): time.time() sub_start = beginning + relativedelta(months=months) plan = plan_dict[cust_set_name][months] if cust_set_name == "big": if plan == bp_basic_both: n_analytics = max(min(int(random.gauss(80, 10) // 1), 100), 1) n_recordings = max(int(random.gauss(200, 20) // 1), 1) elif plan == bp_pro_both: n_analytics = max(min(int(random.gauss(400, 50) // 1), 500), 1) n_recordings = max(int(random.gauss(200, 20) // 1), 1) n_cust = 100 users_mean, users_sd = 4.5, 0.5 elif cust_set_name == "medium": if plan == bp_basic_events: n_analytics = max(min(int(random.gauss(80, 10) // 1), 100), 1) n_recordings = 0 elif plan == bp_pro_events: n_analytics = max(min(int(random.gauss(400, 50) // 1), 500), 1) n_recordings = 0 elif plan == bp_pro_both: n_analytics = max(min(int(random.gauss(400, 50) // 1), 500), 1) n_recordings = max(int(random.gauss(150, 10) // 1), 1) n_cust = 40 users_mean, users_sd = 3.5, 0.5 elif cust_set_name == "small": if plan == free_bp: n_analytics = max(int(random.gauss(20, 10) // 1), 50) n_recordings = 0 elif plan == bp_basic_events: n_analytics = max(min(int(random.gauss(80, 10) // 1), 100), 1) n_recordings = 0 n_cust = 10 users_mean, users_sd = 1.5, 0.5 sr = make_subscription_record( organization=organization, customer=customer, plan=plan, start_date=sub_start, is_new=months == 0, ) if n_analytics != 0: events = [] for i in range(n_analytics): dts = list(random_date(sr.start_date, sr.end_date, n_analytics)) user_ids = np.random.randint(1, n_cust, n_analytics) buttons_clicked = np.random.randint(1, 10, n_analytics) page = np.random.randint(1, 100, n_analytics) e = Event( organization=organization, event_name="analytics_event", properties={ "user_id": user_ids[i].item(), "buttons_clicked": buttons_clicked[i].item(), "page_url": f"https://www.example.com/{page[i].item()}", }, time_created=dts[i], idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) Event.objects.bulk_create(events) if n_recordings != 0: events = [] for i in range(n_recordings): dts = list( random_date(sr.start_date, sr.end_date, n_recordings) ) user_ids = np.random.randint(1, n_cust, n_recordings) recording_lengths = np.random.randint(1, 3600, n_recordings) e = Event( organization=organization, event_name="session_recording", properties={ "user_id": user_ids[i].item(), "recording_length": recording_lengths[i].item(), }, time_created=dts[i], idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) Event.objects.bulk_create(events) n_cost = (n_recordings + n_analytics) // 10 rnd = np.random.random(n_cost) * 10 baker.make( Event, organization=organization, event_name="server_cost_logging", properties=itertools.cycle( [ { "cost": rnd[i].item(), } for i in range(n_cost) ] ), time_created=random_date(sr.start_date, sr.end_date, n_cost), idempotency_id=itertools.cycle( [uuid.uuid4().hex for _ in range(n_cost)] ), _quantity=n_cost, cust_id=customer.customer_id, ) max_users = max( x.range_end for x in plan.plan_components.get( billable_metric=num_seats ).tiers.all() ) n = max(int(random.gauss(6, 1.5) // 1), 1) baker.make( Event, organization=organization, event_name="log_num_seats", properties=gaussian_users(n, users_mean, users_sd, max_users), time_created=random_date(sr.start_date, sr.end_date, n), idempotency_id=itertools.cycle( [str(uuid.uuid4().hex) for _ in range(n)] ), _quantity=n, cust_id=customer.customer_id, ) next_plan = plan_dict[cust_set_name].get(months + 1, plan) if months == 0: try: run_generate_invoice.delay( [sr.pk], issue_date=sr.start_date, ) except Exception as e: print(e) pass if months != 5: cur_replace_with = sr.billing_plan.replace_with sr.billing_plan.replace_with = next_plan sr.save() try: run_generate_invoice.delay( [sr.pk], issue_date=sr.end_date, charge_next_plan=True ) except Exception as e: print(e) pass sr.fully_billed = True sr.billing_plan.replace_with = cur_replace_with sr.save() time.time() now_utc() # backtest = Backtest.objects.create( # backtest_name=organization, # start_date="2022-08-01", # end_date="2022-11-01", # organization=organization, # time_created=now, # kpis=[BACKTEST_KPI.TOTAL_REVENUE], # ) # BacktestSubstitution.objects.create( # backtest=backtest, # original_plan=bp_pro_both, # new_plan=bp_experimental, # organization=organization, # ) # run_backtest.delay(backtest.backtest_id) return user
null
6,988
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( LightweightCustomerSerializer, LightweightMetricSerializer, LightweightPlanVersionSerializer, ) from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP from metering_billing.invoice import generate_invoice from metering_billing.models import ( Analysis, APIToken, Backtest, BacktestSubstitution, CategoricalFilter, ComponentFixedCharge, Customer, CustomerBalanceAdjustment, CustomPricingUnitConversion, Event, ExternalPlanLink, Feature, Invoice, InvoiceLineItem, Metric, NumericFilter, Organization, Plan, PlanComponent, PlanVersion, PriceAdjustment, PriceTier, PricingUnit, Product, RecurringCharge, SubscriptionRecord, TeamInviteToken, User, WebhookEndpoint, WebhookTrigger, ) from metering_billing.tasks import run_backtest, run_generate_invoice from metering_billing.utils import ( convert_to_decimal, date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_decimals_strings, now_utc, round_all_decimals_to_two_places, ) from metering_billing.utils.enums import ( ANALYSIS_KPI, BACKTEST_KPI, EVENT_TYPE, EXPERIMENT_STATUS, METRIC_AGGREGATION, METRIC_GRANULARITY, METRIC_STATUS, METRIC_TYPE, PLAN_DURATION, ) logger = logging.getLogger("django.server") def create_pc_and_tiers( organization, plan_version, billable_metric, max_units=None, free_units=None, cost_per_batch=None, metric_units_per_batch=None, ): pc = PlanComponent.objects.create( plan_version=plan_version, billable_metric=billable_metric, organization=organization, ) range_start = 0 if free_units is not None: PriceTier.objects.create( plan_component=pc, range_start=0, range_end=free_units, type=PriceTier.PriceTierType.FREE, organization=organization, ) range_start = free_units if cost_per_batch is not None: PriceTier.objects.create( plan_component=pc, range_start=range_start, range_end=max_units, type=PriceTier.PriceTierType.PER_UNIT, cost_per_batch=cost_per_batch, metric_units_per_batch=metric_units_per_batch, organization=organization, batch_rounding_type=PriceTier.BatchRoundingType.NO_ROUNDING, ) class Organization(models.Model): class OrganizationType(models.IntegerChoices): PRODUCTION = (1, "Production") DEVELOPMENT = (2, "Development") EXTERNAL_DEMO = (3, "Demo") INTERNAL_DEMO = (4, "Internal Demo") team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="organizations" ) organization_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization_name = models.TextField(blank=False, null=False) created = models.DateField(default=now_utc) organization_type = models.PositiveSmallIntegerField( choices=OrganizationType.choices, default=OrganizationType.DEVELOPMENT ) properties = models.JSONField(default=dict, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) # BILLING RELATED FIELDS default_payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) braintree_integration = models.ForeignKey( "BraintreeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="+", null=True, blank=True, help_text="The primary origin address for the organization", ) default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) # TAX RELATED FIELDS tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) tax_providers = TaxProviderListField(default=[TAX_PROVIDER.LOTUS]) # TIMEZONE RELATED FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) __original_timezone = None # SUBSCRIPTION RELATED FIELDS subscription_filter_keys = ArrayField( models.TextField(), default=list, blank=True, help_text="Allowed subscription filter keys", ) __original_subscription_filter_keys = None # PROVISIONING FIELDS webhooks_provisioned = models.BooleanField(default=False) currencies_provisioned = models.IntegerField(default=0) crm_settings_provisioned = models.BooleanField(default=False) # settings gen_cust_in_stripe_after_lotus = models.BooleanField(default=False) gen_cust_in_braintree_after_lotus = models.BooleanField(default=False) payment_grace_period = models.IntegerField(null=True, default=None) lotus_is_customer_source_for_salesforce = models.BooleanField(default=False) # HISTORY RELATED FIELDS history = HistoricalRecords() def __init__(self, *args, **kwargs): super(Organization, self).__init__(*args, **kwargs) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys class Meta: indexes = [ models.Index(fields=["organization_name"]), models.Index(fields=["organization_type"]), models.Index(fields=["organization_id"]), models.Index(fields=["team"]), ] def __str__(self): return self.organization_name def save(self, *args, **kwargs): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP new = self._state.adding is True # self._state.adding represents whether creating new instance or updating if self.timezone != self.__original_timezone and not new: num_updated = self.customers.filter(timezone_set=False).update( timezone=self.timezone ) if num_updated > 0: customer_ids = self.customers.filter(timezone_set=False).values_list( "id", flat=True ) customer_cache_keys = [f"tz_customer_{id}" for id in customer_ids] cache.delete_many(customer_cache_keys) if self.team is None: self.team = Team.objects.create(name=self.organization_name) if self.subscription_filter_keys is None: self.subscription_filter_keys = [] self.subscription_filter_keys = sorted( list( set(self.subscription_filter_keys).union( set(self.__original_subscription_filter_keys) ) ) ) super(Organization, self).save(*args, **kwargs) if self.subscription_filter_keys != self.__original_subscription_filter_keys: for metric in self.metrics.all(): METRIC_HANDLER_MAP[metric.metric_type].create_continuous_aggregate( metric, refresh=True ) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys if new: self.provision_currencies() if not self.default_currency: self.default_currency = PricingUnit.objects.get( organization=self, code="USD" ) self.save() if not self.webhooks_provisioned: self.provision_webhooks() def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_address(self) -> Address: if self.default_payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_organization_address(self) elif self.default_payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_organization_address(self) else: return self.address def provision_webhooks(self): if SVIX_CONNECTOR is not None and not self.webhooks_provisioned: logger.info("provisioning webhooks") svix = SVIX_CONNECTOR svix.application.create( ApplicationIn(uid=self.organization_id.hex, name=self.organization_name) ) self.webhooks_provisioned = True self.save() def provision_currencies(self): if SUPPORTED_CURRENCIES_VERSION != self.currencies_provisioned: for name, code, symbol in SUPPORTED_CURRENCIES: PricingUnit.objects.get_or_create( organization=self, code=code, name=name, symbol=symbol, custom=False ) PricingUnit.objects.filter( ~Q(code__in=[code for _, code, _ in SUPPORTED_CURRENCIES]), custom=False, organization=self, ).delete() self.currencies_provisioned = SUPPORTED_CURRENCIES_VERSION self.save() class User(AbstractUser): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="users", ) team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="users" ) email = models.EmailField(unique=True) history = HistoricalRecords() def save(self, *args, **kwargs): if not self.team and self.organization: self.team = self.organization.team super(User, self).save(*args, **kwargs) class Customer(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="customers" ) customer_name = models.TextField( blank=True, help_text="The display name of the customer", null=True, ) email = models.EmailField( max_length=100, help_text="The primary email address of the customer, must be the same as the email address used to create the customer in the payment provider", null=True, ) customer_id = models.TextField( default=customer_uuid, help_text="The id provided when creating the customer, we suggest matching with your internal customer id in your backend", null=True, ) uuidv5_customer_id = models.UUIDField( help_text="The v5 UUID generated from the customer_id. This is used for efficient lookups in the database, specifically for the Events table", null=True, ) properties = models.JSONField( default=dict, null=True, help_text="Extra metadata for the customer" ) deleted = models.DateTimeField( null=True, help_text="The date the customer was deleted" ) # BILLING RELATED FIELDS default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="customers", null=True, blank=True, help_text="The currency the customer will be invoiced in", ) shipping_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="shipping_customers", null=True, blank=True, help_text="The shipping address for the customer", ) billing_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="billing_customers", null=True, blank=True, help_text="The billing address for the customer", ) # TAX RELATED FIELDS tax_providers = TaxProviderListField(default=[]) tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) # TIMEZONE FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) timezone_set = models.BooleanField(default=False) # PAYMENT PROCESSOR FIELDS payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) braintree_integration = models.ForeignKey( "BraintreeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) salesforce_integration = models.OneToOneField( "UnifiedCRMCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customer", ) # HISTORY FIELDS created = models.DateTimeField(default=now_utc) history = HistoricalRecords() objects = BaseCustomerManager() deleted_objects = DeletedCustomerManager() class Meta: constraints = [ UniqueConstraint(fields=["organization", "email"], name="unique_email"), UniqueConstraint( fields=["organization", "customer_id"], name="unique_customer_id" ), ] def __str__(self) -> str: return str(self.customer_name) + " " + str(self.customer_id) def save(self, *args, **kwargs): if not self.default_currency: try: self.default_currency = ( self.organization.default_currency or PricingUnit.objects.get( code="USD", organization=self.organization ) ) except PricingUnit.DoesNotExist: self.default_currency = None super(Customer, self).save(*args, **kwargs) def get_active_subscription_records(self): active_subscription_records = self.subscription_records.active().filter( fully_billed=False, ) return active_subscription_records def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_usage_and_revenue(self): customer_subscriptions = ( SubscriptionRecord.objects.active() .filter( customer=self, organization=self.organization, ) .prefetch_related("billing_plan__plan_components") .prefetch_related("billing_plan__plan_components__billable_metric") .select_related("billing_plan") ) subscription_usages = {"subscriptions": [], "sub_objects": []} for subscription in customer_subscriptions: sub_dict = subscription.get_usage_and_revenue() del sub_dict["components"] sub_dict["billing_plan_name"] = subscription.billing_plan.plan.plan_name subscription_usages["subscriptions"].append(sub_dict) subscription_usages["sub_objects"].append(subscription) return subscription_usages def get_active_sub_drafts_revenue(self): from metering_billing.invoice import generate_invoice total = 0 sub_records = self.get_active_subscription_records() if sub_records is not None and len(sub_records) > 0: invs = generate_invoice( sub_records, draft=True, charge_next_plan=True, ) total += sum([inv.amount for inv in invs]) for inv in invs: inv.delete() return total def get_currency_balance(self, currency): now = now_utc() balance = self.customer_balance_adjustments.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), effective_at__lte=now, amount_currency=currency, ).aggregate(balance=Sum("amount"))["balance"] or Decimal(0) return balance def get_outstanding_revenue(self): unpaid_invoice_amount_due = ( self.invoices.filter(payment_status=Invoice.PaymentStatus.UNPAID) .aggregate(unpaid_inv_amount=Sum("amount")) .get("unpaid_inv_amount") ) total_amount_due = unpaid_invoice_amount_due or 0 return total_amount_due def get_billing_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="billing") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.billing_address def get_shipping_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="shipping") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.shipping_address class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=models.SET_NULL, related_name="+", null=True, blank=True ) cust_id = models.TextField(blank=True) uuidv5_customer_id = models.UUIDField() event_name = models.TextField( help_text="String name of the event, corresponds to definition in metrics", ) uuidv5_event_name = models.UUIDField() time_created = models.DateTimeField( help_text="The time that the event occured, represented as a datetime in RFC3339 in the UTC timezome." ) properties = models.JSONField( default=dict, blank=True, help_text="Extra metadata on the event that can be filtered and queried on in the metrics. All key value pairs should have string keys and values can be either strings or numbers. Place subscription filters in this object to specify which subscription the event should be tracked under", ) idempotency_id = models.TextField( default=event_uuid, help_text="A unique identifier for the specific event being passed in. Passing in a unique id allows Lotus to make sure no double counting occurs. We recommend using a UUID4. You can use the same idempotency_id again after 45 days.", primary_key=True, ) uuidv5_idempotency_id = models.UUIDField() inserted_at = models.DateTimeField(default=now_utc) objects = EventManager() class Meta: managed = False db_table = "metering_billing_usageevent" def __str__(self): return ( str(self.event_name)[:6] + "-" + str(self.cust_id)[:8] + "-" + str(self.time_created)[:10] + "-" + str(self.idempotency_id)[:6] ) class Metric(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="metrics", ) event_name = models.TextField( help_text="Name of the event that this metric is tracking." ) metric_type = models.CharField( max_length=20, choices=METRIC_TYPE.choices, default=METRIC_TYPE.COUNTER, help_text="The type of metric that this is. Please refer to our documentation for an explanation of the different types.", ) properties = models.JSONField(default=dict, blank=True, null=True) billable_metric_name = models.TextField(blank=True, null=True) metric_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) event_type = models.CharField( max_length=20, choices=EVENT_TYPE.choices, blank=True, null=True, help_text="Used only for metrics of type 'gauge'. Please refer to our documentation for an explanation of the different types.", ) # metric type specific usage_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.COUNT, help_text="The type of aggregation that should be used for this metric. Please refer to our documentation for an explanation of the different types.", ) billable_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.SUM, blank=True, null=True, ) property_name = models.TextField( blank=True, null=True, help_text="The name of the property of the event that should be used for this metric. Doesn't apply if the metric is of type 'counter' with an aggregation of count.", ) granularity = models.CharField( choices=METRIC_GRANULARITY.choices, default=METRIC_GRANULARITY.TOTAL, max_length=10, blank=True, null=True, help_text="The granularity of the metric. Only applies to metrics of type 'gauge' or 'rate'.", ) proration = models.CharField( choices=METRIC_GRANULARITY.choices, default=None, max_length=10, blank=True, null=True, help_text="The proration of the metric. Only applies to metrics of type 'gauge'.", ) is_cost_metric = models.BooleanField( default=False, help_text="Whether or not this metric is a cost metric (used to track costs to your business).", ) custom_sql = models.TextField( blank=True, null=True, help_text="A custom SQL query that can be used to define the metric. Please refer to our documentation for more information.", ) # filters numeric_filters = models.ManyToManyField(NumericFilter, blank=True) categorical_filters = models.ManyToManyField(CategoricalFilter, blank=True) # status status = models.CharField( choices=METRIC_STATUS.choices, max_length=40, default=METRIC_STATUS.ACTIVE ) mat_views_provisioned = models.BooleanField(default=False) # records history = HistoricalRecords() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "billable_metric_name"], condition=Q(status=METRIC_STATUS.ACTIVE), name="unique_org_billable_metric_name", ), ] + [ models.UniqueConstraint( fields=sorted( list( { "organization", "billable_metric_name", # nullable "event_name", "metric_type", "usage_aggregation_type", "billable_aggregation_type", # nullable "property_name", # nullable "granularity", # nullable "is_cost_metric", "custom_sql", # nullable } - {x for x in nullables} ) ), condition=Q( **{f"{nullable}__in": [None, ""] for nullable in sorted(nullables)} ) & Q(status=METRIC_STATUS.ACTIVE), name="uq_metric_w_null__" + "_".join( [ "_".join([x[:2] for x in nullable.split("_")]) for nullable in sorted(nullables) ] ), ) for nullables in itertools.chain( *map( lambda x: itertools.combinations( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], x, ), range( 0, len( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], ) + 1, ), ) ) ] indexes = [ models.Index(fields=["organization", "status"]), models.Index(fields=["organization", "is_cost_metric"]), models.Index(fields=["organization", "metric_id"]), ] def __str__(self): return self.billable_metric_name or "" def save(self, *args, **kwargs): super().save(*args, **kwargs) def delete_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.archive_metric(self) self.mat_views_provisioned = False self.save() def get_aggregation_type(self): return self.aggregation_type def get_billing_record_total_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_total_billable_usage(self, billing_record) return usage def get_billing_record_daily_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_daily_billable_usage(self, billing_record) return usage def get_billing_record_current_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_current_usage(self, billing_record) return usage def get_daily_total_usage( self, start_date: datetime.date, end_date: datetime.date, customer: Optional[Customer] = None, top_n: Optional[int] = None, ) -> dict[Union[Customer, Literal["Other"]], dict[datetime.date, Decimal]]: from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_daily_total_usage( self, start_date, end_date, customer, top_n ) return usage def refresh_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self, refresh=True) self.mat_views_provisioned = True self.save() def provision_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self) self.mat_views_provisioned = True self.save() class RecurringCharge(models.Model): class ChargeTimingType(models.IntegerChoices): IN_ADVANCE = (1, "in_advance") IN_ARREARS = (2, "in_arrears") class ChargeBehaviorType(models.IntegerChoices): PRORATE = (1, "prorate") CHARGE_FULL = (2, "full") class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") recurring_charge_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="recurring_charges", ) name = models.TextField() plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="recurring_charges", ) charge_timing = models.PositiveSmallIntegerField( choices=ChargeTimingType.choices, default=ChargeTimingType.IN_ADVANCE ) charge_behavior = models.PositiveSmallIntegerField( choices=ChargeBehaviorType.choices, default=ChargeBehaviorType.PRORATE ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="recurring_charges", null=True, ) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) def __str__(self): return self.name + " [" + str(self.plan_version) + "]" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "plan_version", "name"], name="unique_recurring_charge_name_in_plan_version", ) ] def convert_length_label_to_value(label): label_map = { RecurringCharge.IntervalLengthType.DAY.label: RecurringCharge.IntervalLengthType.DAY, RecurringCharge.IntervalLengthType.WEEK.label: RecurringCharge.IntervalLengthType.WEEK, RecurringCharge.IntervalLengthType.MONTH.label: RecurringCharge.IntervalLengthType.MONTH, RecurringCharge.IntervalLengthType.YEAR.label: RecurringCharge.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_recurring_charge_invoicing_dates( self, subscription_record, append_range_start=False ): # FOR RECURRIG CHARGES # first we get the actual star tdate and end date of this subscription. However, if this is an addon, we need to calculate the periods w.r.t the parent subscription sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date invoicing_interval_unit = self.invoicing_interval_unit invoicing_interval_count = self.invoicing_interval_count # if we don't have a sub-plan length invoicing interval, use the plan length if not invoicing_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. invoicing_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if invoicing_interval_unit == PLAN_DURATION.QUARTERLY: invoicing_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[invoicing_interval_unit]: invoicing_interval_count or 1} ) invoicing_dates = [] invoicing_date = range_start_date # now generate invoicing dates while invoicing_date < range_end_date: invoicing_date += interval_delta append_date = min(invoicing_date, range_end_date) invoicing_dates.append(append_date) # purge the ones that don't match up with the real duration, and add the start + end dates invoicing_dates = { x for x in invoicing_dates if x >= sr_start_date and x <= sr_end_date } if append_range_start: invoicing_dates = invoicing_dates | {sr_start_date} invoicing_dates = invoicing_dates | {sr_end_date} invoicing_dates = sorted(list(invoicing_dates)) return invoicing_dates def get_recurring_charge_reset_dates(self, subscription_record): # FOR RECURRIG CHARGES sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): if sr_start_date > reset_dates[i]: continue start = max(reset_dates[i], sr_start_date) if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges class PlanVersion(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plan_versions", ) version = models.PositiveSmallIntegerField(default=1) version_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) localized_name = models.TextField(null=True, blank=True, default=None) plan = models.ForeignKey("Plan", on_delete=models.CASCADE, related_name="versions") created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plan_versions", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) # BILLING SCHEDULE day_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(31)], null=True, blank=True, ) month_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True, ) replace_with = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) transition_to = models.ForeignKey( "Plan", on_delete=models.SET_NULL, null=True, blank=True, related_name="transition_from", ) addon_spec = models.OneToOneField( "AddOnSpecification", on_delete=models.SET_NULL, related_name="plan_version", null=True, blank=True, ) active_from = models.DateTimeField(null=True, default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # PRICING features = models.ManyToManyField(Feature, blank=True) price_adjustment = models.ForeignKey( "PriceAdjustment", on_delete=models.SET_NULL, null=True, blank=True ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="versions", null=True, blank=True, ) # MISC is_custom = models.BooleanField(default=False) target_customers = models.ManyToManyField(Customer, related_name="plan_versions") objects = PlanVersionManager() plan_versions = RegularPlanVersionManager() addon_versions = AddOnPlanVersionManager() deleted_objects = DeletedPlanVersionManager() class Meta: constraints = [ models.UniqueConstraint( fields=["plan", "version", "currency"], name="unique_plan_version_per_currency", condition=Q(is_custom=False), ), ] indexes = [ models.Index(fields=["organization", "plan"]), models.Index(fields=["organization", "version_id"]), ] def __str__(self) -> str: if self.localized_name is not None: return self.localized_name return str(self.plan) def num_active_subs(self): cnt = self.subscription_records.active().count() return cnt def is_active(self, time=None): if time is None: time = now_utc() return self.active_from <= time and ( self.active_to is None or self.active_to > time ) def get_status(self) -> PLAN_VERSION_STATUS: now = now_utc() if self.deleted is not None: return PLAN_VERSION_STATUS.DELETED if not self.active_from: return PLAN_VERSION_STATUS.INACTIVE if self.active_from <= now: if self.active_to is None or self.active_to > now: return PLAN_VERSION_STATUS.ACTIVE else: n_active_subs = self.num_active_subs() if self.replace_with is None: if n_active_subs > 0: # SHOULD NEVER HAPPEN. EXPIRED PLAN, ACTIVE SUBS, NO REPLACEMENT return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE elif self.replace_with == self: if n_active_subs > 0: return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE else: if n_active_subs > 0: return PLAN_VERSION_STATUS.RETIRING else: return PLAN_VERSION_STATUS.INACTIVE else: return PLAN_VERSION_STATUS.INACTIVE class Plan(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plans" ) plan_name = models.TextField(help_text="Name of the plan") plan_description = models.TextField( help_text="Description of the plan", blank=True, null=True ) plan_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plans", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) is_addon = models.BooleanField(default=False) # BILLING taxjar_code = models.TextField(max_length=30, null=True, blank=True) plan_duration = models.CharField( choices=PLAN_DURATION.choices, max_length=40, help_text="Duration of the plan", null=True, ) active_from = models.DateTimeField(default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # MISC tags = models.ManyToManyField("Tag", blank=True, related_name="plans") objects = BasePlanManager() plans = RegularPlanManager() addons = AddOnPlanManager() deleted_objects = DeletedPlanManager() history = HistoricalRecords() # USELESS RN parent_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product_plans", null=True, blank=True, help_text="The product that this plan belongs to", ) class Meta: indexes = [ models.Index(fields=["organization", "plan_id"]), ] def __str__(self): return self.plan_name def add_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) def remove_tags(self, tags): existing_tags = self.tags.all() tags_lower = [tag["tag_name"].lower() for tag in tags] for existing_tag in existing_tags: if existing_tag.tag_name.lower() in tags_lower: self.tags.remove(existing_tag) def set_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] new_tag_names_lower = [tag["tag_name"].lower() for tag in tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) for existing_tag in existing_tags: if existing_tag.tag_name.lower() not in new_tag_names_lower: self.tags.remove(existing_tag) def active_subs_by_version(self): versions = self.versions.all().prefetch_related("subscription_records") now = now_utc() versions_count = versions.annotate( active_subscriptions=Count( "subscription_record", filter=Q( subscription_record__start_date__lte=now, subscription_record__end_date__gte=now, ), output_field=models.IntegerField(), ) ) return versions_count def get_version_for_customer(self, customer) -> Optional[PlanVersion]: versions = self.versions.active().prefetch_related( "subscription_records", "target_customers" ) # rules are as follows: # 1. if there is only one version, return it # 2. custom plans, preferring the customer's preferred currency # 3. filter down to the customer's preferred currency # 4. filter down to the organization's preferred currency if versions.count() == 0: return None elif versions.count() == 1: return versions.first() else: customer_target_plans = customer.plan_versions.filter(plan=self) customer_target_plan_in_customer_currency = customer_target_plans.filter( currency=customer.default_currency ) customer_target_plan_in_org_currency = customer_target_plans.filter( currency=customer.organization.default_currency ) if customer_target_plans.count() == 1: return customer_target_plans.first() elif customer_target_plan_in_customer_currency.count() == 1: return customer_target_plan_in_customer_currency.first() elif customer_target_plan_in_customer_currency.count() > 1: return None # DO NOT randomly choose a plan if multiple match elif customer_target_plan_in_org_currency.count() == 1: return customer_target_plan_in_org_currency.first() elif customer_target_plan_in_org_currency.count() > 1: return None # if we get here that means there are no customer specific plans versions_in_customer_currency = versions.filter( currency=customer.default_currency ) if versions_in_customer_currency.count() == 1: return versions_in_customer_currency.first() elif versions_in_customer_currency.count() > 1: return None versions_in_org_currency = versions.filter( currency=customer.organization.default_currency ) if versions_in_org_currency.count() == 1: return versions_in_org_currency.first() elif versions_in_org_currency.count() > 1: return None return None class PricingUnit(models.Model): """ This model is used to store pricing units for a plan. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="pricing_units", ) code = models.CharField(max_length=10) name = models.TextField() symbol = models.CharField(max_length=10) custom = models.BooleanField(default=False) def __str__(self): ret = f"{self.code}" if self.symbol: ret += f"({self.symbol})" return ret class Meta: constraints = [ UniqueConstraint( fields=["organization", "code"], name="unique_code_per_org" ), UniqueConstraint( fields=["organization", "name"], name="unique_name_per_org" ), ] def setup_paas_demo( organization_name="paas", username="paas", email="paas@paas.com", password="paas", org_type=Organization.OrganizationType.EXTERNAL_DEMO, ): try: org = Organization.objects.get(organization_name=organization_name) Event.objects.filter(organization=org).delete() org.delete() logger.info("[PAAS DEMO]: Deleted existing organization, replacing") except Organization.DoesNotExist: logger.info("[PAAS DEMO]: creating from scratch") try: user = User.objects.get(username=username, email=email) except Exception: user = User.objects.create_user( username=username, email=email, password=password ) if user.organization is None: organization, _ = Organization.objects.get_or_create( organization_name=organization_name ) user.organization = organization organization.organization_type = org_type user.save() organization.save() organization = user.organization organization.subscription_filter_keys = ["shard_id"] big_customers = [] for _ in range(1): customer = Customer.objects.create( organization=organization, customer_name="BigCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) big_customers.append(customer) medium_customers = [] for _ in range(2): customer = Customer.objects.create( organization=organization, customer_name="MediumCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) medium_customers.append(customer) small_customers = [] for _ in range(5): customer = Customer.objects.create( organization=organization, customer_name="SmallCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)[:8]}@{str(uuid.uuid4().hex)[:8]}.com", ) small_customers.append(customer) ( valnodes, rpcnodes, ixnodes, evixnodes, tntxns, mntxns, tntxns_rate, mntxns_rate, ) = baker.make( Metric, organization=organization, event_name=itertools.cycle( [ "num_validators_change", "rpc_nodes_change", "indexer_nodes_change", "event_indexer_nodes_change", "testnet_transaction", "mainnet_transaction", "testnet_transaction", "mainnet_transaction", ] ), property_name=itertools.cycle(["change"] * 4 + [""] * 4), usage_aggregation_type=itertools.cycle( [METRIC_AGGREGATION.MAX] * 4 + [METRIC_AGGREGATION.COUNT] * 4 ), billable_metric_name=itertools.cycle( [ "Validator Nodes", "RPC Nodes", "Indexer Nodes", "Event Indexer Nodes", "Testnet Transactions", "Mainnet Transactions", "Ratelimit Testnet Transactions", "Ratelimit Mainnet Transactions", ] ), metric_type=itertools.cycle( [METRIC_TYPE.GAUGE] * 4 + [METRIC_TYPE.COUNTER] * 2 + [METRIC_TYPE.RATE] * 2 ), proration=itertools.cycle([METRIC_GRANULARITY.MINUTE] * 4 + [None] * 4), event_type=itertools.cycle([EVENT_TYPE.DELTA] * 4 + [None] * 4), billable_aggregation_type=itertools.cycle( [None] * 6 + [METRIC_AGGREGATION.MAX] * 2 ), granularity=itertools.cycle( [METRIC_GRANULARITY.MONTH] * 4 + [None] * 2 + [METRIC_GRANULARITY.HOUR] * 2 ), _quantity=8, ) plan = Plan.objects.create( plan_name="Basic Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) basic_plan = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=basic_plan, amount=125, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=basic_plan.currency, ) create_pc_and_tiers( organization, plan_version=basic_plan, billable_metric=tntxns, free_units=None, max_units=2000, cost_per_batch=0.05, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=basic_plan, billable_metric=tntxns_rate, free_units=50, ) plan.save() plan = Plan.objects.create( plan_name="Professional Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) professional_plan = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=professional_plan, amount=0, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=professional_plan.currency, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=valnodes, free_units=2, max_units=10, cost_per_batch=200, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=rpcnodes, free_units=2, max_units=10, cost_per_batch=200, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=ixnodes, free_units=2, max_units=10, cost_per_batch=200, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=evixnodes, free_units=2, max_units=10, cost_per_batch=200, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=tntxns, free_units=None, max_units=5000, cost_per_batch=0.05, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=tntxns_rate, free_units=50, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=mntxns, free_units=None, max_units=5000, cost_per_batch=0.25, metric_units_per_batch=1, ) create_pc_and_tiers( organization, plan_version=professional_plan, billable_metric=mntxns_rate, free_units=100, ) plan.save() for component in professional_plan.plan_components.all(): if component.billable_metric.metric_type == METRIC_TYPE.GAUGE: component.save()
null
6,989
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( LightweightCustomerSerializer, LightweightMetricSerializer, LightweightPlanVersionSerializer, ) from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP from metering_billing.invoice import generate_invoice from metering_billing.models import ( Analysis, APIToken, Backtest, BacktestSubstitution, CategoricalFilter, ComponentFixedCharge, Customer, CustomerBalanceAdjustment, CustomPricingUnitConversion, Event, ExternalPlanLink, Feature, Invoice, InvoiceLineItem, Metric, NumericFilter, Organization, Plan, PlanComponent, PlanVersion, PriceAdjustment, PriceTier, PricingUnit, Product, RecurringCharge, SubscriptionRecord, TeamInviteToken, User, WebhookEndpoint, WebhookTrigger, ) from metering_billing.tasks import run_backtest, run_generate_invoice from metering_billing.utils import ( convert_to_decimal, date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_decimals_strings, now_utc, round_all_decimals_to_two_places, ) from metering_billing.utils.enums import ( ANALYSIS_KPI, BACKTEST_KPI, EVENT_TYPE, EXPERIMENT_STATUS, METRIC_AGGREGATION, METRIC_GRANULARITY, METRIC_STATUS, METRIC_TYPE, PLAN_DURATION, ) logger = logging.getLogger("django.server") def random_date(start, end, n): """Generate a random datetime between `start` and `end`""" if type(start) is datetime.date: start = date_as_min_dt(start, timezone=pytz.UTC) if type(end) is datetime.date: end = date_as_max_dt(end, timezone=pytz.UTC) for _ in range(n): dt = start + relativedelta( # Get a random amount of seconds between `start` and `end` seconds=random.randint(0, int((end - start).total_seconds())), ) yield dt def make_subscription_record( organization, customer, plan, start_date, is_new, ): sr = SubscriptionRecord.create_subscription_record( start_date=start_date, end_date=None, billing_plan=plan, customer=customer, organization=organization, subscription_filters=None, is_new=is_new, quantity=1, do_generate_invoice=False, ) return sr def create_pc_plus_tiers_new(plan_versions, pcs_dict): for plan_version in plan_versions: for metric, pc_info in pcs_dict.items(): pc = PlanComponent.objects.create( plan_version=plan_version, billable_metric=metric, organization=plan_version.organization, pricing_unit=plan_version.currency, invoicing_interval_unit=pc_info.get("invoicing_interval_unit"), invoicing_interval_count=pc_info.get("invoicing_interval_count"), reset_interval_unit=pc_info.get("reset_interval_unit"), reset_interval_count=pc_info.get("reset_interval_count"), ) if pc_info.get("fixed_charge"): fc = ComponentFixedCharge.objects.create( organization=plan_version.organization, units=pc_info.get("units"), charge_behavior=pc_info.get("charge_behavior"), ) pc.fixed_charge = fc pc.save() if pc_info.get("tiers"): for tier in pc_info.get("tiers"): PriceTier.objects.create( plan_component=pc, range_start=tier.get("range_start"), range_end=tier.get("range_end"), type=tier.get("type"), cost_per_batch=tier.get("cost_per_batch"), metric_units_per_batch=tier.get("metric_units_per_batch", 1), organization=plan_version.organization, batch_rounding_type=tier.get("batch_rounding_type"), ) class LightweightCustomerSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = Customer fields = ( "customer_name", "email", "customer_id", ) extra_kwargs = { "customer_id": {"required": True, "read_only": True}, "customer_name": {"required": True, "read_only": True, "allow_null": True}, "email": {"required": True, "read_only": True}, } class LightweightPlanVersionSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = PlanVersion fields = ("plan_name", "plan_id", "version_id", "version") extra_kwargs = { "plan_id": {"required": True, "read_only": True}, "plan_name": {"required": True, "read_only": True}, "version_id": {"required": True, "read_only": True}, "version": {"required": True, "read_only": True}, } plan_name = serializers.SerializerMethodField() plan_id = PlanUUIDField(source="plan.plan_id") version_id = PlanVersionUUIDField(read_only=True) version = serializers.SerializerMethodField() def get_plan_name(self, obj) -> str: return str(obj) def get_version(self, obj) -> Union[int, Literal["custom_version"]]: if obj.version == 0: return "custom_version" else: return obj.version ) class LightweightMetricSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = Metric fields = ( "metric_id", "event_name", "metric_name", ) extra_kwargs = { "metric_id": {"required": True, "read_only": True, "allow_blank": False}, "event_name": {"required": True, "read_only": True}, "metric_name": {"required": True, "read_only": True}, } metric_id = MetricUUIDField() metric_name = serializers.CharField(source="billable_metric_name") ) ) ) METRIC_HANDLER_MAP = { METRIC_TYPE.COUNTER: CounterHandler, METRIC_TYPE.GAUGE: GaugeHandler, METRIC_TYPE.RATE: RateHandler, METRIC_TYPE.CUSTOM: CustomHandler, } def generate_invoice( subscription_records, draft=False, charge_next_plan=False, generate_next_subscription_record=False, issue_date=None, ): """ Generate an invoice for a subscription. IMPORTANT: addons must be passed explicitly as part of subscription_records, otherwise they will not be charged. """ from metering_billing.models import Invoice, PricingUnit from metering_billing.tasks import generate_invoice_pdf_async if not issue_date: issue_date = now_utc() if not isinstance(subscription_records, (QuerySet, Iterable)): subscription_records = [subscription_records] if len(subscription_records) == 0: return None try: customers = subscription_records.values("customer").distinct().count() except AttributeError: customers = len({x.customer for x in subscription_records}) assert ( customers == 1 ), "All subscription records must belong to the same customer when invoicing." try: organizations = subscription_records.values("organization").distinct().count() except AttributeError: organizations = len({x.organization for x in subscription_records}) assert ( organizations == 1 ), "All subscription records must belong to the same organization when invoicing." organization = subscription_records[0].organization customer = subscription_records[0].customer due_date = calculate_due_date(issue_date, organization) try: distinct_currencies_pks = ( subscription_records.order_by() .values_list("billing_plan__currency", flat=True) .distinct() ) distinct_currencies = PricingUnit.objects.filter(pk__in=distinct_currencies_pks) except AttributeError: distinct_currencies = {x.billing_plan.currency for x in subscription_records} invoices = {} for currency in distinct_currencies: # create kwargs for invoice invoice_kwargs = { "issue_date": issue_date, "organization": organization, "customer": customer, "payment_status": Invoice.PaymentStatus.DRAFT if draft else Invoice.PaymentStatus.UNPAID, "currency": currency, "due_date": due_date, } # Create the invoice invoice = Invoice.objects.create(**invoice_kwargs) invoices[currency] = invoice for subscription_record in subscription_records: invoice = invoices[subscription_record.billing_plan.currency] invoice.subscription_records.add(subscription_record) # flat fee calculation for current plan calculate_subscription_record_flat_fees(subscription_record, invoice, draft) # usage calculation calculate_subscription_record_usage_fees(subscription_record, invoice, draft) # next plan flat fee calculation next_bp = find_next_billing_plan(subscription_record) sr_renews = check_subscription_record_renews(subscription_record, issue_date) if sr_renews: if generate_next_subscription_record: # actually make one, when we're actually invoicing next_subscription_record = create_next_subscription_record( subscription_record, next_bp ) else: # this is just a placeholder e.g. for previewing draft invoices next_subscription_record = subscription_record if charge_next_plan: # this can be both for actual invoicing or just for drafts to see whats next charge_next_plan_flat_fee( subscription_record, next_subscription_record, next_bp, invoice, draft, ) return_list = [] for invoice in invoices.values(): if invoice.line_items.count() == 0: invoice.delete() continue apply_plan_discounts(invoice) apply_taxes(invoice, customer, organization, draft) apply_customer_balance_adjustments(invoice, customer, organization, draft) finalize_invoice_amount(invoice, draft) if not draft: new_inv = generate_external_payment_obj(invoice) if new_inv: invoice = new_inv for subscription_record in subscription_records: if subscription_record.end_date <= now_utc(): subscription_record.fully_billed = True subscription_record.save() try: generate_invoice_pdf_async.delay(invoice.pk) except Exception as e: sentry_sdk.capture_exception(e) invoice_created_webhook(invoice, organization) if kafka_producer: kafka_producer.produce_invoice(invoice) return_list.append(invoice) return return_list class Organization(models.Model): class OrganizationType(models.IntegerChoices): PRODUCTION = (1, "Production") DEVELOPMENT = (2, "Development") EXTERNAL_DEMO = (3, "Demo") INTERNAL_DEMO = (4, "Internal Demo") team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="organizations" ) organization_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization_name = models.TextField(blank=False, null=False) created = models.DateField(default=now_utc) organization_type = models.PositiveSmallIntegerField( choices=OrganizationType.choices, default=OrganizationType.DEVELOPMENT ) properties = models.JSONField(default=dict, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) # BILLING RELATED FIELDS default_payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) braintree_integration = models.ForeignKey( "BraintreeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="+", null=True, blank=True, help_text="The primary origin address for the organization", ) default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) # TAX RELATED FIELDS tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) tax_providers = TaxProviderListField(default=[TAX_PROVIDER.LOTUS]) # TIMEZONE RELATED FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) __original_timezone = None # SUBSCRIPTION RELATED FIELDS subscription_filter_keys = ArrayField( models.TextField(), default=list, blank=True, help_text="Allowed subscription filter keys", ) __original_subscription_filter_keys = None # PROVISIONING FIELDS webhooks_provisioned = models.BooleanField(default=False) currencies_provisioned = models.IntegerField(default=0) crm_settings_provisioned = models.BooleanField(default=False) # settings gen_cust_in_stripe_after_lotus = models.BooleanField(default=False) gen_cust_in_braintree_after_lotus = models.BooleanField(default=False) payment_grace_period = models.IntegerField(null=True, default=None) lotus_is_customer_source_for_salesforce = models.BooleanField(default=False) # HISTORY RELATED FIELDS history = HistoricalRecords() def __init__(self, *args, **kwargs): super(Organization, self).__init__(*args, **kwargs) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys class Meta: indexes = [ models.Index(fields=["organization_name"]), models.Index(fields=["organization_type"]), models.Index(fields=["organization_id"]), models.Index(fields=["team"]), ] def __str__(self): return self.organization_name def save(self, *args, **kwargs): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP new = self._state.adding is True # self._state.adding represents whether creating new instance or updating if self.timezone != self.__original_timezone and not new: num_updated = self.customers.filter(timezone_set=False).update( timezone=self.timezone ) if num_updated > 0: customer_ids = self.customers.filter(timezone_set=False).values_list( "id", flat=True ) customer_cache_keys = [f"tz_customer_{id}" for id in customer_ids] cache.delete_many(customer_cache_keys) if self.team is None: self.team = Team.objects.create(name=self.organization_name) if self.subscription_filter_keys is None: self.subscription_filter_keys = [] self.subscription_filter_keys = sorted( list( set(self.subscription_filter_keys).union( set(self.__original_subscription_filter_keys) ) ) ) super(Organization, self).save(*args, **kwargs) if self.subscription_filter_keys != self.__original_subscription_filter_keys: for metric in self.metrics.all(): METRIC_HANDLER_MAP[metric.metric_type].create_continuous_aggregate( metric, refresh=True ) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys if new: self.provision_currencies() if not self.default_currency: self.default_currency = PricingUnit.objects.get( organization=self, code="USD" ) self.save() if not self.webhooks_provisioned: self.provision_webhooks() def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_address(self) -> Address: if self.default_payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_organization_address(self) elif self.default_payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_organization_address(self) else: return self.address def provision_webhooks(self): if SVIX_CONNECTOR is not None and not self.webhooks_provisioned: logger.info("provisioning webhooks") svix = SVIX_CONNECTOR svix.application.create( ApplicationIn(uid=self.organization_id.hex, name=self.organization_name) ) self.webhooks_provisioned = True self.save() def provision_currencies(self): if SUPPORTED_CURRENCIES_VERSION != self.currencies_provisioned: for name, code, symbol in SUPPORTED_CURRENCIES: PricingUnit.objects.get_or_create( organization=self, code=code, name=name, symbol=symbol, custom=False ) PricingUnit.objects.filter( ~Q(code__in=[code for _, code, _ in SUPPORTED_CURRENCIES]), custom=False, organization=self, ).delete() self.currencies_provisioned = SUPPORTED_CURRENCIES_VERSION self.save() class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class WebhookTrigger(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_triggers", null=True, ) webhook_endpoint = models.ForeignKey( WebhookEndpoint, on_delete=models.CASCADE, related_name="triggers" ) trigger_name = models.CharField( choices=WEBHOOK_TRIGGER_EVENTS.choices, max_length=40 ) class Meta: indexes = [ models.Index( fields=["organization", "webhook_endpoint", "trigger_name"], name="unique_webhook_trigger", ) ] class User(AbstractUser): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="users", ) team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="users" ) email = models.EmailField(unique=True) history = HistoricalRecords() def save(self, *args, **kwargs): if not self.team and self.organization: self.team = self.organization.team super(User, self).save(*args, **kwargs) class Product(models.Model): """ This model is used to store the products that are available to be purchased. """ name = models.CharField(max_length=100, blank=False) description = models.TextField(null=True, blank=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="products" ) product_id = models.SlugField(default=product_uuid, max_length=100, unique=True) status = models.CharField(choices=PRODUCT_STATUS.choices, max_length=40) history = HistoricalRecords() class Meta: unique_together = ("organization", "product_id") def __str__(self): return f"{self.name}" class Customer(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="customers" ) customer_name = models.TextField( blank=True, help_text="The display name of the customer", null=True, ) email = models.EmailField( max_length=100, help_text="The primary email address of the customer, must be the same as the email address used to create the customer in the payment provider", null=True, ) customer_id = models.TextField( default=customer_uuid, help_text="The id provided when creating the customer, we suggest matching with your internal customer id in your backend", null=True, ) uuidv5_customer_id = models.UUIDField( help_text="The v5 UUID generated from the customer_id. This is used for efficient lookups in the database, specifically for the Events table", null=True, ) properties = models.JSONField( default=dict, null=True, help_text="Extra metadata for the customer" ) deleted = models.DateTimeField( null=True, help_text="The date the customer was deleted" ) # BILLING RELATED FIELDS default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="customers", null=True, blank=True, help_text="The currency the customer will be invoiced in", ) shipping_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="shipping_customers", null=True, blank=True, help_text="The shipping address for the customer", ) billing_address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="billing_customers", null=True, blank=True, help_text="The billing address for the customer", ) # TAX RELATED FIELDS tax_providers = TaxProviderListField(default=[]) tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) # TIMEZONE FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) timezone_set = models.BooleanField(default=False) # PAYMENT PROCESSOR FIELDS payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) braintree_integration = models.ForeignKey( "BraintreeCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customers", ) salesforce_integration = models.OneToOneField( "UnifiedCRMCustomerIntegration", on_delete=models.SET_NULL, null=True, blank=True, related_name="customer", ) # HISTORY FIELDS created = models.DateTimeField(default=now_utc) history = HistoricalRecords() objects = BaseCustomerManager() deleted_objects = DeletedCustomerManager() class Meta: constraints = [ UniqueConstraint(fields=["organization", "email"], name="unique_email"), UniqueConstraint( fields=["organization", "customer_id"], name="unique_customer_id" ), ] def __str__(self) -> str: return str(self.customer_name) + " " + str(self.customer_id) def save(self, *args, **kwargs): if not self.default_currency: try: self.default_currency = ( self.organization.default_currency or PricingUnit.objects.get( code="USD", organization=self.organization ) ) except PricingUnit.DoesNotExist: self.default_currency = None super(Customer, self).save(*args, **kwargs) def get_active_subscription_records(self): active_subscription_records = self.subscription_records.active().filter( fully_billed=False, ) return active_subscription_records def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_usage_and_revenue(self): customer_subscriptions = ( SubscriptionRecord.objects.active() .filter( customer=self, organization=self.organization, ) .prefetch_related("billing_plan__plan_components") .prefetch_related("billing_plan__plan_components__billable_metric") .select_related("billing_plan") ) subscription_usages = {"subscriptions": [], "sub_objects": []} for subscription in customer_subscriptions: sub_dict = subscription.get_usage_and_revenue() del sub_dict["components"] sub_dict["billing_plan_name"] = subscription.billing_plan.plan.plan_name subscription_usages["subscriptions"].append(sub_dict) subscription_usages["sub_objects"].append(subscription) return subscription_usages def get_active_sub_drafts_revenue(self): from metering_billing.invoice import generate_invoice total = 0 sub_records = self.get_active_subscription_records() if sub_records is not None and len(sub_records) > 0: invs = generate_invoice( sub_records, draft=True, charge_next_plan=True, ) total += sum([inv.amount for inv in invs]) for inv in invs: inv.delete() return total def get_currency_balance(self, currency): now = now_utc() balance = self.customer_balance_adjustments.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), effective_at__lte=now, amount_currency=currency, ).aggregate(balance=Sum("amount"))["balance"] or Decimal(0) return balance def get_outstanding_revenue(self): unpaid_invoice_amount_due = ( self.invoices.filter(payment_status=Invoice.PaymentStatus.UNPAID) .aggregate(unpaid_inv_amount=Sum("amount")) .get("unpaid_inv_amount") ) total_amount_due = unpaid_invoice_amount_due or 0 return total_amount_due def get_billing_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="billing") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.billing_address def get_shipping_address(self) -> Address: if self.payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_customer_address(self, type="shipping") elif self.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_customer_address(self, type="billing") else: return self.shipping_address class CustomerBalanceAdjustment(models.Model): """ This model is used to store the customer balance adjustments. """ adjustment_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="+", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name="customer_balance_adjustments" ) amount = models.DecimalField(decimal_places=10, max_digits=20) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="adjustments", null=True, blank=True, ) description = models.TextField(null=True, blank=True) created = models.DateTimeField(default=now_utc) effective_at = models.DateTimeField(default=now_utc) expires_at = models.DateTimeField(null=True, blank=True) parent_adjustment = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="drawdowns", ) amount_paid = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0) ) amount_paid_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="paid_adjustments", null=True, blank=True, ) status = models.CharField( max_length=20, choices=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.choices, default=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) def __str__(self): return f"{self.customer.customer_name} {self.amount} {self.created}" class Meta: ordering = ["-created"] unique_together = ("customer", "created") indexes = [ models.Index( fields=["organization", "adjustment_id"] ), # for lookup for single models.Index( fields=["organization", "customer", "pricing_unit", "-expires_at"] ), # for lookup for drawdowns models.Index(fields=["status", "expires_at"]), # for lookup for expired ] def save(self, *args, **kwargs): new = self._state.adding is True if not new: orig = CustomerBalanceAdjustment.objects.get(pk=self.pk) if ( orig.amount != self.amount or orig.pricing_unit != self.pricing_unit or orig.created != self.created or orig.effective_at != self.effective_at or orig.parent_adjustment != self.parent_adjustment ): raise NotEditable( "Cannot update any fields in a balance adjustment other than status and description" ) if self.expires_at is not None and now_utc() > self.expires_at: raise NotEditable("Cannot change the expiry date to the past") if self.amount < 0: assert ( self.parent_adjustment is not None ), "If credit is negative, parent adjustment must be provided" if self.parent_adjustment: assert ( self.parent_adjustment.amount > 0 ), "Parent adjustment must be a credit adjustment" assert ( self.parent_adjustment.customer == self.customer ), "Parent adjustment must be for the same customer" assert self.amount < 0, "Child adjustment must be a debit adjustment" assert ( self.pricing_unit == self.parent_adjustment.pricing_unit ), "Child adjustment must be in the same currency as parent adjustment" assert self.parent_adjustment.get_remaining_balance() - self.amount >= 0, ( "Child adjustment must be less than or equal to the remaining balance of " "the parent adjustment" ) if not self.organization: self.organization = self.customer.organization if self.amount_paid is None or self.amount_paid == 0: self.amount_paid_currency = None if not self.pricing_unit: raise ValidationError("Pricing unit must be provided") super(CustomerBalanceAdjustment, self).save(*args, **kwargs) def get_remaining_balance(self): try: dd_aggregate = self.total_drawdowns except AttributeError: dd_aggregate = self.drawdowns.aggregate(drawdowns=Sum("amount"))[ "drawdowns" ] drawdowns = dd_aggregate or 0 return self.amount + drawdowns def zero_out(self, reason=None): if reason == "expired": fmt = self.expires_at.strftime("%Y-%m-%d %H:%M") description = f"Expiring remaining credit at {fmt} UTC" elif reason == "voided": fmt = now_utc().strftime("%Y-%m-%d %H:%M") description = f"Voiding remaining credit at {fmt} UTC" else: description = "Zeroing out remaining credit" remaining_balance = self.get_remaining_balance() if remaining_balance > 0: CustomerBalanceAdjustment.objects.create( organization=self.customer.organization, customer=self.customer, amount=-remaining_balance, pricing_unit=self.pricing_unit, parent_adjustment=self, description=description, ) self.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE self.save() def draw_down_amount(customer, amount, pricing_unit, description=""): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .annotate( cost_basis=Cast( Coalesce(F("amount_paid") / F("amount"), 0), FloatField() ) ) .order_by( F("expires_at").asc(nulls_last=True), F("cost_basis").desc(nulls_last=True), ) .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") + F("drawn_down_amount")) ) am = amount for adj in adjs: remaining_balance = adj.remaining_balance if remaining_balance <= 0: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() continue drawdown_amount = min(am, remaining_balance) CustomerBalanceAdjustment.objects.create( organization=customer.organization, customer=customer, amount=-drawdown_amount, pricing_unit=adj.pricing_unit, parent_adjustment=adj, description=description, ) if drawdown_amount == remaining_balance: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() am -= drawdown_amount if am == 0: break return am def get_pricing_unit_balance(customer, pricing_unit): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .prefetch_related("drawdowns") .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") - F("drawn_down_amount")) .aggregate(total_balance=Sum("remaining_balance"))["total_balance"] ) total_balance = adjs or 0 return total_balance class Event(models.Model): organization = models.ForeignKey( Organization, on_delete=models.SET_NULL, related_name="+", null=True, blank=True ) cust_id = models.TextField(blank=True) uuidv5_customer_id = models.UUIDField() event_name = models.TextField( help_text="String name of the event, corresponds to definition in metrics", ) uuidv5_event_name = models.UUIDField() time_created = models.DateTimeField( help_text="The time that the event occured, represented as a datetime in RFC3339 in the UTC timezome." ) properties = models.JSONField( default=dict, blank=True, help_text="Extra metadata on the event that can be filtered and queried on in the metrics. All key value pairs should have string keys and values can be either strings or numbers. Place subscription filters in this object to specify which subscription the event should be tracked under", ) idempotency_id = models.TextField( default=event_uuid, help_text="A unique identifier for the specific event being passed in. Passing in a unique id allows Lotus to make sure no double counting occurs. We recommend using a UUID4. You can use the same idempotency_id again after 45 days.", primary_key=True, ) uuidv5_idempotency_id = models.UUIDField() inserted_at = models.DateTimeField(default=now_utc) objects = EventManager() class Meta: managed = False db_table = "metering_billing_usageevent" def __str__(self): return ( str(self.event_name)[:6] + "-" + str(self.cust_id)[:8] + "-" + str(self.time_created)[:10] + "-" + str(self.idempotency_id)[:6] ) class NumericFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="numeric_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField(max_length=10, choices=NUMERIC_FILTER_OPERATORS.choices) comparison_value = models.FloatField() class CategoricalFilter(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="categorical_filters", null=True, ) property_name = models.CharField(max_length=100) operator = models.CharField( max_length=10, choices=CATEGORICAL_FILTER_OPERATORS.choices ) comparison_value = models.JSONField() def __str__(self): return f"{self.property_name} {self.operator} {self.comparison_value}" class Metric(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="metrics", ) event_name = models.TextField( help_text="Name of the event that this metric is tracking." ) metric_type = models.CharField( max_length=20, choices=METRIC_TYPE.choices, default=METRIC_TYPE.COUNTER, help_text="The type of metric that this is. Please refer to our documentation for an explanation of the different types.", ) properties = models.JSONField(default=dict, blank=True, null=True) billable_metric_name = models.TextField(blank=True, null=True) metric_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) event_type = models.CharField( max_length=20, choices=EVENT_TYPE.choices, blank=True, null=True, help_text="Used only for metrics of type 'gauge'. Please refer to our documentation for an explanation of the different types.", ) # metric type specific usage_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.COUNT, help_text="The type of aggregation that should be used for this metric. Please refer to our documentation for an explanation of the different types.", ) billable_aggregation_type = models.CharField( max_length=10, choices=METRIC_AGGREGATION.choices, default=METRIC_AGGREGATION.SUM, blank=True, null=True, ) property_name = models.TextField( blank=True, null=True, help_text="The name of the property of the event that should be used for this metric. Doesn't apply if the metric is of type 'counter' with an aggregation of count.", ) granularity = models.CharField( choices=METRIC_GRANULARITY.choices, default=METRIC_GRANULARITY.TOTAL, max_length=10, blank=True, null=True, help_text="The granularity of the metric. Only applies to metrics of type 'gauge' or 'rate'.", ) proration = models.CharField( choices=METRIC_GRANULARITY.choices, default=None, max_length=10, blank=True, null=True, help_text="The proration of the metric. Only applies to metrics of type 'gauge'.", ) is_cost_metric = models.BooleanField( default=False, help_text="Whether or not this metric is a cost metric (used to track costs to your business).", ) custom_sql = models.TextField( blank=True, null=True, help_text="A custom SQL query that can be used to define the metric. Please refer to our documentation for more information.", ) # filters numeric_filters = models.ManyToManyField(NumericFilter, blank=True) categorical_filters = models.ManyToManyField(CategoricalFilter, blank=True) # status status = models.CharField( choices=METRIC_STATUS.choices, max_length=40, default=METRIC_STATUS.ACTIVE ) mat_views_provisioned = models.BooleanField(default=False) # records history = HistoricalRecords() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "billable_metric_name"], condition=Q(status=METRIC_STATUS.ACTIVE), name="unique_org_billable_metric_name", ), ] + [ models.UniqueConstraint( fields=sorted( list( { "organization", "billable_metric_name", # nullable "event_name", "metric_type", "usage_aggregation_type", "billable_aggregation_type", # nullable "property_name", # nullable "granularity", # nullable "is_cost_metric", "custom_sql", # nullable } - {x for x in nullables} ) ), condition=Q( **{f"{nullable}__in": [None, ""] for nullable in sorted(nullables)} ) & Q(status=METRIC_STATUS.ACTIVE), name="uq_metric_w_null__" + "_".join( [ "_".join([x[:2] for x in nullable.split("_")]) for nullable in sorted(nullables) ] ), ) for nullables in itertools.chain( *map( lambda x: itertools.combinations( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], x, ), range( 0, len( [ "billable_metric_name", "billable_aggregation_type", "property_name", "granularity", "custom_sql", ], ) + 1, ), ) ) ] indexes = [ models.Index(fields=["organization", "status"]), models.Index(fields=["organization", "is_cost_metric"]), models.Index(fields=["organization", "metric_id"]), ] def __str__(self): return self.billable_metric_name or "" def save(self, *args, **kwargs): super().save(*args, **kwargs) def delete_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.archive_metric(self) self.mat_views_provisioned = False self.save() def get_aggregation_type(self): return self.aggregation_type def get_billing_record_total_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_total_billable_usage(self, billing_record) return usage def get_billing_record_daily_billable_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_daily_billable_usage(self, billing_record) return usage def get_billing_record_current_usage(self, billing_record): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_billing_record_current_usage(self, billing_record) return usage def get_daily_total_usage( self, start_date: datetime.date, end_date: datetime.date, customer: Optional[Customer] = None, top_n: Optional[int] = None, ) -> dict[Union[Customer, Literal["Other"]], dict[datetime.date, Decimal]]: from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP if self.status == METRIC_STATUS.ACTIVE and not self.mat_views_provisioned: self.provision_materialized_views() handler = METRIC_HANDLER_MAP[self.metric_type] usage = handler.get_daily_total_usage( self, start_date, end_date, customer, top_n ) return usage def refresh_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self, refresh=True) self.mat_views_provisioned = True self.save() def provision_materialized_views(self): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP handler = METRIC_HANDLER_MAP[self.metric_type] handler.create_continuous_aggregate(self) self.mat_views_provisioned = True self.save() class PriceTier(models.Model): class PriceTierType(models.IntegerChoices): FLAT = (1, _("flat")) PER_UNIT = (2, _("per_unit")) FREE = (3, _("free")) class BatchRoundingType(models.IntegerChoices): ROUND_UP = (1, _("round_up")) ROUND_DOWN = (2, _("round_down")) ROUND_NEAREST = (3, _("round_nearest")) NO_ROUNDING = (4, _("no_rounding")) organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="price_tiers", null=True ) plan_component = models.ForeignKey( "PlanComponent", on_delete=models.CASCADE, related_name="tiers", null=True, blank=True, ) type = models.PositiveSmallIntegerField(choices=PriceTierType.choices) range_start = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) range_end = models.DecimalField( max_digits=20, decimal_places=10, null=True, blank=True, validators=[MinValueValidator(0)], ) cost_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, validators=[MinValueValidator(0)], ) metric_units_per_batch = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, default=1.0, validators=[MinValueValidator(0)], ) batch_rounding_type = models.PositiveSmallIntegerField( choices=BatchRoundingType.choices, blank=True, null=True, ) class Meta: constraints = [ models.CheckConstraint( check=Q(range_end__gte=F("range_start")) | Q(range_end__isnull=True), name="price_tier_type_valid", ), models.UniqueConstraint( fields=["organization", "plan_component", "range_start"], name="unique_price_tier", ), ] def save(self, *args, **kwargs): new = self._state.adding is True ranges = [ (tier["range_start"], tier["range_end"]) for tier in self.plan_component.tiers.order_by("range_start").values( "range_start", "range_end" ) ] if new: ranges = sorted( ranges + [(self.range_start, self.range_end)], key=lambda x: x[0] ) for i, (start, end) in enumerate(ranges): if i == 0: if start != 0: raise ValidationError("First tier must start at 0") else: diff = start - ranges[i - 1][1] if diff != Decimal(0) and diff != Decimal(1): raise ValidationError( "Tier ranges must be continuous or separated by 1" ) if i != len(ranges) - 1: if end is None: raise ValidationError("Only last tier can be open ended") super().save(*args, **kwargs) def calculate_revenue( self, usage: float, prev_tier_end=False, bulk_pricing_enabled=False ): # if division_factor is None: # division_factor = len(usage_dict) revenue = 0 discontinuous_range = ( prev_tier_end != self.range_start and prev_tier_end is not None ) # for usage in usage_dict.values(): usage = convert_to_decimal(usage) if ( bulk_pricing_enabled and self.range_end is not None and self.range_end <= usage ): return revenue if bulk_pricing_enabled: usage_in_range = self.range_start <= usage else: usage_in_range = ( self.range_start <= usage if discontinuous_range else self.range_start < usage or self.range_start == 0 ) if usage_in_range: if self.type == PriceTier.PriceTierType.FLAT: revenue += self.cost_per_batch return revenue if self.type == PriceTier.PriceTierType.PER_UNIT: if bulk_pricing_enabled: billable_units = usage elif self.range_end is not None: billable_units = min( usage - self.range_start, self.range_end - self.range_start ) else: billable_units = usage - self.range_start if discontinuous_range: billable_units += 1 billable_batches = billable_units / self.metric_units_per_batch if self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_UP: billable_batches = math.ceil(billable_batches) elif self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_DOWN: billable_batches = math.floor(billable_batches) elif ( self.batch_rounding_type == PriceTier.BatchRoundingType.ROUND_NEAREST ): billable_batches = round(billable_batches) revenue += self.cost_per_batch * billable_batches return revenue class ComponentFixedCharge(models.Model): class ChargeBehavior(models.IntegerChoices): PRORATE = (1, _("prorate")) FULL = (2, _("full")) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="component_charges" ) units = models.DecimalField( decimal_places=10, max_digits=20, blank=True, null=True, validators=[MinValueValidator(0)], ) charge_behavior = models.PositiveSmallIntegerField( choices=ChargeBehavior.choices, default=ChargeBehavior.PRORATE ) def __str__(self): try: return f"Fixed Charge for {self.component}" except AttributeError: return "Fixed Charge" def get_charge_behavior_from_label(label): mapping = { ComponentFixedCharge.ChargeBehavior.PRORATE.label: ComponentFixedCharge.ChargeBehavior.PRORATE.value, ComponentFixedCharge.ChargeBehavior.FULL.label: ComponentFixedCharge.ChargeBehavior.FULL.value, } return mapping.get(label, label) class PlanComponent(models.Model): class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, related_name="plan_components", null=True, ) usage_component_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) billable_metric = models.ForeignKey( Metric, on_delete=models.CASCADE, related_name="+", null=True, blank=True, ) plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="plan_components", null=True, blank=True, ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="components", null=True, blank=True, ) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) fixed_charge = models.OneToOneField( ComponentFixedCharge, on_delete=models.SET_NULL, related_name="component", null=True, ) bulk_pricing_enabled = models.BooleanField(default=False) def __str__(self): return str(self.billable_metric) def save(self, *args, **kwargs): if self.pricing_unit is None and self.plan_version is not None: self.pricing_unit = self.plan_version.currency super().save(*args, **kwargs) def convert_length_label_to_value(label): label_map = { PlanComponent.IntervalLengthType.DAY.label: PlanComponent.IntervalLengthType.DAY, PlanComponent.IntervalLengthType.WEEK.label: PlanComponent.IntervalLengthType.WEEK, PlanComponent.IntervalLengthType.MONTH.label: PlanComponent.IntervalLengthType.MONTH, PlanComponent.IntervalLengthType.YEAR.label: PlanComponent.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_component_invoicing_dates( self, subscription_record, override_start_date=None ): # FOR PLAN COMPONENTS start_date = override_start_date or subscription_record.start_date end_date = subscription_record.end_date if self.invoicing_interval_unit is None: return [end_date] unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", } interval_delta = relativedelta( **{ unit_map[self.invoicing_interval_unit]: self.invoicing_interval_count or 1 } ) invoicing_dates = [] invoicing_date = start_date while invoicing_date < end_date: invoicing_date += interval_delta append_date = min(invoicing_date, end_date) invoicing_dates.append(append_date) return invoicing_dates def get_component_reset_dates(self, subscription_record, override_start_date=None): # FOR PLAN COMPONENTS sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date if override_start_date: range_start_date = override_start_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): start = reset_dates[i] if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges def calculate_total_revenue( self, billing_record, prepaid_units=None ) -> UsageRevenueSummary: assert isinstance( billing_record, BillingRecord ), "billing_record must be a BillingRecord" billable_metric = self.billable_metric usage_qty = billable_metric.get_billing_record_total_billable_usage( billing_record ) revenue = self.tier_rating_function(usage_qty) latest_component_charge = self.component_charge_records.order_by( "-start_date" ).first() if latest_component_charge is not None: revenue_from_prepaid_units = self.tier_rating_function(prepaid_units) revenue = max(revenue - revenue_from_prepaid_units, 0) return {"revenue": revenue, "usage_qty": usage_qty} def tier_rating_function(self, usage_qty): revenue = 0 tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: # this is for determining whether this is a continuous or discontinuous range prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( usage_qty, prev_tier_end=prev_tier_end, bulk_pricing_enabled=self.bulk_pricing_enabled, ) else: tier_revenue = tier.calculate_revenue( usage_qty, bulk_pricing_enabled=self.bulk_pricing_enabled ) revenue += tier_revenue revenue = convert_to_decimal(revenue) return revenue def calculate_revenue_per_day( self, billing_record ) -> dict[datetime.datetime, UsageRevenueSummary]: assert isinstance(billing_record, BillingRecord) billable_metric = self.billable_metric usage_per_day = billable_metric.get_billing_record_daily_billable_usage( billing_record ) results = {} for period in dates_bwn_two_dts( billing_record.start_date, billing_record.end_date ): period = convert_to_date(period) results[period] = {"revenue": Decimal(0), "usage_qty": Decimal(0)} running_total_revenue = Decimal(0) running_total_usage = Decimal(0) for date, usage_qty in usage_per_day.items(): date = convert_to_date(date) usage_qty = convert_to_decimal(usage_qty) running_total_usage += usage_qty revenue = Decimal(0) tiers = self.tiers.all() for i, tier in enumerate(tiers): if i > 0: prev_tier_end = tiers[i - 1].range_end tier_revenue = tier.calculate_revenue( running_total_usage, prev_tier_end=prev_tier_end ) else: tier_revenue = tier.calculate_revenue(running_total_usage) revenue += convert_to_decimal(tier_revenue) date_revenue = revenue - running_total_revenue running_total_revenue += date_revenue if date in results: results[date]["revenue"] += date_revenue results[date]["usage_qty"] += usage_qty return results class Feature(models.Model): feature_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="features" ) feature_name = models.CharField(max_length=50, blank=False) feature_description = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "feature_name"], name="unique_feature" ) ] def __str__(self): return str(self.feature_name) class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status class InvoiceLineItem(models.Model): invoice_line_item_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoice_line_items", null=True, ) name = models.CharField(max_length=100) start_date = models.DateTimeField(max_length=100, default=now_utc) end_date = models.DateTimeField(max_length=100, default=now_utc) quantity = models.DecimalField( decimal_places=10, max_digits=20, null=True, blank=True, validators=[MinValueValidator(0)], ) base = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Base price of the line item. This is the price before any adjustments are applied.", ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), help_text="Amount of the line item. This is the price after any adjustments are applied.", ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="line_items", null=True, blank=True, ) billing_type = models.CharField( max_length=40, choices=INVOICE_CHARGE_TIMING_TYPE.choices, blank=True, null=True ) chargeable_item_type = models.CharField( max_length=40, choices=CHARGEABLE_ITEM_TYPE.choices, blank=True, null=True ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, null=True, related_name="line_items" ) associated_plan_version = models.ForeignKey( "PlanVersion", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_subscription_record = models.ForeignKey( "SubscriptionRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) associated_billing_record = models.ForeignKey( "BillingRecord", on_delete=models.SET_NULL, null=True, related_name="line_items", ) metadata = models.JSONField(default=dict, blank=True, null=True) def __str__(self): return self.name + " " + str(self.invoice.invoice_number) + f"[{self.base}]" def save(self, *args, **kwargs): self.amount = self.base + sum( [adjustment.amount for adjustment in self.adjustments.all()] ) super().save(*args, **kwargs) class APIToken(AbstractAPIKey): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="api_keys" ) class Meta(AbstractAPIKey.Meta): verbose_name = "API Token" verbose_name_plural = "API Tokens" def __str__(self): return str(self.name) + " " + str(self.organization.organization_name) class TeamInviteToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_invite_token" ) team = models.ForeignKey( Team, on_delete=models.CASCADE, related_name="team_invite_token" ) email = models.EmailField() token = models.SlugField(max_length=250, default=uuid.uuid4) expire_at = models.DateTimeField(default=now_plus_day, null=False, blank=False) def __str__(self): return str(self.email) + " - " + str(self.team) class RecurringCharge(models.Model): class ChargeTimingType(models.IntegerChoices): IN_ADVANCE = (1, "in_advance") IN_ARREARS = (2, "in_arrears") class ChargeBehaviorType(models.IntegerChoices): PRORATE = (1, "prorate") CHARGE_FULL = (2, "full") class IntervalLengthType(models.IntegerChoices): DAY = (1, "day") WEEK = (2, "week") MONTH = (3, "month") YEAR = (4, "year") recurring_charge_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="recurring_charges", ) name = models.TextField() plan_version = models.ForeignKey( "PlanVersion", on_delete=models.CASCADE, related_name="recurring_charges", ) charge_timing = models.PositiveSmallIntegerField( choices=ChargeTimingType.choices, default=ChargeTimingType.IN_ADVANCE ) charge_behavior = models.PositiveSmallIntegerField( choices=ChargeBehaviorType.choices, default=ChargeBehaviorType.PRORATE ) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="recurring_charges", null=True, ) reset_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) reset_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) invoicing_interval_unit = models.PositiveSmallIntegerField( choices=IntervalLengthType.choices, null=True, blank=True ) invoicing_interval_count = models.PositiveSmallIntegerField(null=True, blank=True) def __str__(self): return self.name + " [" + str(self.plan_version) + "]" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "plan_version", "name"], name="unique_recurring_charge_name_in_plan_version", ) ] def convert_length_label_to_value(label): label_map = { RecurringCharge.IntervalLengthType.DAY.label: RecurringCharge.IntervalLengthType.DAY, RecurringCharge.IntervalLengthType.WEEK.label: RecurringCharge.IntervalLengthType.WEEK, RecurringCharge.IntervalLengthType.MONTH.label: RecurringCharge.IntervalLengthType.MONTH, RecurringCharge.IntervalLengthType.YEAR.label: RecurringCharge.IntervalLengthType.YEAR, None: None, } return label_map[label] def get_recurring_charge_invoicing_dates( self, subscription_record, append_range_start=False ): # FOR RECURRIG CHARGES # first we get the actual star tdate and end date of this subscription. However, if this is an addon, we need to calculate the periods w.r.t the parent subscription sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date invoicing_interval_unit = self.invoicing_interval_unit invoicing_interval_count = self.invoicing_interval_count # if we don't have a sub-plan length invoicing interval, use the plan length if not invoicing_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. invoicing_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if invoicing_interval_unit == PLAN_DURATION.QUARTERLY: invoicing_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[invoicing_interval_unit]: invoicing_interval_count or 1} ) invoicing_dates = [] invoicing_date = range_start_date # now generate invoicing dates while invoicing_date < range_end_date: invoicing_date += interval_delta append_date = min(invoicing_date, range_end_date) invoicing_dates.append(append_date) # purge the ones that don't match up with the real duration, and add the start + end dates invoicing_dates = { x for x in invoicing_dates if x >= sr_start_date and x <= sr_end_date } if append_range_start: invoicing_dates = invoicing_dates | {sr_start_date} invoicing_dates = invoicing_dates | {sr_end_date} invoicing_dates = sorted(list(invoicing_dates)) return invoicing_dates def get_recurring_charge_reset_dates(self, subscription_record): # FOR RECURRIG CHARGES sr_start_date = subscription_record.start_date sr_end_date = subscription_record.end_date if subscription_record.parent: range_start_date = subscription_record.parent.start_date range_end_date = subscription_record.parent.end_date else: range_start_date = sr_start_date range_end_date = sr_end_date reset_interval_unit = self.reset_interval_unit reset_interval_count = self.reset_interval_count # if we don't have a sub-plan length reset interval, use the plan length if not reset_interval_unit: # problem here is for addons. Their plans do not have durations as they depend on the parent subscription. reset_interval_unit = ( self.plan_version.plan.plan_duration or subscription_record.parent.billing_plan.plan.plan_duration ) if reset_interval_unit == PLAN_DURATION.QUARTERLY: reset_interval_count = 3 unit_map = { PlanComponent.IntervalLengthType.DAY: "days", PlanComponent.IntervalLengthType.WEEK: "weeks", PlanComponent.IntervalLengthType.MONTH: "months", PlanComponent.IntervalLengthType.YEAR: "years", PLAN_DURATION.MONTHLY: "months", PLAN_DURATION.QUARTERLY: "months", PLAN_DURATION.YEARLY: "years", } interval_delta = relativedelta( **{unit_map[reset_interval_unit]: reset_interval_count or 1} ) if not self.reset_interval_unit: unadjusted_duration_microseconds = ( (range_start_date + interval_delta) - range_start_date ).total_seconds() * 10**6 return [(sr_start_date, sr_end_date, unadjusted_duration_microseconds)] reset_dates = [] reset_date = range_start_date while reset_date < range_end_date: append_date = min(reset_date, range_end_date) reset_dates.append(append_date) reset_date += interval_delta # Construct non-overlapping date ranges reset_ranges = [] for i in range(len(reset_dates)): if sr_start_date > reset_dates[i]: continue start = max(reset_dates[i], sr_start_date) if i == len(reset_dates) - 1: end = sr_end_date else: end = reset_dates[i + 1] - datetime.timedelta(microseconds=1) unadjusted_duration_microseconds = ( (reset_dates[i] + interval_delta) - reset_dates[i] ).total_seconds() * 10**6 reset_ranges.append((start, end, unadjusted_duration_microseconds)) return reset_ranges class PlanVersion(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plan_versions", ) version = models.PositiveSmallIntegerField(default=1) version_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) localized_name = models.TextField(null=True, blank=True, default=None) plan = models.ForeignKey("Plan", on_delete=models.CASCADE, related_name="versions") created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plan_versions", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) # BILLING SCHEDULE day_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(31)], null=True, blank=True, ) month_anchor = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)], null=True, blank=True, ) replace_with = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) transition_to = models.ForeignKey( "Plan", on_delete=models.SET_NULL, null=True, blank=True, related_name="transition_from", ) addon_spec = models.OneToOneField( "AddOnSpecification", on_delete=models.SET_NULL, related_name="plan_version", null=True, blank=True, ) active_from = models.DateTimeField(null=True, default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # PRICING features = models.ManyToManyField(Feature, blank=True) price_adjustment = models.ForeignKey( "PriceAdjustment", on_delete=models.SET_NULL, null=True, blank=True ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="versions", null=True, blank=True, ) # MISC is_custom = models.BooleanField(default=False) target_customers = models.ManyToManyField(Customer, related_name="plan_versions") objects = PlanVersionManager() plan_versions = RegularPlanVersionManager() addon_versions = AddOnPlanVersionManager() deleted_objects = DeletedPlanVersionManager() class Meta: constraints = [ models.UniqueConstraint( fields=["plan", "version", "currency"], name="unique_plan_version_per_currency", condition=Q(is_custom=False), ), ] indexes = [ models.Index(fields=["organization", "plan"]), models.Index(fields=["organization", "version_id"]), ] def __str__(self) -> str: if self.localized_name is not None: return self.localized_name return str(self.plan) def num_active_subs(self): cnt = self.subscription_records.active().count() return cnt def is_active(self, time=None): if time is None: time = now_utc() return self.active_from <= time and ( self.active_to is None or self.active_to > time ) def get_status(self) -> PLAN_VERSION_STATUS: now = now_utc() if self.deleted is not None: return PLAN_VERSION_STATUS.DELETED if not self.active_from: return PLAN_VERSION_STATUS.INACTIVE if self.active_from <= now: if self.active_to is None or self.active_to > now: return PLAN_VERSION_STATUS.ACTIVE else: n_active_subs = self.num_active_subs() if self.replace_with is None: if n_active_subs > 0: # SHOULD NEVER HAPPEN. EXPIRED PLAN, ACTIVE SUBS, NO REPLACEMENT return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE elif self.replace_with == self: if n_active_subs > 0: return PLAN_VERSION_STATUS.GRANDFATHERED else: return PLAN_VERSION_STATUS.INACTIVE else: if n_active_subs > 0: return PLAN_VERSION_STATUS.RETIRING else: return PLAN_VERSION_STATUS.INACTIVE else: return PLAN_VERSION_STATUS.INACTIVE class PriceAdjustment(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="price_adjustments" ) price_adjustment_name = models.CharField(max_length=100) price_adjustment_description = models.TextField(blank=True, null=True) price_adjustment_type = models.CharField( max_length=40, choices=PRICE_ADJUSTMENT_TYPE.choices ) price_adjustment_amount = models.DecimalField( max_digits=20, decimal_places=10, ) def __str__(self): if self.price_adjustment_name != "": return str(self.price_adjustment_name) else: return ( str(round(self.price_adjustment_amount, 2)) + " " + str(self.price_adjustment_type) ) def apply(self, amount): if self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PERCENTAGE: return amount * (1 + self.price_adjustment_amount / 100) elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.FIXED: return amount + self.price_adjustment_amount elif self.price_adjustment_type == PRICE_ADJUSTMENT_TYPE.PRICE_OVERRIDE: return self.price_adjustment_amount class Plan(models.Model): # META organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="plans" ) plan_name = models.TextField(help_text="Name of the plan") plan_description = models.TextField( help_text="Description of the plan", blank=True, null=True ) plan_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) created_on = models.DateTimeField(default=now_utc) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="created_plans", null=True, blank=True, ) deleted = models.DateTimeField(null=True, blank=True) is_addon = models.BooleanField(default=False) # BILLING taxjar_code = models.TextField(max_length=30, null=True, blank=True) plan_duration = models.CharField( choices=PLAN_DURATION.choices, max_length=40, help_text="Duration of the plan", null=True, ) active_from = models.DateTimeField(default=now_utc, blank=True) active_to = models.DateTimeField(null=True, blank=True) # MISC tags = models.ManyToManyField("Tag", blank=True, related_name="plans") objects = BasePlanManager() plans = RegularPlanManager() addons = AddOnPlanManager() deleted_objects = DeletedPlanManager() history = HistoricalRecords() # USELESS RN parent_product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product_plans", null=True, blank=True, help_text="The product that this plan belongs to", ) class Meta: indexes = [ models.Index(fields=["organization", "plan_id"]), ] def __str__(self): return self.plan_name def add_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) def remove_tags(self, tags): existing_tags = self.tags.all() tags_lower = [tag["tag_name"].lower() for tag in tags] for existing_tag in existing_tags: if existing_tag.tag_name.lower() in tags_lower: self.tags.remove(existing_tag) def set_tags(self, tags): existing_tags = self.tags.all() existing_tag_names = [tag.tag_name.lower() for tag in existing_tags] new_tag_names_lower = [tag["tag_name"].lower() for tag in tags] for tag in tags: if tag["tag_name"].lower() not in existing_tag_names: defaults = { "tag_group": TAG_GROUP.PLAN, "tag_hex": tag.get("tag_hex"), "tag_color": tag.get("tag_color"), "tag_name": tag["tag_name"], } tag_obj, _ = Tag.objects.get_or_create( organization=self.organization, tag_name__iexact=tag["tag_name"].lower(), defaults=defaults, ) self.tags.add(tag_obj) for existing_tag in existing_tags: if existing_tag.tag_name.lower() not in new_tag_names_lower: self.tags.remove(existing_tag) def active_subs_by_version(self): versions = self.versions.all().prefetch_related("subscription_records") now = now_utc() versions_count = versions.annotate( active_subscriptions=Count( "subscription_record", filter=Q( subscription_record__start_date__lte=now, subscription_record__end_date__gte=now, ), output_field=models.IntegerField(), ) ) return versions_count def get_version_for_customer(self, customer) -> Optional[PlanVersion]: versions = self.versions.active().prefetch_related( "subscription_records", "target_customers" ) # rules are as follows: # 1. if there is only one version, return it # 2. custom plans, preferring the customer's preferred currency # 3. filter down to the customer's preferred currency # 4. filter down to the organization's preferred currency if versions.count() == 0: return None elif versions.count() == 1: return versions.first() else: customer_target_plans = customer.plan_versions.filter(plan=self) customer_target_plan_in_customer_currency = customer_target_plans.filter( currency=customer.default_currency ) customer_target_plan_in_org_currency = customer_target_plans.filter( currency=customer.organization.default_currency ) if customer_target_plans.count() == 1: return customer_target_plans.first() elif customer_target_plan_in_customer_currency.count() == 1: return customer_target_plan_in_customer_currency.first() elif customer_target_plan_in_customer_currency.count() > 1: return None # DO NOT randomly choose a plan if multiple match elif customer_target_plan_in_org_currency.count() == 1: return customer_target_plan_in_org_currency.first() elif customer_target_plan_in_org_currency.count() > 1: return None # if we get here that means there are no customer specific plans versions_in_customer_currency = versions.filter( currency=customer.default_currency ) if versions_in_customer_currency.count() == 1: return versions_in_customer_currency.first() elif versions_in_customer_currency.count() > 1: return None versions_in_org_currency = versions.filter( currency=customer.organization.default_currency ) if versions_in_org_currency.count() == 1: return versions_in_org_currency.first() elif versions_in_org_currency.count() > 1: return None return None class ExternalPlanLink(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="external_plan_links", ) plan = models.ForeignKey( Plan, on_delete=models.CASCADE, related_name="external_links" ) source = models.CharField(choices=PAYMENT_PROCESSORS.choices, max_length=40) external_plan_id = models.CharField(max_length=100) def __str__(self): return f"{self.plan} - {self.source} - {self.external_plan_id}" class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "source", "external_plan_id"], name="unique_external_plan_link", ) ] class SubscriptionRecord(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="subscription_records", ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=False, related_name="subscription_records", help_text="The customer object associated with this subscription.", ) billing_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, null=True, related_name="subscription_records", related_query_name="subscription_record", help_text="The plan associated with this subscription.", ) usage_start_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) end_date = models.DateTimeField( help_text="The time the subscription starts. This will be a string in yyyy-mm-dd HH:mm:ss format in UTC time." ) auto_renew = models.BooleanField( default=True, help_text="Whether the subscription automatically renews. Defaults to true.", ) is_new = models.BooleanField( default=True, help_text="Whether this subscription came from a renewal or from a first-time. Defaults to true on creation.", ) subscription_record_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) subscription_filters = ArrayField( ArrayField( models.TextField(blank=False, null=False), size=2, ), default=list, ) invoice_usage_charges = models.BooleanField(default=True) flat_fee_behavior = models.CharField( choices=FLAT_FEE_BEHAVIOR.choices, max_length=20, null=True, default=None ) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.CASCADE, related_name="addon_subscription_records", help_text="The parent subscription record.", ) quantity = models.PositiveIntegerField(default=1) metadata = models.JSONField(default=dict, blank=True) stripe_subscription_id = models.TextField(null=True, blank=True, default=None) # managers etc objects = SubscriptionRecordManager() addon_objects = AddOnSubscriptionRecordManager() base_objects = BaseSubscriptionRecordManager() stripe_objects = StripeSubscriptionRecordManager() history = HistoricalRecords() class Meta: constraints = [ CheckConstraint( check=Q(start_date__lte=F("end_date")), name="end_date_gte_start_date" ), CheckConstraint(check=Q(quantity__gt=0), name="quantity_gt_0"), # check if stripe subscription id is null, then billing plan is not null, and vice versa CheckConstraint( check=( Q(stripe_subscription_id__isnull=False) & Q(billing_plan__isnull=True) ) | ( Q(stripe_subscription_id__isnull=True) & Q(billing_plan__isnull=False) ), name="stripe_subscription_id_xor_billing_plan", ), ] def __str__(self): addon = "[ADDON] " if self.billing_plan.addon_spec else "" if self.stripe_subscription_id: plan_name = "Stripe Subscription {}".format(self.stripe_subscription_id) else: plan_name = self.billing_plan.plan.plan_name return f"{addon}{self.customer.customer_name} {plan_name} : {self.start_date.date()} to {self.end_date.date()}" def create_subscription_record( start_date, end_date, billing_plan, customer, organization, subscription_filters=None, is_new=True, quantity=1, component_fixed_charges_initial_units=None, do_generate_invoice=True, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } assert ( billing_plan.addon_spec is None ), "Cannot create a base subscription record with an addon plan" sr = SubscriptionRecord.objects.create( start_date=start_date, end_date=end_date, billing_plan=billing_plan, customer=customer, organization=organization, subscription_filters=subscription_filters, is_new=is_new, quantity=quantity, ) for component in sr.billing_plan.plan_components.all(): metric = component.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(component, **kwargs) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) if do_generate_invoice: generate_invoice(sr) return sr def create_addon_subscription_record( parent_subscription_record, addon_billing_plan, quantity=1, ): from metering_billing.invoice import generate_invoice now = now_utc() assert ( addon_billing_plan.addon_spec is not None ), "Cannot create an addon subscription record with a base plan" sr = SubscriptionRecord.objects.create( parent=parent_subscription_record, start_date=now, end_date=parent_subscription_record.end_date, billing_plan=addon_billing_plan, customer=parent_subscription_record.customer, organization=parent_subscription_record.organization, subscription_filters=parent_subscription_record.subscription_filters, is_new=True, quantity=quantity, auto_renew=addon_billing_plan.addon_spec.billing_frequency == AddOnSpecification.BillingFrequency.RECURRING, ) for component in sr.billing_plan.plan_components.all(): sr._create_component_billing_records(component) for recurring_charge in sr.billing_plan.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) generate_invoice(sr) return sr def _create_component_billing_records( self, component, override_start_date=None, initial_units=None, ignore_prepaid=False, fail_on_no_prepaid=True, ): prepaid_charge = component.fixed_charge invoicing_dates = component.get_component_invoicing_dates( self, override_start_date ) reset_ranges = component.get_component_reset_dates(self, override_start_date) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, component=component, start_date=start_date, end_date=end_date, invoicing_dates=br_invoicing_dates, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) new_invoicing_dates = set(br_invoicing_dates) if prepaid_charge and not ignore_prepaid: units = initial_units or prepaid_charge.units if units is None and fail_on_no_prepaid: raise PrepaymentMissingUnits( "No units specified for prepayment. This is usually an input error but may possibly be caused by inconsistent state in the backend." ) if units: ComponentChargeRecord.objects.create( organization=self.organization, billing_record=br, component_charge=prepaid_charge, component=component, start_date=start_date, end_date=end_date, units=units, ) new_invoicing_dates |= {start_date} new_invoicing_dates = sorted(list(new_invoicing_dates)) if new_invoicing_dates != br_invoicing_dates: br.invoicing_dates = new_invoicing_dates br.next_invoicing_date = new_invoicing_dates[0] br.save() brs.append(br) return brs def _create_recurring_charge_billing_records(self, recurring_charge): # first thign we want to see is if we need to charge "in advance" at all, that will # affect the way we calculate the reset ranges and invociing dates append_range_start = False if ( recurring_charge.charge_timing == RecurringCharge.ChargeTimingType.IN_ADVANCE ): addon_spec = recurring_charge.plan_version.addon_spec if ( addon_spec and addon_spec.flat_fee_invoicing_behavior_on_attach == AddOnSpecification.FlatFeeInvoicingBehaviorOnAttach.INVOICE_ON_SUBSCRIPTION_END ): # this is the ONLY case where its in advance and we don't want to append the range start. in this case they explicitly do not want to charge the flat fee on attach append_range_start = False else: append_range_start = True invoicing_dates = recurring_charge.get_recurring_charge_invoicing_dates( self, append_range_start ) reset_ranges = recurring_charge.get_recurring_charge_reset_dates(self) brs = [] for start_date, end_date, unadjusted_duration_microseconds in reset_ranges: one_past_end_added = False br_invoicing_dates = set() for inv_date in invoicing_dates: if one_past_end_added: break if inv_date >= start_date: br_invoicing_dates.add(inv_date) if inv_date >= end_date: one_past_end_added = True br_invoicing_dates = sorted(list(br_invoicing_dates)) br = BillingRecord.objects.create( organization=self.organization, subscription=self, recurring_charge=recurring_charge, invoicing_dates=br_invoicing_dates, start_date=start_date, end_date=end_date, unadjusted_duration_microseconds=unadjusted_duration_microseconds, ) brs.append(br) return brs def save(self, *args, **kwargs): if self.subscription_filters is None: self.subscription_filters = [] now = now_utc() timezone = self.customer.timezone if not self.end_date: day_anchor, month_anchor = ( self.billing_plan.day_anchor, self.billing_plan.month_anchor, ) self.end_date = calculate_end_date( self.billing_plan.plan.plan_duration, self.start_date, timezone, day_anchor=day_anchor, month_anchor=month_anchor, ) new = self._state.adding is True if new: new_filters = set(tuple(x) for x in self.subscription_filters) overlapping_subscriptions = SubscriptionRecord.objects.filter( Q(start_date__range=(self.start_date, self.end_date)) | Q(end_date__range=(self.start_date, self.end_date)), organization=self.organization, customer=self.customer, billing_plan=self.billing_plan, ) for subscription in overlapping_subscriptions: old_filters = set(tuple(x) for x in subscription.subscription_filters) if old_filters.issubset(new_filters) or new_filters.issubset( old_filters ): raise OverlappingPlans( f"Overlapping subscriptions with the same filters are not allowed. \n Plan: {self.billing_plan} \n Customer: {self.customer}. \n New dates: ({self.start_date, self.end_date}) \n New subscription_filters: {new_filters} \n Old dates: ({self.start_date, self.end_date}) \n Old subscription_filters: {list(old_filters)}" ) super(SubscriptionRecord, self).save(*args, **kwargs) if new: alerts = UsageAlert.objects.filter( organization=self.organization, plan_version=self.billing_plan ) now = now_utc() for alert in alerts: UsageAlertResult.objects.create( organization=self.organization, alert=alert, subscription_record=self, last_run_value=0, last_run_timestamp=now, ) def get_filters_dictionary(self): filters_dict = {f[0]: f[1] for f in self.subscription_filters} return filters_dict def amt_already_invoiced(self): billed_invoices = self.line_items.filter( ~Q(invoice__payment_status=Invoice.PaymentStatus.VOIDED) & ~Q(invoice__payment_status=Invoice.PaymentStatus.DRAFT), base__isnull=False, ).aggregate(tot=Sum("base"))["tot"] return billed_invoices or 0 def get_usage_and_revenue(self): sub_dict = {"components": []} # set up the billing plan for this subscription plan = self.billing_plan # set up other details of the subscription self.start_date self.end_date # extract other objects that we need when calculating usage self.customer plan_components_qs = plan.plan_components.all() # For each component of the plan, calculate usage/revenue for plan_component in plan_components_qs: plan_component_summary = plan_component.calculate_total_revenue(self) sub_dict["components"].append((plan_component.pk, plan_component_summary)) sub_dict["usage_amount_due"] = Decimal(0) for component_pk, component_dict in sub_dict["components"]: sub_dict["usage_amount_due"] += component_dict["revenue"] sub_dict["flat_amount_due"] = sum( x.amount for x in plan.recurring_charges.all() ) sub_dict["total_amount_due"] = ( sub_dict["flat_amount_due"] + sub_dict["usage_amount_due"] ) return sub_dict def cancel_subscription( self, bill_usage=True, flat_fee_behavior=FLAT_FEE_BEHAVIOR.CHARGE_FULL, invoice_now=True, ): from metering_billing.invoice import generate_invoice now = now_utc() if self.end_date <= now: logger.info("Subscription already ended.") raise SubscriptionAlreadyEnded self.flat_fee_behavior = flat_fee_behavior self.invoice_usage_charges = bill_usage self.auto_renew = False self.end_date = now self.save() for billing_record in self.billing_records.all(): billing_record.cancel_billing_record(now) addon_srs = [] for addon_sr in self.addon_subscription_records.filter(end_date__gt=now): addon_sr.cancel_subscription( bill_usage=bill_usage, flat_fee_behavior=flat_fee_behavior, invoice_now=False, ) addon_srs.append(addon_sr) srs = [self] + addon_srs if invoice_now: generate_invoice(srs) def turn_off_auto_renew(self): self.auto_renew = False self.save() def _billing_record_cancel_protocol(billing_record, cancel_date, invoice_now=True): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass else: # this means it's currently active billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now ) def _check_should_transfer_cancel_if_not( billing_record, cancel_date, invoice_now=True ): if billing_record.start_date >= cancel_date: # this billing record hasn't started yet, so we can just delete it billing_record.delete() return False elif billing_record.end_date < cancel_date: # this billing record has already ended, so we can just check if we should invoice it now or not. if invoice_now: billing_record.cancel_billing_record( cancel_date=cancel_date, change_invoice_date_to_cancel_date=invoice_now, ) else: # we don't want to invoice it now, so we can just leave the old invoice date pass return False return True def switch_plan( self, new_version, transfer_usage=True, invoice_now=True, component_fixed_charges_initial_units=None, ): from metering_billing.invoice import generate_invoice if component_fixed_charges_initial_units is None: component_fixed_charges_initial_units = [] component_fixed_charges_initial_units = { d["metric"]: d["units"] for d in component_fixed_charges_initial_units } # when switching a plan, there's a few things we need to take into account: # 1. flat fees dont transfer. Just end them. # 2. what does it mean for usage to transfer? Does it just mean the billing records for the old plan are cancelled and new ones are created for the new plan with a start date the same as previously? In the case we used to charge for x but no longer do, then perhaps in that case we do charge? If we weren;t doing the whole reset frequency thing anymore it would be awesome because we could just switch which plan component it points at and have the already billed for be a part of that. now = now_utc() sr = SubscriptionRecord.objects.create( organization=self.organization, customer=self.customer, billing_plan=new_version, start_date=now + relativedelta(microseconds=1), end_date=self.end_date, auto_renew=self.auto_renew, ) # current recurring_charge billing records must be canceled + billed for billing_record in self.billing_records.filter( recurring_charge__isnull=False, fully_billed=False ): # this is common enough that we made a method for it SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) # and now we generate the new recurring_charge billing records for recurring_charge in new_version.recurring_charges.all(): sr._create_recurring_charge_billing_records(recurring_charge) # same for component based billing records # so we're going to have to create a new billing record for each component, except if the metric coincides in the old plan and the new plan, then if transfer usage is true we have to do some wizardry to accomplish this # first a set of components we'll create from scratch... if we transfer usage from anywhere we'll remove it from this set pcs_to_create_charges_for = set(new_version.plan_components.all()) # dict of metrics for convenience new_version_metrics_map = { x.billable_metric: x for x in pcs_to_create_charges_for } for billing_record in self.billing_records.filter( component__isnull=False, fully_billed=False ): component = billing_record.component # if not transferring usage, simple, just cancel the billing record same as above if not transfer_usage: SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) else: metric = component.billable_metric if metric in new_version_metrics_map: # if the metric is in the new plan, we perform the surgery to switch the billing record to the new plan. Don't create from scratch. transfer = SubscriptionRecord._check_should_transfer_cancel_if_not( billing_record, now, invoice_now=invoice_now ) if transfer: new_component = new_version_metrics_map[metric] pcs_to_create_charges_for.remove(new_component) new_billing_records = sr._create_component_billing_records( new_component, override_start_date=billing_record.start_date, ignore_prepaid=True, ) override_billing_record = new_billing_records[0] # heres the surgery... open to improvements... this allows us to keep # info about what's been paid already though which is nice billing_record.subscription = sr billing_record.billing_plan = new_version billing_record.component = override_billing_record.component billing_record.start_date = override_billing_record.start_date billing_record.end_date = override_billing_record.end_date billing_record.unadjusted_duration_microseconds = ( override_billing_record.unadjusted_duration_microseconds ) billing_record.invoicing_dates = ( override_billing_record.invoicing_dates ) billing_record.next_invoicing_date = ( override_billing_record.next_invoicing_date ) billing_record.fully_billed = ( override_billing_record.fully_billed ) billing_record.save() charge_records = ( billing_record.component_charge_records.all().order_by( "start_date" ) ) for k, component_charge_record in enumerate(charge_records): new_component = override_billing_record.component component_charge_record.component = new_component component_charge_record.component_charge = ( new_component.charges.all().first() ) if k == len(charge_records) - 1: component_charge_record.end_date = ( billing_record.end_date ) component_charge_record.save() override_billing_record.delete() else: # if the metric is not in the new plan, we cancel the billing record SubscriptionRecord._billing_record_cancel_protocol( billing_record, now, invoice_now=invoice_now ) for pc in pcs_to_create_charges_for: metric = pc.billable_metric kwargs = {} if metric in component_fixed_charges_initial_units: kwargs["initial_units"] = component_fixed_charges_initial_units[metric] sr._create_component_billing_records(pc, **kwargs) self.end_date = now self.auto_renew = False self.save() generate_invoice([self, sr]) return sr def calculate_earned_revenue_per_day(self): return_dict = {} for billing_record in self.billing_records.all(): br_dict = billing_record.calculate_earned_revenue_per_day() for key in br_dict: if key not in return_dict: return_dict[key] = br_dict[key] else: return_dict[key] += br_dict[key] return return_dict def delete_subscription(self, delete_time=None): if delete_time is None: delete_time = now_utc() self.end_date = delete_time self.auto_renew = False for billing_record in self.billing_records.all(): if billing_record.start_date >= delete_time: # straight up delete it billing_record.delete() else: # essentially all we have to do is set everythign as already billed # this means we won't generate invoices for it anymore billing_record.end_date = min(billing_record.end_date, delete_time) billing_record.fully_billed = True billing_record.save() for addon_subscription in self.addon_subscription_records.all(): addon_subscription.delete_subscription(delete_time=delete_time) self.save() class Analysis(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="historical_analyses" ) analysis_name = models.TextField() start_date = models.DateField() end_date = models.DateField() time_created = models.DateTimeField(default=now_utc) analysis_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) kpis = ArrayField(models.TextField(choices=ANALYSIS_KPI.choices), default=list) analysis_results = models.JSONField(default=dict, blank=True) status = models.CharField( choices=EXPERIMENT_STATUS.choices, default=EXPERIMENT_STATUS.RUNNING, max_length=40, ) def save(self, *args, **kwargs): self.kpis = sorted(list(set(self.kpis))) super().save(*args, **kwargs) def __str__(self): return f"{self.analysis_name} - {self.start_date}" class Backtest(models.Model): """ This model is used to store the results of a backtest. """ backtest_name = models.TextField() start_date = models.DateField() end_date = models.DateField() organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtests" ) time_created = models.DateTimeField(default=now_utc) backtest_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) kpis = models.JSONField(default=list) backtest_results = models.JSONField(default=dict, blank=True) status = models.CharField( choices=EXPERIMENT_STATUS.choices, default=EXPERIMENT_STATUS.RUNNING, max_length=40, ) def __str__(self): return f"{self.backtest_name} - {self.start_date}" class BacktestSubstitution(models.Model): """ This model is used to substitute a backtest for a live trading session. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="backtest_substitutions", null=True, ) backtest = models.ForeignKey( Backtest, on_delete=models.CASCADE, related_name="backtest_substitutions" ) original_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) new_plan = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="+" ) def __str__(self): return f"{self.backtest}" class PricingUnit(models.Model): """ This model is used to store pricing units for a plan. """ organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True, related_name="pricing_units", ) code = models.CharField(max_length=10) name = models.TextField() symbol = models.CharField(max_length=10) custom = models.BooleanField(default=False) def __str__(self): ret = f"{self.code}" if self.symbol: ret += f"({self.symbol})" return ret class Meta: constraints = [ UniqueConstraint( fields=["organization", "code"], name="unique_code_per_org" ), UniqueConstraint( fields=["organization", "name"], name="unique_name_per_org" ), ] class CustomPricingUnitConversion(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="custom_pricing_unit_conversions", null=True, ) plan_version = models.ForeignKey( PlanVersion, on_delete=models.CASCADE, related_name="pricing_unit_conversions" ) from_unit = models.ForeignKey( PricingUnit, on_delete=models.CASCADE, related_name="+" ) from_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) to_unit = models.ForeignKey(PricingUnit, on_delete=models.CASCADE, related_name="+") to_qty = models.DecimalField( max_digits=20, decimal_places=10, validators=[MinValueValidator(0)] ) def setup_database_demo( organization_name, username=None, email=None, password=None, mode="create", org_type=Organization.OrganizationType.EXTERNAL_DEMO, size="small", ): if mode == "create": try: org = Organization.objects.get(organization_name=organization_name) Event.objects.filter(organization=org).delete() org.delete() logger.info("[DBDEMO]: Deleted existing organization, replacing") except Organization.DoesNotExist: logger.info("[DBDEMO]: creating from scratch") try: user = User.objects.get(username=username, email=email) except Exception: user = User.objects.create_user( username=username, email=email, password=password ) if user.organization is None: organization, _ = Organization.objects.get_or_create( organization_name=organization_name ) organization.organization_type = org_type user.organization = organization user.save() organization.save() elif mode == "regenerate": organization = Organization.objects.get(organization_name=organization_name) user = organization.users.all().first() WebhookEndpoint.objects.filter(organization=organization).delete() WebhookTrigger.objects.filter(organization=organization).delete() PlanVersion.objects.filter(organization=organization).delete() Plan.objects.filter(organization=organization).delete() Customer.objects.filter(organization=organization).delete() Event.objects.filter(organization=organization).delete() Metric.objects.filter(organization=organization).delete() Product.objects.filter(organization=organization).delete() CustomerBalanceAdjustment.objects.filter(organization=organization).delete() Feature.objects.filter(organization=organization).delete() Invoice.objects.filter(organization=organization).delete() APIToken.objects.filter(organization=organization).delete() TeamInviteToken.objects.filter(organization=organization).delete() PriceAdjustment.objects.filter(organization=organization).delete() ExternalPlanLink.objects.filter(organization=organization).delete() SubscriptionRecord.objects.filter(organization=organization).delete() Backtest.objects.filter(organization=organization).delete() PricingUnit.objects.filter(organization=organization).delete() NumericFilter.objects.filter(organization=organization).delete() CategoricalFilter.objects.filter(organization=organization).delete() PriceTier.objects.filter(organization=organization).delete() PlanComponent.objects.filter(organization=organization).delete() InvoiceLineItem.objects.filter(organization=organization).delete() BacktestSubstitution.objects.filter(organization=organization).delete() CustomPricingUnitConversion.objects.filter(organization=organization).delete() if user is None: organization.delete() return organization = user.organization big_customers = [] for _ in range(1 if size == "small" else 5): customer = Customer.objects.create( organization=organization, customer_name="BigCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) big_customers.append(customer) medium_customers = [] for _ in range(2 if size == "small" else 10): customer = Customer.objects.create( organization=organization, customer_name="MediumCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) medium_customers.append(customer) small_customers = [] for _ in range(4 if size == "small" else 20): customer = Customer.objects.create( organization=organization, customer_name="SmallCompany " + str(uuid.uuid4().hex)[:6], email=f"{str(uuid.uuid4().hex)}@{str(uuid.uuid4().hex)}.com", ) small_customers.append(customer) organization.subscription_filter_keys = ["environment"] organization.save() gb_storage = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric( { "organization": organization, "event_name": "storage_change", "property_name": "gb_storage", "usage_aggregation_type": METRIC_AGGREGATION.MAX, "billable_metric_name": "GB Months", "metric_type": METRIC_TYPE.GAUGE, "granularity": METRIC_GRANULARITY.MONTH, "event_type": EVENT_TYPE.TOTAL, } ) gb_storage_hours = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric( { "organization": organization, "event_name": "storage_change", "property_name": "gb_storage", "usage_aggregation_type": METRIC_AGGREGATION.MAX, "billable_metric_name": "GB Hours - Minute Proration", "metric_type": METRIC_TYPE.GAUGE, "granularity": METRIC_GRANULARITY.HOUR, "proration": METRIC_GRANULARITY.MINUTE, "event_type": EVENT_TYPE.TOTAL, } ) data_egress = METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric( { "organization": organization, "event_name": "data_egress", "property_name": "gb_data_egress", "usage_aggregation_type": METRIC_AGGREGATION.SUM, "billable_metric_name": "GB Data Egress", "metric_type": METRIC_TYPE.COUNTER, } ) insert_rate = METRIC_HANDLER_MAP[METRIC_TYPE.RATE].create_metric( { "organization": organization, "event_name": "db_insert", "property_name": "num_rows", "usage_aggregation_type": METRIC_AGGREGATION.SUM, "billable_aggregation_type": METRIC_AGGREGATION.MAX, "billable_metric_name": "Rows Insert Rate", "metric_type": METRIC_TYPE.RATE, "granularity": METRIC_GRANULARITY.DAY, } ) METRIC_HANDLER_MAP[METRIC_TYPE.COUNTER].create_metric( { "organization": organization, "event_name": "server_costs", "property_name": "cost", "usage_aggregation_type": METRIC_AGGREGATION.SUM, "billable_metric_name": "AWS Server Costs", "metric_type": METRIC_TYPE.COUNTER, "is_cost_metric": True, } ) gb_ram = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric( { "organization": organization, "event_name": "ram_change", "property_name": "gb_ram", "usage_aggregation_type": METRIC_AGGREGATION.MAX, "billable_metric_name": "GB RAM Months - Daily Proration", "metric_type": METRIC_TYPE.GAUGE, "granularity": METRIC_GRANULARITY.MONTH, "proration": METRIC_GRANULARITY.DAY, "event_type": EVENT_TYPE.TOTAL, } ) number_cpus = METRIC_HANDLER_MAP[METRIC_TYPE.GAUGE].create_metric( { "organization": organization, "event_name": "cpu_change", "property_name": "number_cpus", "usage_aggregation_type": METRIC_AGGREGATION.MAX, "billable_metric_name": "CPU Months - Daily Proration", "metric_type": METRIC_TYPE.GAUGE, "granularity": METRIC_GRANULARITY.MONTH, "proration": METRIC_GRANULARITY.DAY, "event_type": EVENT_TYPE.TOTAL, } ) # SET THE BILLING PLANS # FREE PLAN -- up to 10 GB storage, 100 GB data egress, 1000 rows/hour insert rate, 4GB RAM, 2 CPU -- flat fee plan = Plan.objects.create( plan_name="Free Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) free_bp = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=PricingUnit.objects.get(organization=organization, code="USD"), ) RecurringCharge.objects.create( organization=organization, plan_version=free_bp, amount=0, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=free_bp.currency, ) create_pc_plus_tiers_new( [free_bp], pcs_dict={ gb_storage: { "tiers": [ { "range_start": 0, "range_end": 10, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], }, data_egress: { "tiers": [ { "range_start": 0, "range_end": 100, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], }, insert_rate: { "tiers": [ { "range_start": 0, "range_end": 1000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], }, gb_ram: { "tiers": [ { "range_start": 0, "range_end": 4, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], }, number_cpus: { "tiers": [ { "range_start": 0, "range_end": 2, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], }, }, ) # BASIC PLAN -- up to 100 GB storage, 1000 GB data egress, 10,000 rows/hour insert rate, 8GB RAM, 4 CPUs -- flat fee plan = Plan.objects.create( plan_name="Basic Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) basic_bp_monthly = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=basic_bp_monthly, amount=250, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=basic_bp_monthly.currency, ) plan_yearly = Plan.objects.create( plan_name="Basic Plan", organization=organization, plan_duration=PLAN_DURATION.YEARLY, ) basic_bp_yearly = PlanVersion.objects.create( organization=organization, plan=plan_yearly, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=basic_bp_yearly, amount=2500, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=basic_bp_yearly.currency, ) create_pc_plus_tiers_new( [basic_bp_monthly, basic_bp_yearly], pcs_dict={ gb_storage: { "tiers": [ { "range_start": 0, "range_end": 100, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, data_egress: { "tiers": [ { "range_start": 0, "range_end": 1000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, insert_rate: { "tiers": [ { "range_start": 0, "range_end": 10_000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, gb_ram: { "tiers": [ { "range_start": 0, "range_end": 8, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, number_cpus: { "tiers": [ { "range_start": 0, "range_end": 4, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, }, ) # PAY AS YOU GO PLAN -- unlimited BUT pay for what you use.. $0.01/GB/hour storage above 24*30*100 = 7200 GB/hr, $0.05 per GB data egress above 1000 GB, 100,000 rows/hour insert rate, $50 per month per 4GB RAM up to 32GB with 8 prepaid, $25 per month per 1 CPU up to 16 CPUs with 4 prepaid plan = Plan.objects.create( plan_name="Pay As You Go Plan", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) pay_as_you_go_bp_monthly = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=pay_as_you_go_bp_monthly, amount=100, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=pay_as_you_go_bp_monthly.currency, ) plan_yearly = Plan.objects.create( plan_name="Pay As You Go Plan", organization=organization, plan_duration=PLAN_DURATION.YEARLY, ) pay_as_you_go_bp_yearly = PlanVersion.objects.create( organization=organization, plan=plan_yearly, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=pay_as_you_go_bp_yearly, amount=1000, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=pay_as_you_go_bp_yearly.currency, ) create_pc_plus_tiers_new( [pay_as_you_go_bp_monthly, pay_as_you_go_bp_yearly], pcs_dict={ gb_storage: { "tiers": [ { "range_start": 0, "range_end": 4000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, gb_storage_hours: { "tiers": [ { "range_start": 0, "range_end": 7200, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, }, { "range_start": 7200, "range_end": 20000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.0001, }, { "range_start": 20000, "range_end": None, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.00005, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, data_egress: { "tiers": [ { "range_start": 0, "range_end": 1000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, }, { "range_start": 1000, "range_end": None, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.05, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, insert_rate: { "tiers": [ { "range_start": 0, "range_end": 100_000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, gb_ram: { "tiers": [ { "range_start": 0, "range_end": 32, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 50, "metric_units_per_batch": 4, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, "prepaid_charge": { "units": 8, "charge_behavior": ComponentFixedCharge.ChargeBehavior.FULL, }, }, number_cpus: { "tiers": [ { "range_start": 0, "range_end": 16, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 25, "metric_units_per_batch": 1, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, "prepaid_charge": { "units": 4, "charge_behavior": ComponentFixedCharge.ChargeBehavior.FULL, }, }, }, ) # Pro Plan plan = Plan.objects.create( plan_name="Pro Plan - Usage Based", organization=organization, plan_duration=PLAN_DURATION.MONTHLY, ) pro_plan_bp_monthly = PlanVersion.objects.create( organization=organization, plan=plan, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=pro_plan_bp_monthly, amount=500, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=pay_as_you_go_bp_monthly.currency, ) plan_yearly = Plan.objects.create( plan_name="Pro Plan - Usage Based", organization=organization, plan_duration=PLAN_DURATION.YEARLY, ) pro_plan_bp_yearly = PlanVersion.objects.create( organization=organization, plan=plan_yearly, version=1, currency=free_bp.currency, ) RecurringCharge.objects.create( organization=organization, plan_version=pro_plan_bp_yearly, amount=5000, name="Flat Rate", charge_timing=RecurringCharge.ChargeTimingType.IN_ADVANCE, pricing_unit=pay_as_you_go_bp_yearly.currency, ) create_pc_plus_tiers_new( [pro_plan_bp_monthly, pro_plan_bp_yearly], pcs_dict={ gb_storage: { "tiers": [ { "range_start": 0, "range_end": 4000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, gb_storage_hours: { "tiers": [ { "range_start": 0, "range_end": 10_000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, }, { "range_start": 10_000, "range_end": 20000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.00005, }, { "range_start": 20000, "range_end": None, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.000025, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, data_egress: { "tiers": [ { "range_start": 0, "range_end": 2500, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, }, { "range_start": 2500, "range_end": None, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 0.035, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, insert_rate: { "tiers": [ { "range_start": 0, "range_end": 100_000, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.FREE, } ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, }, gb_ram: { "tiers": [ { "range_start": 0, "range_end": 32, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 40, "metric_units_per_batch": 4, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, "prepaid_charge": { "units": 16, "charge_behavior": ComponentFixedCharge.ChargeBehavior.FULL, }, }, number_cpus: { "tiers": [ { "range_start": 0, "range_end": 16, "batch_rounding_type": PriceTier.BatchRoundingType.NO_ROUNDING, "type": PriceTier.PriceTierType.PER_UNIT, "cost_per_batch": 20, "metric_units_per_batch": 1, }, ], "reset_interval_unit": PlanComponent.IntervalLengthType.MONTH, "reset_interval_count": 1, "prepaid_charge": { "units": 8, "charge_behavior": ComponentFixedCharge.ChargeBehavior.FULL, }, }, }, ) # ADDON: n_months = 4 if size == "small" else 12 start_of_sim = now_utc() - relativedelta(months=n_months) - relativedelta(days=5) for cust_set_name, cust_set in [ ("big", big_customers), ("medium", medium_customers), ("small", small_customers), ]: plan_dict = { "big": [ (0, basic_bp_monthly), (1 / 3, pay_as_you_go_bp_monthly), (5 / 6, pro_plan_bp_monthly), ], "medium": [ (0, free_bp), (1 / 6, basic_bp_monthly), (1 / 2, pay_as_you_go_bp_monthly), ], "small": [(0, free_bp), (1 / 3, basic_bp_monthly)], } for customer in cust_set: offset = np.random.randint(0, 30) beginning = start_of_sim + relativedelta(days=offset) for months in range(n_months): sub_start = beginning + relativedelta(months=months) cur_pct = (months + 1) / n_months for i in range(len(plan_dict[cust_set_name])): lower_bound = plan_dict[cust_set_name][i][0] upper_bound = ( plan_dict[cust_set_name][i + 1][0] if i + 1 < len(plan_dict[cust_set_name]) else float("inf") ) if lower_bound < cur_pct <= upper_bound: plan = plan_dict[cust_set_name][i][1] break # number of gauge events is irrespective n_storage_events = max(int(random.gauss(100, 20) // 1), 1) n_gb_ram_events = max(int(random.gauss(20, 3) // 1), 1) n_cpu_events = max(int(random.gauss(10, 2) // 1), 1) if plan == free_bp: max_storage = 10 max_gb_ram = 4 max_cpus = 2 max_egress = 100 max_insert_rate = 1000 elif plan == basic_bp_monthly: max_storage = 100 max_gb_ram = 8 max_cpus = 4 max_egress = 1000 max_insert_rate = 10_000 else: max_storage = 4000 max_gb_ram = 32 max_cpus = 16 max_egress = 10_000 max_insert_rate = 100_000 if cust_set_name == "big": pct_of_max__mean = 0.8 elif cust_set_name == "medium": pct_of_max__mean = 0.6 else: pct_of_max__mean = 0.6 if months == 0: sr = make_subscription_record( organization=organization, customer=customer, plan=plan, start_date=sub_start, is_new=months == 0, ) else: sr = SubscriptionRecord.objects.get( organization=organization, customer=customer, start_date__gt=sr.start_date, ) # ALL EVENTS events = [] # storage events dts = list(random_date(sr.start_date, sr.end_date, n_storage_events)) for dt in dts: gb_storage = ( min(random.gauss(pct_of_max__mean, 0.05), 1) * max_storage ) e = Event( organization=organization, event_name="storage_change", properties={ "gb_storage": gb_storage, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) # gb ram events dts = list(random_date(sr.start_date, sr.end_date, n_gb_ram_events)) for dt in dts: gb_ram = min(random.gauss(pct_of_max__mean, 0.05), 1) * max_gb_ram e = Event( organization=organization, event_name="ram_change", properties={ "gb_ram": gb_ram, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) # cpu events dts = list(random_date(sr.start_date, sr.end_date, n_cpu_events)) for dt in dts: number_cpus = ( min(random.gauss(pct_of_max__mean, 0.05), 1) * max_cpus ) e = Event( organization=organization, event_name="cpu_change", properties={ "number_cpus": number_cpus, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) # data egress events target_egress = ( min(random.gauss(pct_of_max__mean, 0.05), 1) * max_egress ) cur_egress = 0 n_egress_events = 0 while cur_egress < target_egress: dt = next(random_date(sr.start_date, sr.end_date, 1)) egress = np.random.random() * 25 if cur_egress + egress > target_egress: break e = Event( organization=organization, event_name="data_egress", properties={ "gb_data_egress": egress, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) cur_egress += egress n_egress_events += 1 # db insert events target_rows = ( min(random.gauss(pct_of_max__mean, 0.05), 1) * max_insert_rate * 10 ) cur_rows = 0 n_insert_events = 0 while cur_rows < target_rows: dt = next(random_date(sr.start_date, sr.end_date, 1)) rows = np.random.random() * 800 if cur_rows + rows > target_rows: break e = Event( organization=organization, event_name="db_insert", properties={ "num_rows": rows, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) cur_rows += rows n_insert_events += 1 # cost events total_events = ( n_cpu_events + n_gb_ram_events + n_storage_events + n_egress_events ) n_cost_events = total_events // 10 dts = list(random_date(sr.start_date, sr.end_date, n_cost_events)) for dt in dts: cost = np.random.random() * 8 e = Event( organization=organization, event_name="server_costs", properties={ "cost": cost, }, time_created=dt, idempotency_id=uuid.uuid4().hex, cust_id=customer.customer_id, ) events.append(e) next_pct = (months + 2) / n_months for i in range(len(plan_dict[cust_set_name])): lower_bound = plan_dict[cust_set_name][i][0] upper_bound = ( plan_dict[cust_set_name][i + 1][0] if i + 1 < len(plan_dict[cust_set_name]) else float("inf") ) if lower_bound < next_pct <= upper_bound: next_plan = plan_dict[cust_set_name][i][1] break Event.objects.bulk_create(events) if months == 0: generate_invoice( [sr], issue_date=sr.start_date, ) if now_utc() > sr.end_date: cur_bp = sr.billing_plan cur_replace_with = cur_bp.replace_with cur_bp.replace_with = next_plan cur_bp.save() generate_invoice( [sr], issue_date=sr.end_date, charge_next_plan=True, generate_next_subscription_record=True, ) cur_bp.replace_with = cur_replace_with cur_bp.save() analysis_results = {} end_date = now_utc() start_date = end_date - relativedelta(days=90) # analysis summary analysis_summary = [] for plan in [pro_plan_bp_monthly, pay_as_you_go_bp_monthly]: plan_ser = LightweightPlanVersionSerializer(plan).data kpis = [] for kpi, _ in ANALYSIS_KPI.choices: if kpi == ANALYSIS_KPI.TOTAL_REVENUE: value = ( InvoiceLineItem.objects.filter( associated_plan_version=pay_as_you_go_bp_monthly ).aggregate( total_revenue=Sum("amount", output_field=DecimalField()) )[ "total_revenue" ] or 0 ) if plan == pro_plan_bp_monthly: value = value * convert_to_decimal(random.gauss(0.8, 0.05)) elif kpi == ANALYSIS_KPI.NEW_REVENUE: value = ( InvoiceLineItem.objects.filter( associated_plan_version=pay_as_you_go_bp_monthly ).aggregate( total_revenue=Sum("amount", output_field=DecimalField()) )[ "total_revenue" ] or 0 ) if plan == pro_plan_bp_monthly: value = value * convert_to_decimal(random.gauss(0.8, 0.05)) value = value * Decimal("0.2") elif kpi == ANALYSIS_KPI.AVERAGE_REVENUE: value_tot = ( InvoiceLineItem.objects.filter( associated_plan_version=pay_as_you_go_bp_monthly ).aggregate( total_revenue=Sum("amount", output_field=DecimalField()) )[ "total_revenue" ] or 0 ) if plan == pro_plan_bp_monthly: value_tot = value_tot * convert_to_decimal(random.gauss(0.8, 0.05)) value_count = SubscriptionRecord.objects.filter( billing_plan=pay_as_you_go_bp_monthly ).count() if plan == pro_plan_bp_monthly: value_count = value_count * convert_to_decimal( random.gauss(0.8, 0.05) ) value = Decimal(value_tot) / Decimal(value_count) elif kpi == ANALYSIS_KPI.TOTAL_COST: cost_metrics = Metric.objects.filter( organization=organization, is_cost_metric=True, status=METRIC_STATUS.ACTIVE, ) metric_cost_dict = {} for metric in cost_metrics: metric_cost_dict[metric.billable_metric_name] = Decimal(0) usage_ret = metric.get_daily_total_usage( start_date, end_date, customer=customer, ).get(customer, {}) for _, usage in usage_ret.items(): metric_cost_dict[metric.billable_metric_name] += Decimal(usage) value = sum(metric_cost_dict.values()) if plan == pro_plan_bp_monthly: value = value * convert_to_decimal(random.gauss(1.2, 0.05)) elif kpi == ANALYSIS_KPI.PROFIT: continue else: value = Decimal("3.16") if plan == pro_plan_bp_monthly: value = value * convert_to_decimal(random.gauss(1.2, 0.05)) single_kpi = {"kpi": kpi, "value": value} kpis.append(single_kpi) revenue_kpi = [x for x in kpis if x["kpi"] == ANALYSIS_KPI.TOTAL_REVENUE][0][ "value" ] cost_kpi = [x for x in kpis if x["kpi"] == ANALYSIS_KPI.TOTAL_COST][0]["value"] profit_kpi = { "kpi": ANALYSIS_KPI.PROFIT, "value": revenue_kpi - cost_kpi, } kpis.append(profit_kpi) single_plan_analysis = { "plan": plan_ser, "kpis": kpis, } analysis_summary.append(single_plan_analysis) analysis_results["analysis_summary"] = analysis_summary # revenue per day graph revenue_per_day = [] for date in dates_bwn_two_dts(start_date, end_date): d = { "date": str(date), } rev_per_plan = [] for plan in [pro_plan_bp_monthly, pay_as_you_go_bp_monthly]: plan_repr = LightweightPlanVersionSerializer(plan).data # create random gaussin with mean 1/90 and standard dev a tenth of that kpi_dict = [ x for x in analysis_summary if x["plan"]["plan_id"] == plan_repr["plan_id"] ][0] revenue_kpi = [ x for x in kpi_dict["kpis"] if x["kpi"] == ANALYSIS_KPI.TOTAL_REVENUE ][0]["value"] value = revenue_kpi * Decimal(random.gauss(1 / 90, 1 / 500)) single_plan_rev = { "plan": plan_repr, "revenue": value, } rev_per_plan.append(single_plan_rev) d["revenue_per_plan"] = rev_per_plan revenue_per_day.append(d) analysis_results["revenue_per_day_graph"] = revenue_per_day # revenue by metric graph revenue_by_metric = [] for plan in [pro_plan_bp_monthly, pay_as_you_go_bp_monthly]: plan_repr = LightweightPlanVersionSerializer(plan).data by_metric = [] kpi_dict = [ x for x in analysis_summary if x["plan"]["plan_id"] == plan_repr["plan_id"] ][0] revenue_kpi = [ x for x in kpi_dict["kpis"] if x["kpi"] == ANALYSIS_KPI.TOTAL_REVENUE ][0]["value"] pcs = plan.plan_components.all() for pc in pcs: metric = pc.billable_metric value = revenue_kpi * Decimal( random.gauss(1 / len(pcs), 1 / (len(pcs) * 2)) ) single_metric = { "metric": LightweightMetricSerializer(metric).data, "revenue": value, } by_metric.append(single_metric) single_plan_metrics = { "plan": plan_repr, "by_metric": by_metric, } revenue_by_metric.append(single_plan_metrics) analysis_results["revenue_by_metric_graph"] = revenue_by_metric # top customers by plan top_customers_by_plan = [] for plan in [pro_plan_bp_monthly, pay_as_you_go_bp_monthly]: customers = Customer.objects.filter( organization=organization, ).order_by( "?" )[:5] top_customers_by_total_revenue = [] for customer in customers: kpi_dict = [ x for x in analysis_summary if x["plan"]["plan_id"] == plan_repr["plan_id"] ][0] revenue_kpi = [ x for x in kpi_dict["kpis"] if x["kpi"] == ANALYSIS_KPI.TOTAL_REVENUE ][0]["value"] value = revenue_kpi * convert_to_decimal( abs(Decimal(random.gauss(1 / 5, 1 / 10))) ) single_customer = { "customer": LightweightCustomerSerializer(customer).data, "value": value, } top_customers_by_total_revenue.append(single_customer) top_customers_by_total_revenue = sorted( top_customers_by_total_revenue, key=lambda x: x["value"], reverse=True ) top_customers_by_average_revenue = [] for customer in customers: kpi_dict = [ x for x in analysis_summary if x["plan"]["plan_id"] == plan_repr["plan_id"] ][0] revenue_kpi = [ x for x in kpi_dict["kpis"] if x["kpi"] == ANALYSIS_KPI.TOTAL_REVENUE ][0]["value"] value = ( revenue_kpi * convert_to_decimal(abs(Decimal(random.gauss(1 / 5, 1 / 10)))) / convert_to_decimal(abs(random.gauss(3, 1))) ) single_customer = { "customer": LightweightCustomerSerializer(customer).data, "value": value, } top_customers_by_average_revenue.append(single_customer) top_customers_by_average_revenue = sorted( top_customers_by_average_revenue, key=lambda x: x["value"], reverse=True ) single_plan = { "plan": LightweightPlanVersionSerializer(plan).data, "top_customers_by_average_revenue": top_customers_by_average_revenue, "top_customers_by_revenue": top_customers_by_total_revenue, } top_customers_by_plan.append(single_plan) analysis_results["top_customers_by_plan"] = top_customers_by_plan # create actual analysis analysis_results = round_all_decimals_to_two_places(analysis_results) analysis_results = make_all_decimals_strings(analysis_results) Analysis.objects.create( organization=organization, analysis_results=analysis_results, analysis_name="test", start_date=start_date, end_date=end_date, kpis=[kpi for kpi, _ in ANALYSIS_KPI.choices], status=EXPERIMENT_STATUS.COMPLETED, ) return user
null
6,990
import datetime import itertools import logging import random import time import uuid from decimal import Decimal import numpy as np import pytz from dateutil.relativedelta import relativedelta from django.db.models import DecimalField, Sum from model_bakery import baker from api.serializers.model_serializers import ( LightweightCustomerSerializer, LightweightMetricSerializer, LightweightPlanVersionSerializer, ) from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP from metering_billing.invoice import generate_invoice from metering_billing.models import ( Analysis, APIToken, Backtest, BacktestSubstitution, CategoricalFilter, ComponentFixedCharge, Customer, CustomerBalanceAdjustment, CustomPricingUnitConversion, Event, ExternalPlanLink, Feature, Invoice, InvoiceLineItem, Metric, NumericFilter, Organization, Plan, PlanComponent, PlanVersion, PriceAdjustment, PriceTier, PricingUnit, Product, RecurringCharge, SubscriptionRecord, TeamInviteToken, User, WebhookEndpoint, WebhookTrigger, ) from metering_billing.tasks import run_backtest, run_generate_invoice from metering_billing.utils import ( convert_to_decimal, date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_decimals_strings, now_utc, round_all_decimals_to_two_places, ) from metering_billing.utils.enums import ( ANALYSIS_KPI, BACKTEST_KPI, EVENT_TYPE, EXPERIMENT_STATUS, METRIC_AGGREGATION, METRIC_GRANULARITY, METRIC_STATUS, METRIC_TYPE, PLAN_DURATION, ) The provided code snippet includes necessary dependencies for implementing the `gaussian_raise_issue` function. Write a Python function `def gaussian_raise_issue(n)` to solve the following problem: Generate `n` stacktrace lengths with a gaussian distribution Here is the function: def gaussian_raise_issue(n): "Generate `n` stacktrace lengths with a gaussian distribution" for _ in range(n): yield { "stacktrace_len": round(random.gauss(50, 15), 0), "latency": round(max(random.gauss(325, 25), 0), 2), "project": random.choice(["project1", "project2", "project3"]), }
Generate `n` stacktrace lengths with a gaussian distribution
6,991
import uuid from django.db import migrations def gen_uuid(apps, schema_editor): Subscription = apps.get_model("metering_billing", "Subscription") for row in Subscription.objects.all(): row.uuid = uuid.uuid4() row.save(update_fields=["subscription_uid"])
null
6,992
from django.db import migrations def move_from_seconds_to_microseconds(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for row in SubscriptionRecord.objects.all(): row.unadjusted_duration_microseconds = row.unadjusted_duration_seconds * 10**6 row.save()
null
6,993
import uuid from django.db import migrations from django.db.models import Q def make_all_emails_nonnull(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") c_list = Customer.objects.filter(Q(email="") | Q(email__isnull=True)) for c in c_list: c.email = f"{str(uuid.uuid4().hex)}@example.com" c.save()
null
6,994
from django.db import migrations def transfer_invoice_status(apps, schema_editor): Invoice = apps.get_model("metering_billing", "Invoice") for inv in Invoice.objects.all(): if inv.payment_status_old == "draft": inv.payment_status = 1 elif inv.payment_status_old == "voided": inv.payment_status = 2 elif inv.payment_status_old == "paid": inv.payment_status = 3 elif inv.payment_status_old == "unpaid": inv.payment_status = 4 inv.save()
null
6,995
from django.db import migrations def transfer_component_granularity_to_metric(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): if metric.metric_type == "stateful": metric.metric_type = "gauge" metric.save()
null
6,996
from django.db import migrations def reverse_transfer_component_granularity_to_metric(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): if metric.metric_type == "gauge": metric.metric_type = "stateful" metric.save()
null
6,997
from django.db import migrations METRIC_HANDLER_MAP = { METRIC_TYPE.COUNTER: CounterHandler, METRIC_TYPE.GAUGE: GaugeHandler, METRIC_TYPE.RATE: RateHandler, METRIC_TYPE.CUSTOM: CustomHandler, } def refresh_mat_views(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP for metric in Metric.objects.all(): handler = METRIC_HANDLER_MAP[metric.metric_type] handler.archive_metric(metric) metric.mat_views_provisioned = False metric.save() ## INITADMIN WILL TAKE CARE OF REFRESHING THE VIEWS
null
6,998
from django.db import migrations def transfer_data(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") Customer = apps.get_model("metering_billing", "Customer") StripeCustomerIntegration = apps.get_model( "metering_billing", "StripeCustomerIntegration" ) BraintreeCustomerIntegration = apps.get_model( "metering_billing", "BraintreeCustomerIntegration" ) StripeOrganizationIntegration = apps.get_model( "metering_billing", "StripeOrganizationIntegration" ) BraintreeOrganizationIntegration = apps.get_model( "metering_billing", "BraintreeOrganizationIntegration" ) # Transfer data from Customer to Stripe/Braintree Customer Integration stripe_customers = Customer.objects.filter( integrations__has_key="stripe", integrations__stripe__has_key="id" ).select_related("organization") for customer in stripe_customers: integration = StripeCustomerIntegration.objects.create( organization=customer.organization, stripe_customer_id=customer.integrations["stripe"]["id"], ) customer.stripe_integration = integration customer.save() braintree_customers = Customer.objects.filter( integrations__has_key="braintree", integrations__braintree__has_key="id" ).select_related("organization") for customer in braintree_customers: integration = BraintreeCustomerIntegration.objects.create( organization=customer.organization, braintree_customer_id=customer.integrations["braintree"]["id"], ) customer.braintree_integration = integration customer.save() # Transfer data from Organization to Stripe/Braintree Organization Integration stripe_organizations = Organization.objects.filter( payment_provider_ids__has_key="stripe", payment_provider_ids__stripe__has_key="id", ) for organization in stripe_organizations: integration = StripeOrganizationIntegration.objects.create( organization=organization, stripe_account_id=organization.payment_provider_ids["stripe"]["id"], ) organization.stripe_integration = integration organization.save() braintree_organizations = Organization.objects.filter( payment_provider_ids__has_key="braintree", payment_provider_ids__braintree__has_key="id", ) for organization in braintree_organizations: integration = BraintreeOrganizationIntegration.objects.create( organization=organization, braintree_merchant_id=organization.payment_provider_ids["braintree"]["id"], ) organization.braintree_integration = integration organization.save()
null
6,999
import uuid from django.conf import settings from django.db import migrations, models def fill_uuid(apps, schema_editor): IdempotenceCheck = apps.get_model("metering_billing", "IdempotenceCheck") for check in IdempotenceCheck.objects.all(): check.uuidv5_idempotency_id = uuid.uuid5( settings.IDEMPOTENCY_ID_NAMESPACE, check.idempotency_id ) check.save()
null
7,000
from django.db import migrations from metering_billing.utils.enums import BATCH_ROUNDING_TYPE, PRICE_TIER_TYPE def migrate_plancomponetns_to_price_tiers(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") PriceTier = apps.get_model("metering_billing", "PriceTier") PlanVersion = apps.get_model("metering_billing", "PlanVersion") for pv in PlanVersion.objects.all().prefetch_related("components"): for pc in pv.components.all(): new_pc = PlanComponent.objects.create( billable_metric=pc.billable_metric, plan_version=pv, ) starting_point = 0 if pc.free_metric_units and pc.free_metric_units > 0: PriceTier.objects.create( plan_component=new_pc, metric_units_per_batch=pc.free_metric_units, type=PRICE_TIER_TYPE.FREE, range_start=0, range_end=pc.free_metric_units, ) starting_point = pc.free_metric_units price_tier_dict = { "plan_component": new_pc, "type": PRICE_TIER_TYPE.PER_UNIT, "range_start": starting_point, "cost_per_batch": pc.cost_per_batch, "metric_units_per_batch": pc.metric_units_per_batch, "batch_rounding_type": BATCH_ROUNDING_TYPE.NO_ROUNDING, "range_end": None, } if pc.max_metric_units and pc.max_metric_units > 0: price_tier_dict["range_end"] = pc.max_metric_units PriceTier.objects.create(**price_tier_dict) PlanComponent.objects.filter(plan_version__isnull=True).delete()
null
7,001
from django.db import migrations, models def change_organization_setting_names(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for setting in OrganizationSetting.objects.all(): if setting.setting_name == "subscription_filters": setting.setting_name = "subscription_filter_keys" setting.save() elif setting.setting_name == "invoice_grace_period": setting.setting_name = "payment_grace_period" setting.save()
null
7,002
import uuid from django.db import migrations def make_unique_uuids(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for plan_component in PlanComponent.objects.all(): plan_component.usage_component_id = uuid.uuid4() plan_component.save() for recurring_charge in RecurringCharge.objects.all(): recurring_charge.recurring_charge_id = uuid.uuid4() recurring_charge.save()
null
7,003
import uuid from django.db import migrations def transfer_text_to_uuid(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") for org in Organization.objects.all(): org.organization_id = uuid.uuid4() org.save() Backtest = apps.get_model("metering_billing", "Backtest") for backtest in Backtest.objects.all(): backtest.backtest_id = uuid.uuid4() backtest.save() CustomerBalanceAdjustment = apps.get_model( "metering_billing", "CustomerBalanceAdjustment" ) for adjustment in CustomerBalanceAdjustment.objects.all(): adjustment.adjustment_id = uuid.uuid4() adjustment.save() Feature = apps.get_model("metering_billing", "Feature") for feature in Feature.objects.all(): feature.feature_id = uuid.uuid4() feature.save() Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): metric.metric_id = uuid.uuid4() metric.save() Invoice = apps.get_model("metering_billing", "Invoice") for invoice in Invoice.objects.all(): invoice.invoice_id = uuid.uuid4() invoice.save() InvoiceLineItem = apps.get_model("metering_billing", "InvoiceLineItem") for line_item in InvoiceLineItem.objects.all(): line_item.invoice_line_item_id = uuid.uuid4() line_item.save() OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for setting in OrganizationSetting.objects.all(): setting.setting_id = uuid.uuid4() setting.save() Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.all(): plan.plan_id = uuid.uuid4() plan.save() PlanVersion = apps.get_model("metering_billing", "PlanVersion") for plan_version in PlanVersion.objects.all(): plan_version.version_id = uuid.uuid4() plan_version.save() Subscription = apps.get_model("metering_billing", "Subscription") for subscription in Subscription.objects.all(): subscription.subscription_id = uuid.uuid4() subscription.save() SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for subscription_record in SubscriptionRecord.objects.all(): subscription_record.subscription_record_id = uuid.uuid4() subscription_record.save() Tag = apps.get_model("metering_billing", "Tag") for tag in Tag.objects.all(): tag.tag_id = uuid.uuid4() tag.save() UsageAlert = apps.get_model("metering_billing", "UsageAlert") for usage_alert in UsageAlert.objects.all(): usage_alert.usage_alert_id = uuid.uuid4() usage_alert.save() WebhookEndpoint = apps.get_model("metering_billing", "WebhookEndpoint") for webhook in WebhookEndpoint.objects.all(): webhook.webhook_endpoint_id = uuid.uuid4() webhook.webhook_secret = uuid.uuid4() webhook.save()
null
7,004
from django.db import migrations, models def delete_dups(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") for row in Customer.objects.all().order_by("pk"): org = row.organization email = row.email pk = row.pk others = Customer.objects.filter(organizaiton=org, email=email).exclude(pk=pk) others.delete()
null
7,005
from django.db import migrations def copy_events_to_idempotencecheck(apps, schema_editor): Event = apps.get_model("metering_billing", "Event") IdempotenceCheck = apps.get_model("metering_billing", "IdempotenceCheck") for event in Event.objects.order_by( "idempotency_id", "organization", "-time_created" ).values("time_created", "idempotency_id", "organization"): try: IdempotenceCheck.objects.get( idempotency_id=event["idempotency_id"], organization_id=event["organization"], ) except IdempotenceCheck.DoesNotExist: IdempotenceCheck.objects.create( time_created=event["time_created"], idempotency_id=event["idempotency_id"], organization_id=event["organization"], )
null
7,006
from django.db import migrations def migrate_customer_and_organization_addresses(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") Organization = apps.get_model("metering_billing", "Organization") Address = apps.get_model("metering_billing", "Address") # Migrate customer addresses for customer in Customer.objects.filter(properties__address__isnull=False): properties = customer.properties address_data = properties.pop("address", {}) address, _ = Address.objects.get_or_create( organization=customer.organization, city=address_data.get("city"), country=address_data.get("country"), line1=address_data.get("line1"), line2=address_data.get("line2"), postal_code=address_data.get("postal_code"), state=address_data.get("state"), ) customer.billing_address = address customer.shipping_address = address customer.save() # Migrate organization addresses for org in Organization.objects.filter(properties__address__isnull=False): properties = org.properties address_data = properties.pop("address", {}) address, _ = Address.objects.get_or_create( organization=org, city=address_data.get("city"), country=address_data.get("country"), line1=address_data.get("line1"), line2=address_data.get("line2"), postal_code=address_data.get("postal_code"), state=address_data.get("state"), ) org.address = address org.properties = properties org.save()
null
7,007
from django.db import migrations def prepopulate(apps, schema_editor): apps.get_model("metering_billing", "PlanComponent") apps.get_model("metering_billing", "PriceTier") apps.get_model("metering_billing", "PlanVersion") PricingUnit = apps.get_model("metering_billing", "PricingUnit") Invoice = apps.get_model("metering_billing", "Invoice") Customer = apps.get_model("metering_billing", "Customer") Organization = apps.get_model("metering_billing", "Organization") supported_currencies = [ ("US Dollar", "USD", "$"), ("Euro", "EUR", "€"), ("Pound", "GBP", "£"), ] for name, code, symbol in supported_currencies: PricingUnit.objects.get_or_create(name=name, code=code, symbol=symbol) usd = PricingUnit.objects.get(code="USD") for inv in Invoice.objects.all(): inv.pricing_unit = usd inv.save() for cust in Customer.objects.all(): cust.default_currency = usd cust.save() for org in Organization.objects.all(): org.default_currency = usd org.save()
null
7,008
from django.db import migrations def mark_as_demo(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") Organization.objects.filter(company_name__startswith="demo_").update(is_demo=True)
null
7,009
from django.db import migrations def set_not_before(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") for version in PlanVersion.objects.all(): if version.created_on: version.active_from = version.created_on version.save() Plan = apps.get_model("metering_billing", "Plan") for version in Plan.objects.all(): if version.created_on: version.active_from = version.created_on version.save()
null
7,010
from django.db import migrations def set_not_after(apps, schema_editor): from metering_billing.utils import now_utc PlanVersion = apps.get_model("metering_billing", "PlanVersion") for version in PlanVersion.objects.all(): if version.status == "active": version.active_to = None else: if version.status == "archived": version.deleted = now_utc() version.active_to = now_utc() version.save() Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.all(): if plan.status == "active": plan.active_to = None else: if plan.status == "archived": plan.deleted = now_utc() plan.active_to = now_utc() plan.save()
null
7,011
import uuid from django.conf import settings from django.db import migrations def set_uuidv5_customer_id(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") HistoricalCustomer = apps.get_model("metering_billing", "HistoricalCustomer") CUSTOMER_ID_NAMESPACE = settings.CUSTOMER_ID_NAMESPACE for customer in Customer.objects.all(): customer.uuidv5_customer_id = uuid.uuid5( CUSTOMER_ID_NAMESPACE, customer.customer_id ) customer.save() for historical_customer in HistoricalCustomer.objects.all(): historical_customer.uuidv5_customer_id = uuid.uuid5( CUSTOMER_ID_NAMESPACE, historical_customer.customer_id ) historical_customer.save()
null
7,012
from django.db import migrations def transfer_events(apps, schema_editor): UsageEvent = apps.get_model("metering_billing", "UsageEvent") Event = apps.get_model("metering_billing", "Event") for event in Event.objects.all(): UsageEvent.objects.create( event_name=event.event_name, time_created=event.time_created, properties=event.properties, idempotency_id=event.idempotency_id, customer_id=event.customer_id, organization_id=event.organization_id, cust_id=event.cust_id, inserted_at=event.inserted_at, )
null
7,013
import uuid from django.db import migrations def unique_team_id(apps, schema_editor): Team = apps.get_model("metering_billing", "Team") for team in Team.objects.all(): team.team_id = uuid.uuid4() team.save()
null
7,014
from django.db import migrations def copy_addon_spec(apps, schema_editor): Plan = apps.get_model("metering_billing", "Plan") AddOnSpecification = apps.get_model("metering_billing", "AddOnSpecification") for plan_template in Plan.objects.filter(addon_spec__isnull=False): plan_template.is_addon = True plan_template.save() addon_spec = plan_template.addon_spec for plan_version in plan_template.versions.all(): addon_spec_copy = AddOnSpecification.objects.create( organization=addon_spec.organization, billing_frequency=addon_spec.billing_frequency, flat_fee_invoicing_behavior_on_attach=addon_spec.flat_fee_invoicing_behavior_on_attach, ) plan_version.addon_spec = addon_spec_copy plan_version.save() addon_spec.delete()
null
7,015
import time from django.db import migrations def transfer_subscription_keys(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for org_setting in OrganizationSetting.objects.filter( setting_name="subscription_filter_keys" ): organization = org_setting.organization organization.subscription_filter_keys = org_setting.setting_values organization.save() # just to be safe w the timescale background workers time.sleep(1)
null
7,016
from django.db import migrations def migrate_stateful_other_to_max(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter( metric_type="rate", usage_aggregation_type="unique", ).update(usage_aggregation_type="count", property_name=None)
null
7,017
from django.db import migrations def transfer_text_to_int(apps, schema_editor): PriceTier = apps.get_model("metering_billing", "PriceTier") for price_tier in PriceTier.objects.all(): if price_tier.type_old == "flat": price_tier.type = 1 elif price_tier.type_old == "per_unit": price_tier.type = 2 elif price_tier.type_old == "free": price_tier.type = 3 if price_tier.batch_rounding_type_old == "round_up": price_tier.batch_rounding_type = 1 elif price_tier.batch_rounding_type_old == "round_down": price_tier.batch_rounding_type = 2 elif price_tier.batch_rounding_type_old == "round_nearest": price_tier.batch_rounding_type = 3 elif price_tier.batch_rounding_type_old == "no_rounding": price_tier.batch_rounding_type = 4 price_tier.save()
null
7,018
from django.db import migrations def transfer_org_settings(apps, schema_editor): OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for org_setting in OrganizationSetting.objects.filter( setting_name="generate_customer_after_creating_in_lotus" ): organization = org_setting.organization organization.gen_cust_in_stripe_after_lotus = org_setting.setting_values[ "value" ] organization.save() for org_setting in OrganizationSetting.objects.filter( setting_name="gen_cust_in_braintree_after_lotus" ): organization = org_setting.organization organization.gen_cust_in_braintree_after_lotus = org_setting.setting_values[ "value" ] organization.save() for org_setting in OrganizationSetting.objects.filter( setting_name="payment_grace_period" ): organization = org_setting.organization organization.payment_grace_period = org_setting.setting_values["value"] organization.save() for org_setting in OrganizationSetting.objects.filter( setting_name="crm_customer_source" ): organization = org_setting.organization organization.lotus_is_customer_source_for_salesforce = ( org_setting.setting_values["salesforce"] ) organization.save()
null
7,019
import uuid from django.db import migrations def make_metric_ids_unique(apps, schema_editor): Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): metric.metric_id = str(uuid.uuid4()) metric.save()
null
7,020
from django.db import migrations def fill_null_pricing_unit_in(apps, schema_editor): RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for recurring_charge in RecurringCharge.objects.filter(pricing_unit__isnull=True): recurring_charge.pricing_unit = recurring_charge.plan_version.currency recurring_charge.save()
null
7,021
from django.db import migrations from django.db.models import Count, Max def remove_duplicates(apps, schema_editor): Event = apps.get_model("metering_billing", "Event") unique_fields = ["organization_id", "idempotency_id"] duplicates = ( Event.objects.values(*unique_fields) .order_by() .annotate( max_time_created=Max("time_created"), cnt=Count("*"), ) .filter(cnt__gt=1) ) for duplicate in duplicates: ( Event.objects.filter( organization_id=duplicate["organization_id"], idempotency_id=duplicate["idempotency_id"], ) .exclude(time_created=duplicate["max_time_created"]) .delete() )
null
7,022
from django.db import migrations def transfer_flat_fees_to_recurring(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") RecurringCharge = apps.get_model("metering_billing", "RecurringCharge") for plan_version in PlanVersion.objects.all(): if plan_version.flat_rate is not None and plan_version.flat_rate > 0: if plan_version.flat_fee_billing_type == "in_advance": charge_timing = 1 # IN_ADVANCE = (1, "in_advance") elif plan_version.flat_fee_billing_type == "in_arrears": charge_timing = 2 # IN_ARREARS = (2, "in_arrears") RecurringCharge.objects.create( organization=plan_version.organization, name="Flat Fee", plan_version=plan_version, charge_timing=charge_timing, charge_behavior=1, # PRORATE = (1, "prorate") amount=plan_version.flat_rate, pricing_unit=plan_version.pricing_unit, )
null
7,023
import metering_billing.utils.utils from django.db import migrations, models def transfer_custom_plans(apps, schema_editor): Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.filter(target_customer__isnull=False): parent_plan = plan.parent_plan num_versions_in_parent = parent_plan.versions.count() i = 1 for version in plan.versions.all(): version.version = num_versions_in_parent + i version.plan = parent_plan version.target_customers.add(plan.target_customer) version.is_custom = True version.save() i += 1 Plan.objects.filter(target_customer__isnull=False).delete()
null
7,024
import uuid from uuid import UUID from django.db import migrations def transfer_text_to_uuid(apps, schema_editor): Organization = apps.get_model("metering_billing", "Organization") for org in Organization.objects.all(): uuid_string = org.organization_id_old.replace("org_", "") uuid_instance = UUID(uuid_string) org.organization_id = uuid_instance org.webhooks_provisioned = False org.save() Backtest = apps.get_model("metering_billing", "Backtest") for backtest in Backtest.objects.all(): uuid_string = backtest.backtest_id_old.replace("btst_", "") uuid_instance = UUID(uuid_string) backtest.backtest_id = uuid_instance backtest.save() CustomerBalanceAdjustment = apps.get_model( "metering_billing", "CustomerBalanceAdjustment" ) for adjustment in CustomerBalanceAdjustment.objects.all(): uuid_string = adjustment.adjustment_id_old.replace("custbaladj_", "") uuid_instance = UUID(uuid_string) adjustment.adjustment_id = uuid_instance adjustment.save() Feature = apps.get_model("metering_billing", "Feature") for feature in Feature.objects.all(): feature.feature_id = uuid.uuid4() feature.save() Metric = apps.get_model("metering_billing", "Metric") for metric in Metric.objects.all(): uuid_string = metric.metric_id_old.replace("metric_", "") uuid_instance = UUID(uuid_string) metric.metric_id = uuid_instance metric.save() Invoice = apps.get_model("metering_billing", "Invoice") for invoice in Invoice.objects.all(): invoice.invoice_id = uuid.uuid4() invoice.save() InvoiceLineItem = apps.get_model("metering_billing", "InvoiceLineItem") for line_item in InvoiceLineItem.objects.all(): line_item.invoice_line_item_id = uuid.uuid4() line_item.save() Organization = apps.get_model("metering_billing", "Organization") for org in Organization.objects.all(): org.organization_id = uuid.uuid4() org.save() OrganizationSetting = apps.get_model("metering_billing", "OrganizationSetting") for setting in OrganizationSetting.objects.all(): uuid_string = setting.setting_id_old uuid_instance = UUID(uuid_string) setting.setting_id = uuid_instance setting.save() Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.all(): uuid_string = plan.plan_id.replace("plan_", "") uuid_instance = UUID(uuid_string) plan.plan_id = uuid_instance plan.save() PlanVersion = apps.get_model("metering_billing", "PlanVersion") for plan_version in PlanVersion.objects.all(): uuid_string = plan_version.version_id_old.replace("plnvrs_", "") uuid_instance = UUID(uuid_string) plan_version.plan_version_id = uuid_instance plan_version.save() Subscription = apps.get_model("metering_billing", "Subscription") for subscription in Subscription.objects.all(): uuid_string = subscription.subscription_id_old.replace("subs_", "") uuid_instance = UUID(uuid_string) subscription.subscription_id = uuid_instance subscription.save() SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for subscription_record in SubscriptionRecord.objects.all(): uuid_string = subscription_record.subscription_record_id_old.replace( "subsrec_", "" ) uuid_instance = UUID(uuid_string) subscription.subscription_id = uuid_instance subscription.save() Tag = apps.get_model("metering_billing", "Tag") for tag in Tag.objects.all(): uuid_string = tag.tag_id_old.replace("tag_", "") uuid_instance = UUID(uuid_string) tag.tag_id = uuid_instance tag.save() UsageAlert = apps.get_model("metering_billing", "UsageAlert") for usage_alert in UsageAlert.objects.all(): uuid_string = usage_alert.alert_id_old.replace("usgalert_", "") uuid_instance = UUID(uuid_string) usage_alert.alert_id = uuid_instance usage_alert.save() WebhookEndpoint = apps.get_model("metering_billing", "WebhookEndpoint") for webhook in WebhookEndpoint.objects.all(): uuid_string = webhook.webhook_endpoint_id_old.replace("whend_", "") uuid_instance = UUID(uuid_string) webhook.webhook_endpoint_id = uuid_instance uuid_string = webhook.webhook_secret_old.replace("whsec_", "") uuid_instance = UUID(uuid_string) webhook.webhook_secret = uuid_instance webhook.save() WebhookSecret = apps.get_model("metering_billing", "WebhookSecret") for webhook_secret in WebhookSecret.objects.all(): uuid_string = webhook_secret.webhook_secret_old.replace("whsec_", "") uuid_instance = UUID(uuid_string) webhook_secret.webhook_secret = uuid_instance webhook_secret.save()
null
7,025
from django.db import migrations def delete_dups(apps, schema_editor): Customer = apps.get_model("metering_billing", "Customer") for row in Customer.objects.all().order_by("pk"): org = row.organization email = row.email pk = row.pk others = Customer.objects.filter(organization=org, email=email).exclude(pk=pk) others.delete()
null
7,026
from django.db import migrations def transfer_component_granularity_to_metric(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") apps.get_model("metering_billing", "Metric") for component in PlanComponent.objects.all(): ass_metric = component.billable_metric if not ass_metric.proration: ass_metric.proration = component.proration_granularity ass_metric.save()
null
7,027
from django.db import migrations def fill_pricing_units(apps, schema_editor): PlanVersion = apps.get_model("metering_billing", "PlanVersion") for plan_version in PlanVersion.objects.filter(currency__isnull=True): plan_version.currency = plan_version.organization.currency plan_version.save()
null
7,028
from django.db import migrations def transfer_to_brs(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") BillingRecord = apps.get_model("metering_billing", "BillingRecord") InvoiceLineItem = apps.get_model("metering_billing", "InvoiceLineItem") for sr in SubscriptionRecord.objects.all(): bp = sr.billing_plan components = bp.plan_components.all() recurring_charges = bp.recurring_charges.all() for component in components: br = BillingRecord.objects.create( organization=sr.organization, subscription=sr, component=component, start_date=sr.usage_start_date, end_date=sr.end_date, invoicing_dates=[sr.end_date], next_invoicing_date=sr.end_date, fully_billed=sr.fully_billed, unadjusted_duration_microseconds=sr.unadjusted_duration_microseconds, ) for invoice_line_items in InvoiceLineItem.objects.filter( associated_subscription_record=sr, associated_plan_component=component ): invoice_line_items.associated_billing_record = br invoice_line_items.save() for charge in recurring_charges: BillingRecord.objects.create( organization=sr.organization, subscription=sr, recurring_charge=charge, start_date=sr.usage_start_date, end_date=sr.end_date, invoicing_dates=[sr.end_date], next_invoicing_date=sr.end_date, fully_billed=sr.fully_billed, unadjusted_duration_microseconds=sr.unadjusted_duration_microseconds, ) for invoice_line_items in InvoiceLineItem.objects.filter( associated_subscription_record=sr, associated_recurring_charge=charge ): invoice_line_items.associated_billing_record = br invoice_line_items.save()
null
7,029
from django.db import migrations def transfer_filters_to_subscription_filters(apps, schema_editor): SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for subscription in SubscriptionRecord.objects.all(): new_filters = [] for sf in subscription.filters.all(): property_name = sf.property_name value = sf.comparison_value[0] new_filters.append([property_name, value]) subscription.subscription_filters = new_filters subscription.save()
null
7,030
from django.db import migrations from django.db.models import Q def migrate_metric_type(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter(metric_type="aggregation").update( metric_type="counter" )
null