|
| 1 | +"""Pull requests or issues per day, week or month: for the charts of the page Trends.""" |
| 2 | + |
| 3 | +from datetime import datetime, tzinfo |
| 4 | + |
| 5 | +from django.db.models import Min |
| 6 | + |
| 7 | +from ..models import Item |
| 8 | +from .kind_trend import contribution_events, first_contributions, in_range |
| 9 | +from .periods import buckets, count_by, label, size_of |
| 10 | + |
| 11 | +# the numbers per bar, by their keys in what kind_series returns |
| 12 | +SERIES = ("opened", "closed", "contributions", "newcomers") |
| 13 | + |
| 14 | + |
| 15 | +def kind_series( |
| 16 | + repositories, |
| 17 | + kind: str, |
| 18 | + since: datetime | None, |
| 19 | + until: datetime | None, |
| 20 | + now: datetime, |
| 21 | + tz: tzinfo, |
| 22 | +) -> dict: |
| 23 | + """Opened, closed, contributions and new contributors per day, week or month. |
| 24 | +
|
| 25 | + For pull requests or for issues, in each day, week or month of the time range. |
| 26 | +
|
| 27 | + Args: |
| 28 | + repositories: The repositories. |
| 29 | + kind: ``pr`` or ``issue``. |
| 30 | + since: The start of the time range, None for the first item or contribution. |
| 31 | + until: The end of the time range, excluded; None for now. |
| 32 | + now: The time now: the end of a range without one. |
| 33 | + tz: The time zone of the days. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + ``size`` (``day``, ``week`` or ``month``), ``labels`` of the bars, and for each bar |
| 37 | + ``opened``, ``closed``, ``contributions`` and ``newcomers``; no labels without data. |
| 38 | + """ |
| 39 | + items = Item.objects.filter(repository__in=repositories, kind=kind) |
| 40 | + events = contribution_events(repositories, kind) |
| 41 | + end = until or now |
| 42 | + start = since or min( |
| 43 | + ( |
| 44 | + found |
| 45 | + for found in ( |
| 46 | + items.aggregate(first=Min("created_at"))["first"], |
| 47 | + events.aggregate(first=Min("at"))["first"], |
| 48 | + ) |
| 49 | + if found is not None |
| 50 | + ), |
| 51 | + default=None, |
| 52 | + ) |
| 53 | + if start is None or start >= end: |
| 54 | + return {"size": "", "labels": []} | {name: [] for name in SERIES} |
| 55 | + size = size_of(start, end) |
| 56 | + |
| 57 | + def per_bar(query, field: str) -> list[int]: |
| 58 | + times = in_range(query, field, start, end).values_list(field, flat=True) |
| 59 | + return count_by(times.iterator(), start, end, size, tz) |
| 60 | + |
| 61 | + return { |
| 62 | + "size": size, |
| 63 | + "labels": [label(day, size) for day in buckets(start, end, size, tz)], |
| 64 | + "opened": per_bar(items, "created_at"), |
| 65 | + "closed": per_bar(items.filter(closed_at__isnull=False), "closed_at"), |
| 66 | + "contributions": per_bar(events, "at"), |
| 67 | + "newcomers": count_by( |
| 68 | + (at for _, at in first_contributions(repositories, kind)), start, end, size, tz |
| 69 | + ), |
| 70 | + } |
0 commit comments