Ejemplo n.º 1
0
def docs_list(doc_objects=[]):
    '''Creates a Mako table with 'Download' and 'View' buttons for
    each doc given. How to use:
    
    ${ docs_list([ {label: 'First Document', doc: final_form}, {label: 'Cover page', doc: cover_page} ]) }
    
    @param docs_objects {list} A list of objects, each containing a `label` and `doc`.
    @param docs_objects[n] {object} The object containing the data for a row in the table.
    @param docs_objects[n].label {string} The name that will be listed for the document.
    @param docs_objects[n].doc {DAFileCollection} The document with which the user will interact.
  '''
    if not doc_objects:
        log('`docs_list() did not get any documents. Please pass some in! Use: `${ docs_list([ {label: "Document", doc: final_form}, {label: "Cover page", doc: cover_page} ]) }'
            )
        return None

    # Header rows have to exist in order for the markdown to recognize it as a table. Hide it with css.
    header_hider = '<div class="ilao_header_hider" aria-hidden="true"></div>\n\n'
    rows = docs_list_top(3)
    docs_in_zip = []
    for doc_obj in doc_objects:
        rows += '\n' + docs_list_row(doc_obj["label"], doc_obj["doc"])
        docs_in_zip.append(doc_obj["doc"])
    docs_zip_url = zip_file(
        docs_in_zip, filename="Easy Form files.zip").url_for(attachment=True)
    rows += '\n' + '**Get all your forms in a {.zip file :question-circle:}** | | ' + action_button_html(
        docs_zip_url,
        new_window=False,
        color="primary",
        label=":file-archive: Download")
    return header_hider + rows
Ejemplo n.º 2
0
 def id(self):
     if self.result is None:
         return None
     if 'id' not in self._full_result['labels'][-1]:
         log('Spot API returned a result but it lacked an id')
         return None
     return self._full_result['labels'][-1]['id']
def store_signature_data(signer):
    """Try to update signature values in the data store.
  
  These include:
  * `signature`
  * `signature_date`
  * `has_signed`
  
  Paramaters
  ----------
  signer: Individual
    An obj of the Individual class that will be given the attributes if keys are valid.
    
  Returns
  ----------
  Returns True if the data got set. Otherwise returns False.
  """
    ## These first two are a bit weird and hidden. What's the clearest/most traceable choice?
    #signer.signature_date = today()
    #signer.has_signed = True
    # TODO: Set persistance and privacy of signature? Seems to funciton without, or is that in other code somewhere?
    log(signer, 'console')
    store_signer_attribute(signer.signature_data_id, signer.id, 'signature',
                           signer.signature)
    store_signer_attribute(signer.signature_data_id, signer.id,
                           'signature_date', today())
    return store_signer_attribute(signer.signature_data_id, signer.id,
                                  'has_signed', True)
def get_zips() -> gpd.GeoDataFrame:
    full_file_path = saved_dir().joinpath(get_boundary_file('us', 'zcta510'))
    if not full_file_path.exists():
        log("{} doesn't exist, downloading".format(full_file_path))
        download_shapes('us', 'zcta510')
    # TODO(brycew): consider a bounding box: it's 2x as fast with one, but
    # trying to read bounding boxes from a different shp file is slower
    return gpd.read_file('zip://' + str(full_file_path))
Ejemplo n.º 5
0
 def locked_get(self):
     json_creds = self.r.get(self.key)
     creds = None
     if json_creds is not None:
         json_creds = json_creds.decode()
         try:
             creds = oauth2client.client.Credentials.new_from_json(json_creds)
         except:
             log("RedisCredStorage: could not read credentials from " + str(json_creds))
     return creds
def set_feedback_github_url(id_for_feedback: str, github_url: str) -> bool:
    """Returns true if save was successful"""
    stmt = (update(feedback_session_table).where(
        feedback_session_table.c.id == id_for_feedback).values(
            html_url=github_url))
    with engine.begin() as conn:
        result = conn.execute(stmt)
    if result.rowcount == 0:
        log(f"Cannot find {id_for_feedback} in redis DB")
        return False
    return True
Ejemplo n.º 7
0
def send_to_table(answer_dict, table_name):
    intake_table = Airtable(at_base_lmm, table_name, api_key=at_api_key)
    send_dict = {}
    for key, value in answer_dict.iteritems():
        if 'Attachment' in key:
            log(value)
            send_dict[key] = value['elements']['fullpath']
        else:
            send_dict[key] = str(value)

    intake_table.insert(send_dict)
def download_file(url: str, local_file: str) -> str:
    """
    Download a file from an arbitrary URL to a local file
    """
    # https://stackoverflow.com/a/16696317
    log('Downloading {} to {}'.format(url, local_file))
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with local_file.open(mode='wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_file
Ejemplo n.º 9
0
def translate_phrase(phrase, source_language, target_language):
    try:
        api_key = get_config('google')['api key']
    except:
        log("Could not translate because Google API key was not in Configuration."
            )
        return phrase
    try:
        service = build('translate', 'v2', developerKey=api_key)
        resp = service.translations().list(source=source_language,
                                           target=target_language,
                                           q=[phrase]).execute()
        return re.sub(r'&#39;', r"'",
                      str(resp['translations'][0]['translatedText']))
    except Exception as err:
        log("translation failed: " + err.__class__.__name__ + ": " + str(err))
        return phrase
def make_github_issue(
    repo_owner, repo_name, template=None, title=None, body=None, label=None
) -> Optional[str]:
    """
    Create a new Github issue and return the URL.

    template - the docassemble template for the github issue. Overrides `title` and `body` if provided.
    title - the title for the github issue
    body - the body of the github issue
    """
    make_issue_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/issues"
    # Headers
    if not TOKEN:
        log("Error creating issues: No valid GitHub token provided.")
        return None

    headers = {
        "Authorization": "token %s" % TOKEN,
        "Accept": "application/vnd.github.v3+json",
    }

    if label:
        labels_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/labels"
        has_label_resp = requests.get(labels_url + "/" + label, headers=headers)
        if has_label_resp.status_code == 404:
            label_data = {
                "name": label,
                "description": "Feedback from a Docassemble Interview",
                "color": "002E60",
            }
            make_label_resp = requests.post(
                labels_url, data=json.dumps(label_data), headers=headers
            )
            if make_label_resp.status_code != 201:
                log(
                    f"Was not able to find nor create the {label} label: {make_label_resp.text}"
                )
                label = None

    if template:
        title = template.subject
        body = template.content
    # Create our issue
    data = {
        "title": title,
        "body": body,
    }
    if label:
        data["labels"] = [label]

    # Add the issue to our repository
    response = requests.post(make_issue_url, data=json.dumps(data), headers=headers)
    if response.status_code == 201:
        return response.json().get("html_url")
    else:
        log(f'Could not create Issue "{title}", results {response.text}')
        return None
Ejemplo n.º 11
0
def get_fields_from_intake(table_name):
    intake_table = Airtable(at_base_lmm, table_name, api_key=at_api_key)
    show_this = {}
    key_list = []
    intake_obj = DAObject('intake_obj')
    for rec in intake_table.get_all(max_records=1):
        log("HEEEEYYYYYYYYY")
        log(rec)
        for field in rec['fields']:
            key_list.append(str(field))
    log(key_list)
    for mf in key_list:
        # set field type based on name of field
        if 'Email' in mf:
            dt = 'email'
        elif 'Date' in mf:
            dt = 'date'
        elif 'Attachment' in mf:
            dt = 'file'
        else:
            dt = ''
        show_this[str(mf)] = {'question': str(mf), 'label': str(mf), 'dt': dt}
    return show_this