Ejemplo n.º 1
0
def bill_details_user_view(request, congress, type_slug, number):
    bill = load_bill_from_url(congress, type_slug, number)

    ret = { }
    if request.user.is_staff:
        admin_panel = """
            {% load humanize %}
            <div class="clear"> </div>
            <div style="margin-top: 1.5em; padding: .5em; background-color: #EEE; ">
                <b>ADMIN</b> - <a href="{% url "bill_go_to_summary_admin" %}?bill={{bill.id}}">Edit Summary</a>
                <br/>Tracked by {{feed.tracked_in_lists.count|intcomma}} users
                ({{feed.tracked_in_lists_with_email.count|intcomma}} w/ email).
            </div>
            """
        from django.template import Template, Context, RequestContext, loader
        ret["admin_panel"] = Template(admin_panel).render(RequestContext(request, {
            'bill': bill,
            "feed": Feed.BillFeed(bill),
            }))

    from person.views import render_subscribe_inline
    ret.update(render_subscribe_inline(request, Feed.BillFeed(bill)))

    # poll_and_call
    if request.user.is_authenticated():
        from poll_and_call.models import RelatedBill as IssueByBill, UserPosition
        try:
            issue = IssueByBill.objects.get(bill=bill).issue
            try:
                up = UserPosition.objects.get(user=request.user, position__issue=issue)
                targets = up.get_current_targets()
                ret["poll_and_call_position"] =  {
                    "id": up.position.id,
                    "text": up.position.text,
                    "can_change": up.can_change_position(),
                    "can_call": [(t.id, t.person.name) for t in targets] if isinstance(targets, list) else [],
                    "call_url": issue.get_absolute_url() + "/make_call",
                }
            except UserPosition.DoesNotExist:
                pass
        except IssueByBill.DoesNotExist:
            pass
        
    return ret
Ejemplo n.º 2
0
 def create_events(self):
     from events.models import Feed, Event
     feeds = [
         Feed.AllCommitteesFeed(),
         Feed.CommitteeMeetingsFeed(self.code)
     ]
     if self.committee:
         feeds.append(Feed.CommitteeMeetingsFeed(
             self.committee.code))  # add parent committee
     with Event.update(self) as E:
         for meeting in self.meetings.all():
             E.add("mtg_" + str(meeting.id), meeting.when,
                   feeds + [Feed.BillFeed(b) for b in meeting.bills.all()])
Ejemplo n.º 3
0
def bill_details_user_view(request, congress, type_slug, number):
    bill = load_bill_from_url(congress, type_slug, number)

    ret = { }
    if request.user.is_staff:
        admin_panel = """
            {% load humanize %}
            <div class="clear"> </div>
            <div style="margin-top: 1.5em; padding: .5em; background-color: #EEE; ">
                <b>ADMIN</b> - <a href="{% url "bill_go_to_summary_admin" %}?bill={{bill.id}}">Edit Summary</a>
                <br/>Tracked by {{feed.tracked_in_lists.count|intcomma}} users
                ({{feed.tracked_in_lists_with_email.count|intcomma}} w/ email).
            </div>
            """
        from django.template import Template, Context, RequestContext, loader
        ret["admin_panel"] = Template(admin_panel).render(RequestContext(request, {
            'bill': bill,
            "feed": Feed.BillFeed(bill),
            }))

    from person.views import render_subscribe_inline
    ret.update(render_subscribe_inline(request, Feed.BillFeed(bill)))

    return ret
Ejemplo n.º 4
0
def bill_details(request, congress, type_slug, number):
    bill = load_bill_from_url(congress, type_slug, number)

    from person.name import get_person_name
    sponsor_name = None if not bill.sponsor else \
        get_person_name(bill.sponsor, role_date=bill.introduced_date, firstname_position='before', show_suffix=True)

    def get_reintroductions():
        reintro_prev = None
        reintro_next = None
        for reintro in bill.find_reintroductions():
            if reintro.congress < bill.congress: reintro_prev = reintro
            if reintro.congress > bill.congress and not reintro_next: reintro_next = reintro
        return reintro_prev, reintro_next

    def get_text_info():
        from models import USCSection
        from billtext import load_bill_text
        from search import parse_slip_law_number
        import re
        try:
            metadata = load_bill_text(bill, None, mods_only=True)

            # do interesting stuff with citations
            if "citations" in metadata and not settings.DEBUG:
                slip_laws = []
                statutes = []
                usc = { }
                other = []
                usc_other = USCSection(name="Other Citations", ordering=99999)
                for cite in metadata["citations"]:
                    if cite["type"] == "slip_law":
                        slip_laws.append(cite)
                        cite["bill"] = parse_slip_law_number(cite["text"])
                    elif cite["type"] == "statutes_at_large":
                        statutes.append(cite)
                    elif cite["type"] in ("usc-section", "usc-chapter"):
                        # Build a tree of title-chapter-...-section nodes so we can
                        # display the citations in context.
                        try:
                            sec_obj = USCSection.objects.get(citation=cite["key"])
                        except: # USCSection.DoesNotExist and MultipleObjectsReturned both possible
                            # create a fake entry for the sake of output
                            # the 'id' field is set to make these objects properly hashable
                            sec_obj = USCSection(id=cite["text"], name=cite["text"], parent_section=usc_other)

                        if "range_to_section" in cite:
                            sec_obj.range_to_section = cite["range_to_section"]

                        # recursively go up to the title
                        path = [sec_obj]
                        so = sec_obj
                        while so.parent_section:
                            so = so.parent_section
                            path.append(so)

                        # build a link to LII
                        if cite["type"] == "usc-section":
                            cite_link = "http://www.law.cornell.edu/uscode/text/" + cite["title"]
                            if cite["section"]:
                                cite_link += "/" + cite["section"]
                            if cite["paragraph"]: cite_link += "#" + "_".join(re.findall(r"\(([^)]+)\)", cite["paragraph"]))
                        elif cite["type"] == "usc-chapter":
                            cite_link = "http://www.law.cornell.edu/uscode/text/" + cite["title"] + "/" + "/".join(
                                (so.level_type + "-" + so.number) for so in reversed(path[:-1])
                                )
                        sec_obj.link = cite_link

                        # now pop off from the path to put the node at the right point in a tree
                        container = usc
                        while path:
                            p = path.pop(-1)
                            if p not in container: container[p] = { }
                            container = container[p]

                    else:
                        other.append(cite)

                slip_laws.sort(key = lambda x : (x["congress"], x["number"]))

                # restructure data format
                def ucfirst(s): return s[0].upper() + s[1:]
                def rebuild_usc_sec(seclist, indent=0):
                    ret = []
                    seclist = sorted(seclist.items(), key=lambda x : x[0].ordering)
                    for sec, subparts in seclist:
                        ret.append({
                            "text": (ucfirst(sec.level_type + ((" " + sec.number) if sec.number else "") + (": " if sec.name else "")) if sec.level_type else "") + (sec.name_recased if sec.name else ""),
                            "link": getattr(sec, "link", None),
                            "range_to_section": getattr(sec, "range_to_section", None),
                            "indent": indent,
                        })
                        ret.extend(rebuild_usc_sec(subparts, indent=indent+1))
                    return ret
                usc = rebuild_usc_sec(usc)

                metadata["citations"] = {
                    "slip_laws": slip_laws, "statutes": statutes, "usc": usc, "other": other,
                    "count": len(slip_laws)+len(statutes)+len(usc)+len(other) }
            return metadata
        except IOError:
            return None

    return {
        'bill': bill,
        "congressdates": get_congress_dates(bill.congress),
        "subtitle": get_secondary_bill_title(bill, bill.titles),
        "sponsor_name": sponsor_name,
        "reintros": get_reintroductions, # defer so we can use template caching
        "current": bill.congress == CURRENT_CONGRESS,
        "dead": bill.congress != CURRENT_CONGRESS and bill.current_status not in BillStatus.final_status_obvious,
        "feed": Feed.BillFeed(bill),
        "text": get_text_info,

        "care2_category_id": {
            5816: '793', # Agriculture and Food=>Health
            5840: '789', # Animals=>Animal Welfare
            5996: '794', # Civil Rights=>Human Rights
            5991: '791', # Education=>Education
            6021: '792', # Energy=>Environment & Wildlife
            6038: '792', # Environmental Protection=>Environment & Wildlife
            6053: '793', # Families=>Health
            6130: '793', # Health=>Health
            6206: '794', # Immigration=>Human Rights
            6279: '792', # Public Lands/Natural Resources=>Environment & Wildlife
            6321: '791', # Social Sciences=>Education
            6328: '793', # Social Welfare => Health
        }.get(bill.get_top_term_id(), '795') # fall back to Politics category
    }
Ejemplo n.º 5
0
def do_site_search(q, allow_redirect=False):
    if q.strip() == "":
        return []

    results = []

    from events.models import Feed
    if "pass" in q or "fail" in q or "vote" in q:
        results.append({
            "title":
            "Tracking Federal Legislation",
            "href":
            "/start",
            "noun":
            "feeds",
            "results": [{
                "href": f.link,
                "label": f.title,
                "obj": f,
                "feed": f,
                "secondary": False
            } for f in (
                Feed.EnactedBillsFeed(),
                Feed.ActiveBillsExceptIntroductionsFeed(),
                Feed.ComingUpFeed(),
                Feed.AllVotesFeed(),
            )]
        })

    from haystack.query import SearchQuerySet
    from events.models import Feed

    results.append({
        "title":
        "Members of Congress, Presidents, and Vice Presidents",
        "href":
        "/congress/members/all",
        "qsarg":
        "name",
        "noun":
        "Members of Congress, Presidents, or Vice Presidents",
        "results": [{
            "href": p.object.get_absolute_url(),
            "label": p.object.name,
            "obj": p.object,
            "feed": Feed.PersonFeed(p.object),
            "secondary": p.object.get_current_role() == None
        } for p in SearchQuerySet().using("person").filter(
            indexed_model_name__in=["Person"], content=q).order_by(
                '-is_currently_serving', '-score')[0:9]]
    })

    # Skipping states for now because we might want to go to the district maps or to
    # the state's main page for state legislative information.
    #import us
    #results.append(("States", "/congress/members", "most_recent_role_state", "states",
    #    sorted([{"href": "/congress/members/%s" % s, "label": us.statenames[s] }
    #        for s in us.statenames
    #        if us.statenames[s].lower().startswith(q.lower())
    #        ], key=lambda p : p["label"])))

    from committee.models import Committee
    results.append({
        "title":
        "Congressional Committees",
        "href":
        "/congress/committees",
        "noun":
        "committees in Congress",
        "results":
        sorted([{
            "href": c.get_absolute_url(),
            "label": c.fullname,
            "feed": Feed.CommitteeFeed(c),
            "obj": c,
            "secondary": c.committee != None
        } for c in Committee.objects.filter(name__icontains=q, obsolete=False)
                ],
               key=lambda c: c["label"])
    })

    from settings import CURRENT_CONGRESS
    from bill.search import parse_bill_citation
    bill = parse_bill_citation(q)
    if not bill or not allow_redirect:
        from haystack.inputs import AutoQuery
        bills = [\
            {"href": b.object.get_absolute_url(),
             "label": b.object.title,
             "obj": b.object,
             "feed": Feed.BillFeed(b.object) if b.object.is_alive else None,
             "secondary": b.object.congress != CURRENT_CONGRESS }
            for b in SearchQuerySet().using("bill").filter(indexed_model_name__in=["Bill"], content=AutoQuery(q)).order_by('-current_status_date')[0:9]]
    else:
        #bills = [{"href": bill.get_absolute_url(), "label": bill.title, "obj": bill, "secondary": bill.congress != CURRENT_CONGRESS }]
        return HttpResponseRedirect(bill.get_absolute_url())
    results.append({
        "title": "Bills and Resolutions (Federal)",
        "href": "/congress/bills/browse",
        "qsarg": "congress=__ALL__&text",
        "noun": "federal bills or resolutions",
        "results": bills
    })

    results.append({
        "title":
        "State Legislation",
        "href":
        "/states/bills/browse",
        "qsarg":
        "text",
        "noun":
        "state legislation",
        "results": [{
            "href": p.object.get_absolute_url(),
            "label": p.object.short_display_title,
            "obj": p.object,
            "feed": Feed(feedname="states_bill:%d" % p.object.id),
            "secondary": True
        } for p in SearchQuerySet().using('states').filter(
            indexed_model_name__in=["StateBill"], content=q)[0:9]]
    })

    # subject terms, but exclude subject terms that look like committee names because
    # that is confusing to also see with committee results
    from bill.models import BillTerm, TermType
    results.append({
        "title":
        "Subject Areas (Federal Legislation)",
        "href":
        "/congress/bills",
        "noun":
        "subject areas",
        "results": [{
            "href": p.get_absolute_url(),
            "label": p.name,
            "obj": p,
            "feed": Feed.IssueFeed(p),
            "secondary": not p.is_top_term()
        } for p in BillTerm.objects.filter(
            name__icontains=q, term_type=TermType.new).exclude(
                name__contains=" Committee on ")[0:9]]
    })

    # in each group, make sure the secondary results are placed last, but otherwise preserve order
    for grp in results:
        for i, obj in enumerate(grp["results"]):
            obj["index"] = i
        grp["results"].sort(
            key=lambda o: (o.get("secondary", False), o["index"]))

    # sort categories first by whether all results are secondary results, then by number of matches (fewest first, if greater than zero)
    results.sort(key=lambda c: (len([
        d for d in c["results"] if d.get("secondary", False) == False
    ]) == 0, len(c["results"]) == 0, len(c["results"])))

    return results