Beispiel #1
0
 def db_set(self, column, value):
     if column == 'ssn':
         self.ssn = value
     elif column == 'first_name':
         self.name.first = value
     elif column == 'last_name':
         self.name.last = value
     elif column == 'address':
         self.address.address = value
     elif column == 'unit':
         self.address.unit = value
     elif column == 'city':
         self.address.city = value
     elif column == 'state':
         self.address.state = value
     elif column == 'zip':
         self.address.zip = value
     elif column == 'shares':
         self.shares = value
     elif column == 'start_date':
         # Docassemble uses a special subclass of the datetime.datetime object, so
         # the as_datetime() function is used to convert the value obtained from SQL.
         self.start_date = as_datetime(value)
     elif column == 'end_date':
         self.end_date = as_datetime(value)
         self.active = False
 def __init__(self, aDate):
   # Try to change string into DADateTime
   try:
     as_datetime( aDate )
     self.valid = True
   # If error, date is not a valid DADateTime (out of range, usually)
   except:
     self.valid = False
Beispiel #3
0
 def validate(cls, aDate):
     # Try to change string into DADateTime
     try:
         as_datetime(aDate)
         return True
     # If error, date is not a valid DADateTime
     except:
         return False
Beispiel #4
0
def make_event(title=None,
               location=None,
               description=None,
               begin_date=None,
               begin_time=None,
               end_date=None,
               end_time=None,
               organizer=None,
               attendees=[]):
    if title is None:
        raise Exception("make_event: a title parameter is required")
    if begin_date is None:
        raise Exception("make_event: a begin_date parameter is required")
    if begin_time is None:
        raise Exception("make_event: a begin_time parameter is required")
    if end_date is None:
        raise Exception("make_event: an end_date parameter is required")
    if end_time is None:
        raise Exception("make_event: an end_time parameter is required")
    c = Calendar()
    e = Event()
    if organizer is not None:
        e.organizer = Organizer(common_name=organizer.name.full(),
                                email=organizer.email)
    if len(attendees) > 0:
        e.attendees = [
            Attendee(common_name=attendee.name.full(), email=attendee.email)
            for attendee in attendees
        ]
    e.name = str(title)
    e.begin = as_datetime(
        begin_date.replace_time(begin_time),
        timezone='UTC').format_datetime('yyyy-MM-dd hh:mm:ss')
    e.end = as_datetime(end_date.replace_time(end_time),
                        timezone='UTC').format_datetime('yyyy-MM-dd hh:mm:ss')
    if location not in (None, ''):
        e.location = str(location)
    if description not in (None, ''):
        e.description = str(description)
    c.events.add(e)
    c.events
    ics_file = DAFile('ics_file')
    ics_file.set_random_instance_name()
    ics_file.initialize(filename="event.ics", mimetype="text/calendar")
    with open(ics_file.path(), 'w') as f:
        f.write(str(c))
    ics_file.commit()
    return ics_file
Beispiel #5
0
 def populate_individual(self, obj, data):
     if 'givenName' in data:
         obj.name.first = data['givenName']
     elif 'name' in data:
         obj.name.uses_parts = False
         obj.name.text = data['name']
     if 'familyName' in data:
         obj.name.last = data['familyName']
     if 'additionalName' in data:
         obj.name.middle = data['additionalName']
     if 'birthDate' in data:
         obj.birthdate = as_datetime(data['birthDate'])
     if 'isVeteran' in data:
         obj.is_veteran = True if data['isVeteran'] else False
     if 'veteranStatus' in data:
         obj.veteran_status = data['veteranStatus']
     if 'language' in data:
         obj.language = data['language']
     if 'address' in data:
         if 'addressLocality' in data['address']:
             obj.address.city = data['address']['addressLocality']
         if 'addressRegion' in data['address']:
             obj.address.state = data['address']['addressRegion']
         if 'postalCode' in data['address']:
             obj.address.zip = data['address']['postalCode']
         if 'streetAddress' in data['address']:
             obj.address.address = data['address']['streetAddress']
         if 'addressUnit' in data['address']:
             obj.address.unit = data['address']['addressUnit']
Beispiel #6
0
 def db_set(self, column, value):
     if column == 'name':
         self.name.text = value
     elif column == 'upload_id':
         self.ensure_upload_exists()
         self.upload[0].number = value
         # The "ok" attribute should be set to True when a DAFile object
         # has a "number."
         self.upload[0].ok = True
     elif column == 'date':
         self.date = as_datetime(value)
     elif column == 'filename':
         self.ensure_upload_exists()
         self.upload[0].filename = value
         # The "has_specific_filename" attribute should be set to True
         # when a DAFile object has a "filename."
         self.upload[0].has_specific_filename = True
     elif column == 'extension':
         self.ensure_upload_exists()
         self.upload[0].extension = value
     elif column == 'mimetype':
         self.ensure_upload_exists()
         self.upload[0].mimetype = value
     else:
         raise Exception("Invalid column " + column)
 def validate(cls, item):
     # If there's no input in the item, it's valid
     if not isinstance(item, str) or item == "":
         return True
     else:
         # Otherwise it needs to be a date on or before today and after the year 1000.
         # We ourselves create this format if the user gives valid info.
         matches_date_pattern = re.search(r"^\d{1,2}\/\d{1,2}\/\d{4}$", item)
         try:
             date = as_datetime(item)
         except Exception as error:
             msg = f"{ item } {word('is not a valid date')}"
             raise DAValidationError(msg)
         if matches_date_pattern:
             date_diff = date_difference(starting=date, ending=today())
             if date_diff.days >= 0.0:
                 return True
             else:
                 raise DAValidationError(
                     word("Answer with a <strong>date of birth</strong>")
                 )
         else:
             msg = (
                 f"{ item } {word('is not a valid <strong>date of birth</strong>')}"
             )
             raise DAValidationError(msg)
def get_next_business_day(
    start_date,
    wait_n_days=1,
    country="US",
    subdiv="MA",
    add_holidays=None,
    remove_holidays=None,
) -> dt:
    # Get non_business_days for current year and next year to avoid calling non_business_days for each individual date
    current_yr = as_datetime(start_date).year
    current_yr_non_business_days = non_business_days(
        year=current_yr,
        country=country,
        subdiv=subdiv,
        add_holidays=add_holidays,
        remove_holidays=remove_holidays,
    )
    next_yr_non_business_days = non_business_days(
        year=current_yr + 1,
        country=country,
        subdiv=subdiv,
        add_holidays=add_holidays,
        remove_holidays=remove_holidays,
    )

    # Initialize
    additional_days = wait_n_days
    done = False

    # Check if start_date+additional_days is a non-business day
    while not done:
        new_date = (
            as_datetime(start_date) + datetime.timedelta(days=additional_days)
        ).strftime("%m/%d/%Y")
        # If new_date is in the year of start_date, use current_yr_non_business_days to check
        if new_date[-4:] == current_yr:
            if new_date not in current_yr_non_business_days:
                done = True
        else:  # Otherwise use next_yr_non_business_days to check
            if new_date not in next_yr_non_business_days:
                done = True
        additional_days += 1  # Increase one more day

    return new_date
Beispiel #9
0
 def db_set(self, column, value):
     if column == 'court':
         self.court = value
     elif column == 'docket_number':
         self.docket_number = value
     elif column == 'plaintiff_first_name':
         self.plaintiff.name.first = value
     elif column == 'plaintiff_last_name':
         self.plaintiff.name.last = value
     elif column == 'filing_date':
         self.filing_date = as_datetime(value)
  def load_client(self, client):
    """Loads up the Individual object (e.g., client) with fields from Legal Server. Fills in birthdate, name, email, and address attributes"""
    try:
      client.name.first = self.client_name_parts['first']
      client.name.last = self.client_name_parts['last']
      client.name.suffix = self.client_name_parts['suffix']
      client.name.middle = self.client_name_parts['middle']

      address_parts = usaddress.tag(self.elements.get('full_address'))
      try:
        if address_parts[1].lower() == 'street address':
          client.address.address = address_parts[0].get('AddressNumber', '') + ' ' + address_parts[0].get(
            'StreetName', '') + ' ' + address_parts[0].get('StreetNamePostType', '')
          client.address.unit = address_parts[0].get(
            'OccupancyType', '') + ' ' + address_parts[0].get('OccupancyIdentifier')
          client.address.city = address_parts[0].get('PlaceName')
          client.address.zip = address_parts[0].get('ZipCode')
          client.address.state = address_parts[0].get('StateName')
        else:
          raise Exception(
            'We expected a Street Address. Fall back to Google Geolocation')
      except:
        client.address.address = self.elements.get('full_address', '')
        client.address.geocode(self.elements.get('full_address', ''))
      

    except:
      pass

    if self.elements.get('full_mailing_address', False):
      client.mailing_address_text = self.elements.get('full_mailing_address', '')
    if self.elements.get('full_address', False):
      client.address_text = self.elements.get('full_address', '')
    if self.elements.get('date_of_birth', False):
      client.birthdate = as_datetime(self.elements.get('date_of_birth'))
    client.email = self.elements.get('sidebar_email', '')
    client.mobile_number = self.elements.get('sidebar_mobile_phone', '')
    client.phone_number = self.elements.get('sidebar_home_phone', '')
    if self.elements.get('social_security', False):
      client.ssn = self.elements.get('social_security', '')
    if self.elements.get('social_security', False) and client.ssn != '':
      client.ssn_last_4 = client.ssn[-4:]
    if self.elements.get('language', False):
      if self.elements.get('language', '') == 'English':
        client.language = 'en'
      if self.elements.get('language', '') == 'Spanish':
        client.language = 'es'
      if self.elements.get('language', '') == 'Vietnamese':
        client.language = 'vi'
      if self.elements.get('language', '') == 'Chinese':
        client.language = 'zo'
    client.gender = self.elements.get('gender', '').lower()
    if self.elements.get('prefix_salutation'):
      client.preferred_salutation = self.elements.get('prefix_salutation')
Beispiel #11
0
 def db_set(self, column, value):
     if column == 'court':
         self.court = value
     elif column == 'docket_number':
         self.docket_number = value
     elif column == 'plaintiff_first_name':
         self.plaintiff.name.first = value
     elif column == 'plaintiff_last_name':
         self.plaintiff.name.last = value
     elif column == 'filing_date':
         self.filing_date = as_datetime(value)
     else:
         raise Exception("Invalid column " + column)
Beispiel #12
0
 def populate_individual(self, obj, data):
     if 'givenName' in data:
         obj.name.first = data['givenName']
     elif 'name' in data:
         obj.name.uses_parts = False
         obj.name.text = data['name']
     if 'familyName' in data:
         obj.name.last = data['familyName']
     if 'additionalName' in data:
         obj.name.middle = data['additionalName']
     if 'birthDate' in data:
         obj.birthdate = as_datetime(data['birthDate'])
     if 'isVeteran' in data:
         obj.is_veteran = True if data['isVeteran'] else False
def is_business_day(
    date, country="US", subdiv="MA", add_holidays=None, remove_holidays=None
) -> bool:
    if (
        date
        in non_business_days(
            as_datetime(date).year,
            country=country,
            subdiv=subdiv,
            add_holidays=add_holidays,
            remove_holidays=remove_holidays,
        ).keys()
    ):
        return False
    else:
        return True
    def validate(cls, item):
        # If there's no input in the item, it's valid
        if not isinstance(item, str) or item == "":
            return True
        else:
            # Otherwise it needs to be a date after the year 1000. We ourselves make
            # sure this format is created if the user gives valid info.
            matches_date_pattern = re.search(r"^\d{1,2}\/\d{1,2}\/\d{4}$", item)
            if matches_date_pattern:
                try:
                    date = as_datetime(item)
                except Exception as error:
                    msg = f"{ item } {word('is not a valid date')}"
                    raise DAValidationError(msg)

                return True
            else:
                raise DAValidationError(f"{ item } {word('is not a valid date')}")
  def load_household(self, household):
    """Try to set the provided object to the corresponding Legal Server listview"""
    household_list = self.elements.get('Family Members', [])
    for person in household_list:
      hh = household.appendObject()
      name_parts = HumanName(person.get('Name'))
      hh.name.first = name_parts.first
      hh.name.last = name_parts.last
      hh.name.middle = name_parts.middle
      hh.name.suffix = name_parts.suffix

      hh.name.text = person.get('Adverse Party Name')
      hh.birthdate = as_datetime(person.get('Date of Birth')) if not person.get(
        'Date of Birth') == 'N/A' else None
      hh.gender = person.get('Gender').lower() if not person.get(
        'Gender') == 'N/A' else None
      hh.race = person.get('Race') if not person.get(
        'Race') == 'N/A' else None
      hh.relationship = person.get('Relationship')
 def load_adverse_parties(self, adverse_parties):
   """Try to set the provided object to the corresponding Legal Server listview"""
   adverse_list = self.elements.get('Adverse Parties')
   if not adverse_list:
     return self.fallback_load_adverse_parties(adverse_parties)
   for person in adverse_list:
     ap = adverse_parties.appendObject()  # Person()
     ap.name.text = person.get('Adverse Party Name')
     try:
       ap.birthdate = as_datetime(person.get('Date of Birth', '')) if person.get('Date of Birth') and not person.get(
         'Date of Birth') == 'N/A' else None      
       ap.gender = person.get('Gender').lower() if not person.get(
         'Gender') == 'N/A' else None
       ap.race = person.get('Race') if not person.get(
         'Race') == 'N/A' else None
       self.parse_address(person.get(
         'Adverse Party Address'), ap.address)
     except:
       pass
 def transform(cls, item):
     if item:
         return as_datetime(item)
def non_business_days(
    year,
    country="US",
    subdiv="MA",
    add_holidays=None,
    remove_holidays=None,
    first_n_dates=0,
    last_n_dates=0,
) -> dict:
    # 1. Collect weekends and standard holidays
    # 1.1 Get all saturdays and sundays in the given year
    # Must use .strftime('%m/%d/%Y')to make it a string, otherwise will get 'TypeError'
    sundays = (
        pd.date_range(start=str(year), end=str(year + 1), freq="W-SUN")
        .strftime("%m/%d/%Y")
        .tolist()
    )
    saturdays = (
        pd.date_range(start=str(year), end=str(year + 1), freq="W-SAT")
        .strftime("%m/%d/%Y")
        .tolist()
    )

    # 1.2 Get holidays of the given country and subdivision (state/province) in the year
    local_holidays = standard_holidays(
        year=year,
        country=country,
        subdiv=subdiv,
        add_holidays=add_holidays,
        remove_holidays=remove_holidays,
    )

    # 2. Populate date_dict using as_datetime format as key for later sorting
    # 2.1 Populate date_dict with holidays
    date_dict = {}
    for raw_date, name in local_holidays.items():
        date_dict[as_datetime(raw_date)] = name

    # 2.2 Add weekends if not already in date_dict
    for a in saturdays:
        if as_datetime(a) not in date_dict.keys():
            date_dict[as_datetime(a)] = "Saturday"
    for b in sundays:
        if as_datetime(b) not in date_dict.keys():
            date_dict[as_datetime(b)] = "Sunday"

    # 3. Sort date_dict then change key from as_datetime to mm/dd/yyyy for easier application
    date_dict = dict(sorted(date_dict.items()))

    clean_date_dict = {}
    for k, v in date_dict.items():
        clean_date_dict[k.strftime("%m/%d/%Y")] = v

    # 4. Take a subset if user desires it (useful only if this function is explicitly called)
    final_output = {}
    if first_n_dates > 0 and last_n_dates > 0:
        first_slice = {
            s: clean_date_dict[s] for s in list(clean_date_dict)[:first_n_dates]
        }
        last_slice = {
            s: clean_date_dict[s]
            for s in list(clean_date_dict)[len(clean_date_dict.keys()) - last_n_dates :]
        }
        final_output = {**first_slice, **last_slice}  # Add two dicts
    elif first_n_dates > 0:
        final_output = {
            s: clean_date_dict[s] for s in list(clean_date_dict)[:first_n_dates]
        }
    elif last_n_dates > 0:
        final_output = {
            s: clean_date_dict[s]
            for s in list(clean_date_dict)[len(clean_date_dict.keys()) - last_n_dates :]
        }
    else:
        final_output = clean_date_dict

    # 5. Return the result
    return final_output