Example #1
0
def love_link(link_id):
    try:
        loveLink = logic.love_link.get_love_link(link_id)
        recipients_str = loveLink.recipient_list
        message = loveLink.message

        recipients = sanitize_recipients(recipients_str)
        loved = [
            Employee.get_key_for_username(recipient).get()
            for recipient in recipients
        ]

        return render_template(
            'love_link.html',
            current_time=datetime.utcnow(),
            current_user=Employee.get_current_employee(),
            recipients=recipients_str,
            message=message,
            loved=loved,
            link_id=link_id,
        )
    except (NoSuchLoveLink, NoSuchEmployee):
        flash('Sorry, that link ({}) is no longer valid.'.format(link_id),
              'error')
        return redirect(url_for('home'))
Example #2
0
def _update_employees(employee_dicts):
    """Given a JSON string in the format "[{employee info 1}, {employee info 2}, ...]",
    create new employee records and update existing records as necessary.

    Then determine whether any employees have been terminated since the last update,
    and mark these employees as such.
    """
    logging.info('Updating employees...')

    employees = []
    for d in employee_dicts:
        existing_employee = Employee.query(Employee.username == d['username']).get()
        if existing_employee is None:
            new_employee = Employee.create_from_dict(d, persist=False)
            employees.append(new_employee)
        else:
            existing_employee.update_from_dict(d)
            # If the user is in the S3 dump, then the user is no longer
            # terminated.
            existing_employee.terminated = False
            employees.append(existing_employee)

        # write to db every 500 employees so we save memory
        if len(employees) == 500:
            ndb.put_multi(employees)
            del employees
            employees = []

    if employees:
        ndb.put_multi(employees)

    logging.info('Done.')
Example #3
0
	def test_callingGetEmployeesReturnsListOfDicts(self):
		Employee.objects.filter = mock.MagicMock()
		company = Company()
		company.pk = 98
		employee_one = Employee()
		employee_one.pk = 12
		employee_one.user = User()
		employee_one.user.first_name = 'Fornavn'
		employee_one.user.last_name = 'Efternavn'
		employee_one.company = company
		employee_two = Employee()
		employee_two.pk = 13
		employee_two.user = User()
		employee_two.user.first_name = 'Fornavn'
		employee_two.user.last_name = 'Efternavn'
		employee_two.company = company
		Employee.objects.filter.return_value = [employee_one, employee_two]
		employee_one.getMyEmployees = mock.MagicMock()
		employee_one.getMyEmployees.return_value = []
		employee_list = employee_one.getEmployees()
		self.assertEquals(2, len(employee_list))
		self.assertTrue(isinstance(employee_list[0], dict))
		self.assertTrue(isinstance(employee_list[0]['manager'], Employee))
		self.assertEquals(employee_list[0]['manager'].pk, 12)
		self.assertTrue(isinstance(employee_list[0]['employees'], list))
		self.assertEquals(employee_list[0]['manager'].user.first_name, 'Fornavn')
		self.assertEquals(employee_list[0]['manager'].user.last_name, 'Efternavn')
Example #4
0
def get_employees_by_location(location_id):

    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute(
            """
        select
            e.id,
            e.name,
            e.location_id
        from Employee e
        WHERE e.location_id = ?
        """, (location_id, ))

        employees = []
        dataset = db_cursor.fetchall()

        for row in dataset:
            employee = Employee(row['id'], row['name'], row['location_id'])

            location = Location(row['location_name'], row['location_address'])

            employee.location = location.__dict__
            employees.append(employee.__dict__)

    return json.dumps(employees)
Example #5
0
def index(request):
  e = Employee(name="John",
               role="manager",
               email='*****@*****.**')
  e.hire_date = datetime.datetime.now().date()
  #e.put()
  day1 = datetime.timedelta(days=1)
  trendslist=[]
  gtrendslist=[]
  yesterday = datetime.date.today()-day1
  query = Trend.all().filter('created >= ', yesterday).order('-created')
  results = query.fetch(100)
  for p in results:
    trendslist.append(p.title)
 
  
        
  gv = globvars
  context = {
    'thispage':'Home',
    'trends':trendslist,
    'gtrends':gtrendslist,
      }
  context = dict(context, **gv.context) #combines the 'local' context with the 'global' context
  return render_to_response('index.html', context)
Example #6
0
def profile_handler(doc, name, url, path):
    filename = os.path.join(path, name + ".html")
    employee = Employee(name=name, url=url)

    # 只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div", attrs={"id":"phy-main"}, limit=1)
    if not divs or len(divs) == 0:
        return employee

    div = divs[0]
    if not os.path.exists(filename):
        with open(filename, 'wb') as fp:
            content = div.prettify()
            fp.write(content)
            fp.close()
    
    #email
    email_div = soup.find_all(name='a',class_="phy-mail")
    if email_div and len(email_div) != 0:
        employee.email = email_div[0].get_text().strip()

    te_div = soup.find_all(name='a',class_="phy-phone")
    if te_div and len(te_div) != 0:
        employee.tel = te_div[0].get_text().strip()
    
    # 使用纯文本方式处理
    lines = div.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines,employee=employee,set_attr_hook=set_attr_hook)
    return parser.parse()
Example #7
0
def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    from models import Department, Employee, Role
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    # Create the fixtures
    engineering = Department(name='Engineering')
    db_session.add(engineering)
    hr = Department(name='Human Resources')
    db_session.add(hr)

    manager = Role(name='manager')
    db_session.add(manager)
    engineer = Role(name='engineer')
    db_session.add(engineer)

    peter = Employee(name='Peter', department=engineering, role=engineer)
    db_session.add(peter)
    roy = Employee(name='Roy', department=engineering, role=engineer)
    db_session.add(roy)
    tracy = Employee(name='Tracy', department=hr, role=manager)

    # postgresql specific dialects tests
    # tracy.articles = [1, 2, 3, 4]
    # tracy.json_data = {"test_json": "test_json"}
    # tracy.jsonb_data = {"test_jsonb": "test_jsonb"}
    # tracy.hstore_data = {"test_hstore": "test_hstore"}

    db_session.add(tracy)
    db_session.commit()
Example #8
0
    def post(self):
        if request.json:
            data = request.json
        else:
            data = request.form

        if (len(data.get('job_id')) == 0 or len(data.get('first_name')) == 0
                or len(data.get('last_name')) == 0
                or len(data.get('hire_date')) == 0
                or len(str(data.get('salary'))) == 0
                or int(data.get('salary')) == 0
                or len(str(data.get('commission_pct'))) == 0
                or len(data.get('email')) == 0
                or data.get('department_id') == 0):

            return jsonify({'message': 'Preencha todos os campos.'}), 409

        newEmployee = Employee().employee_form_data(data)
        newEmployee.employee_id = Employee.query.order_by(
            Employee.employee_id.desc()).first().employee_id + 1
        newEmployee.hire_date = datetime.strptime(data.get('hire_date'),
                                                  '%Y-%m-%d %H:%M:%S')
        db.session.add(newEmployee)

        try:
            db.session.commit()
            return jsonify({'message': 'Employee inserido.'})
        except Exception as e:
            return jsonify(
                {'message': 'Não foi possivel executar a operação.'}), 500
Example #9
0
def create_invoice():
    if Security.is_login(SK):
        item = Item()
        employee = Employee()
        return render_template('invoice/create_invoice.html', title='Create Invoice', items=item.get_items(),
                               employees=employee.get_employees())
    return redirect(url_for('login', callback=stack()[0][3]))
Example #10
0
	def test_callingGetDevelopmentPlansWithAsManagerEqualToTrueCallsFilterWithOwnerManagerAsArgument(self):
		employee = Employee()
		employee.pk = 38
		DevelopmentPlan.objects.filter = mock.MagicMock()
		DevelopmentPlan.objects.filter.return_value.order_by = mock.MagicMock()
		employee.getDevelopmentPlans(as_manager=True)
		DevelopmentPlan.objects.filter.assert_called_once_with(owner__manager__pk=38)
Example #11
0
def get_all_employees():
    with sqlite3.connect("./kennel.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            e.id,
            e.name,
            e.address,
            e.location_id,
            l.name location_name,
            l.address location_address
        FROM employee e
        JOIN location l
            ON l.id = e.location_id
        """)

        employees = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            employee = Employee(row['id'], row['name'], row['address'],
                                row['location_id'])

            location = Location(row['location_id'], row['location_name'],
                                row['location_address'])

            employee.location = location.__dict__

            employees.append(employee.__dict__)

    return json.dumps(employees)
Example #12
0
File: love.py Project: sharan1/love
def get_love(sender_username=None, recipient_username=None, limit=None):
    """Get all love from a particular sender or to a particular recipient.

    :param sender_username: If present, only return love sent from a particular user.
    :param recipient_username: If present, only return love sent to a particular user.
    :param limit: If present, only return this many items.
    """
    sender_username = logic.alias.name_for_alias(sender_username)
    recipient_username = logic.alias.name_for_alias(recipient_username)

    if not (sender_username or recipient_username):
        raise TaintedLove('Not gonna give you all the love in the world. Sorry.')

    if sender_username == recipient_username:
        raise TaintedLove('Who sends love to themselves? Honestly?')

    love_query = (
        Love.query()
        .filter(Love.secret == False)  # noqa
        .order(-Love.timestamp)
    )

    if sender_username:
        sender_key = Employee.get_key_for_username(sender_username)
        love_query = love_query.filter(Love.sender_key == sender_key)

    if recipient_username:
        recipient_key = Employee.get_key_for_username(recipient_username)
        love_query = love_query.filter(Love.recipient_key == recipient_key)

    if limit:
        return love_query.fetch_async(limit)
    else:
        return love_query.fetch_async()
Example #13
0
    def post(self):
        if (self.request.get('username')):
            user = self.request.get('username')
        else:
            user = self.session['username']
        employee_query = Employee.query(Employee.login_name == user)
        employee = employee_query.fetch()[0]

        timesheet_query = Timesheet.query(Timesheet.time_period == self.request.get('time_period'), Timesheet.worked_by == employee.key)
        timesheet = timesheet_query.fetch()

        currentPositions = []
        for sheet in timesheet:
            currentPositions.append(sheet.position)

        for position in employee.positions:
            if position not in currentPositions:
                new_timesheet = Timesheet(worked_by=employee.key, position=position, time_period=self.request.get('time_period'))
                new_timesheet.put()
                timesheet.append(new_timesheet)

        jsonSheet = {'sheets': []}
        for t in timesheet:
            obj = {
                'worked_by': Employee.query(Employee.key == t.worked_by).fetch()[0].login_name,
                'position': Position.query(Position.key == t.position).fetch()[0].title,
                'hours_worked': t.hours_worked,
                'time_period': t.time_period,
                'is_submitted': t.is_submitted,
                'is_approved': t.is_approved
            }
            jsonSheet['sheets'].append(obj)

        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(jsonSheet))
Example #14
0
    def ask_employee(self, inputtxt=None):
        """Ask the title for the task"""

        while_breaker = 1

        while True:

            # This helps the testing, since these are kind of
            # infinite loops while testing, there's need for something
            # that can break them automatically
            if while_breaker > 100:
                break
            else:
                while_breaker += 1

            utils.cls()
            name = utils.get_input(inputtxt)

            if not name:
                utils.pause('Error: Blanks spaces are not allowed')
                continue

            try:
                employee = Employee.get(Employee.name == name)
            except Employee.DoesNotExist:
                employee = Employee.create(name=name)

            return employee.id_employee
Example #15
0
def profile_handler(doc, name, url, path):
    filename = os.path.join(path, name + ".html")
    employee = Employee(name=name, url=url)

    # 只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div", class_="box_rt01 list", limit=1)
    if not divs or len(divs) == 0:
        div = soup
    else:
        div = divs[0]

    with open(filename, 'wb') as fp:
        content = div.prettify()
        fp.write(content)
        fp.close()

    h3s = div.find_all('h3')
    if h3s and len(h3s) != 0:
        title = h3s[0].get_text()
        title = ''.join(title.split())
        print title
        for t in PROFILE_TITLES:
            if t in title:
                employee.title = title
                print "got => " + title
                break
    else:
        print "not found h3"
    # 使用纯文本方式处理
    lines = div.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines,employee=employee,force_email=True)
    return parser.parse()
Example #16
0
def profile_handler(doc, name, url, path):
    filename = os.path.join(path, name + ".html")
    employee = Employee(name=name, url=url)

    # 只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div", attrs={"id":"right_2"}, limit=1)
    if not divs or len(divs) == 0:
        return employee

    div = divs[0]
    if not os.path.exists(filename):
        with open(filename, 'wb') as fp:
            content = div.prettify()
            fp.write(content)
            fp.close()
    
    researches = [' ',' ']
    tds = div.find_all(name="td",attrs={"bgcolor":"#FFFFFF","class":"ft12","valign":"top"},limit=4)
    if len(tds) == 4:
        researches[0] = tds[2].get_text().strip()
        researches[1] = tds[3].get_text().strip()
        employee.research = researches[0] + ";" +researches[1]
        print "research:" + employee.research 
    # 使用纯文本方式处理
    lines = div.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines,employee=employee,ignore=set(['research']))
    return parser.parse()
def get_single_employee(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            e.id,
            e.name,
            e.address,
            e.location_id,
            l.name location_name,
            l.address location_address
        FROM employee e
        JOIN Location l
            ON l.id = e.location_id
        WHERE e.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an employee instance from the current row
        employee = Employee(data['id'], data['name'], data['address'],
                            data['location_id'])
        location = Location(data['location_id'], data['location_name'],
                            data['location_address'])
        employee.location = location.__dict__
        return json.dumps(employee.__dict__)
def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    from models import Department, Employee, Role
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    # Create the fixtures
    engineering = Department(name='Engineering')
    db_session.add(engineering)
    hr = Department(name='Human Resources')
    db_session.add(hr)

    manager = Role(name='manager')
    db_session.add(manager)
    engineer = Role(name='engineer')
    db_session.add(engineer)

    peter = Employee(name='Peter', department=engineering, role=engineer)
    db_session.add(peter)
    roy = Employee(name='Roy', department=engineering, role=engineer)
    db_session.add(roy)
    tracy = Employee(name='Tracy', department=hr, role=manager)
    db_session.add(tracy)
    db_session.commit()
Example #19
0
def test_history_just_one_day():
  entries = ['2018-04-12T08:00:00','2018-04-12T12:00:00','2018-04-12T13:00:00','2018-04-12T19:00:00']
  timesheet = TimeSheet(entries)
  employee = Employee(timesheet, default_workload, default_processor)
  history = employee.history(datetime(2018, 4,12), datetime(2018, 4,12))
  assert len(history) == 1
  assert history[0]['day'] == '2018-04-12'
  assert history[0]['balance'] == 60
Example #20
0
def add_employee(name_rus, surname_rus):
    """Adding employee to database"""
    employee = Employee(name_rus, surname_rus)
    conn = sqlite3.connect(database_url)
    conn.execute('INSERT INTO employees VALUES (NULL, ?, ?, ?, ?, ?)',
                 employee.get_values())
    conn.commit()
    conn.close()
Example #21
0
	def test_callingGetEmployeesCallsFilterOnEmployeeWithCompanyPkAsArgumentAndIsMangerEqualToTrue(self):
		employee = Employee()
		company = Company()
		company.pk = 8
		employee.company = company
		with mock.patch.object(Employee, 'objects') as query_mock:
			employee.getEmployees()
			query_mock.filter.assert_called_with(company__pk=company.pk, is_manager=True)
Example #22
0
def test_total_interval_duration():
  entries = ['2018-04-10T05:43:00', '2018-04-10T09:28:00', '2018-04-10T09:46:00', '2018-04-10T11:05:00',
    '2018-04-12T08:00:00','2018-04-12T12:00:00','2018-04-12T13:00:00','2018-04-12T20:00:00',
    '2018-04-16T08:00:00','2018-04-16T09:00:00','2018-04-16T13:00:00','2018-04-16T14:00:00',]
  timesheet = TimeSheet(entries)
  employee = Employee(timesheet, default_workload, default_processor)
  assert str(employee.total_interval_duration('2018-04-10')) == '0:18:00'
  assert str(employee.total_interval_duration('2018-04-12')) == '1:00:00'
Example #23
0
 def mutate(self, info, name_d, name_e):
     department = Department.query.filter_by(name=name_d).first()
     employee = Employee(name=name_e)
     if department is not None:
         employee.department = department
     db_session.add(employee)
     db_session.commit()
     return CreateEmployee(employee=employee)
Example #24
0
def profile_handler(doc, name, url, path):
    symbols = {
        u'电话:': 'tel',
        u'联系电话:': 'tel',
        u'传真:': 'fax',
    }

    employee = Employee(name=name, url=url)
    # 太乱了,只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div", class_="box_detail", limit=1)
    if not divs or len(divs) == 0:
        return employee
    div = divs[0]

    filename = path + name + ".html"
    with open(filename, 'wb') as fp:
        content = div.prettify()
        fp.write(content)
        fp.close()

    td_left = div.find_all("td",
                           attrs={
                               "style": "line-height: 16px",
                               "align": "left"
                           })
    if not td_left or len(td_left) == 0:
        return employee

    # 解析详细内容
    links = div.find_all("a", limit=2)
    for link in links:
        if link.string:
            if '@' in link.string:
                employee.email = link.string
    for count, tag in enumerate(td_left[0].children):
        if not tag.string:
            continue
        if count > 15:
            break

        text = tag.string
        text = ''.join(text.split())
        if len(text) == 0:
            continue
        for symbol, name in symbols.items():
            idx = text.find(symbol)
            if idx != -1:
                idx += len(symbol)
                value = text[idx:]
                if hasattr(employee, name):
                    setattr(employee, name, value)
                    symbols
                    # print (name + ":" + value)
                else:
                    print("no attr %s in employee" % name)
                break
    return employee
Example #25
0
def handler(tag):
    name = tag.get_text()
    name = ''.join(name.split())
    names = name.split('_')
    name = names[0]
    employee = Employee(url=tag['href'], name=name)
    if len(names) >= 2:
        employee.title = names[1]
    return employee
Example #26
0
 def test_callingGetDevelopmentPlansWithAsManagerEqualToTrueCallsFilterWithOwnerManagerAsArgument(
         self):
     employee = Employee()
     employee.pk = 38
     DevelopmentPlan.objects.filter = mock.MagicMock()
     DevelopmentPlan.objects.filter.return_value.order_by = mock.MagicMock()
     employee.getDevelopmentPlans(as_manager=True)
     DevelopmentPlan.objects.filter.assert_called_once_with(
         owner__manager__pk=38)
Example #27
0
def handler(tag):
    name = tag.get_text()
    name = ''.join(name.split())
    names = name.split('_')
    name = names[0]
    employee = Employee(url=tag['href'], name=name)
    if len(names) >= 2:
        employee.title = names[1]
    return employee
Example #28
0
def profile_handler(doc,name,url,path):
    # employee可用属性(url, name, email, tel, title, profile, research, departments,fax,addr):
    symbols = {
        u'Email:'    :'email',
        u'邮箱:'      :'email',
        u'电子邮件:'   :'email',
        u'电子邮箱:'   :'email',
        u'电话:'      :'tel',  
        u'联系电话:'   :'tel',
        u'Tel:'       :'tel',
        u'办公电话:'   :'tel',
        u'传真:'      :'fax',  
        u'URL:'      :'url',
        u'职称:'      :'title'
    }
    employee = None
    
    # 太乱了,只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(id="s2_right_con",limit=1)
    filename = path+name+".html"
    if not divs or len(divs) == 0:
        return Employee(name=name,url=url)
    div =divs[0]
    with open(filename,'wb') as fp:
        content = div.prettify()
        fp.write(content)
        fp.close()
     
    
    employee = Employee()
    # parse name
    name_h4 = div.h4
    if name_h4:
        employee.name = name_h4.string.strip(' \t\n\r')
    else:
        print name_h4
    
    for tag in div.children:
        if not tag.string:
            continue
        text = tag.string.strip(' \t\n\r')
        if len(text) == 0:
            continue
        for symbol,name in symbols.items():
            idx = text.find(symbol)
            if idx != -1:
                idx += len(symbol)
                value = text[idx:]
                if hasattr(employee, name):
                    setattr(employee, name, value)
                    symbols
                    # print (name + ":" + value)
                else:
                    print ("no attr %s in employee" % name)
                break
    return  employee
Example #29
0
def profile_handler(doc, name, url, path):
    # employee可用属性(url, name, email, tel, title, profile, research, departments,fax,addr):
    symbols = {
        u'Email:': 'email',
        u'邮箱:': 'email',
        u'电子邮件:': 'email',
        u'电子邮箱:': 'email',
        u'电话:': 'tel',
        u'联系电话:': 'tel',
        u'Tel:': 'tel',
        u'办公电话:': 'tel',
        u'传真:': 'fax',
        u'URL:': 'url',
        u'职称:': 'title'
    }
    employee = None

    # 太乱了,只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(id="s2_right_con", limit=1)
    filename = path + name + ".html"
    if not divs or len(divs) == 0:
        return Employee(name=name, url=url)
    div = divs[0]
    with open(filename, 'wb') as fp:
        content = div.prettify()
        fp.write(content)
        fp.close()

    employee = Employee()
    # parse name
    name_h4 = div.h4
    if name_h4:
        employee.name = name_h4.string.strip(' \t\n\r')
    else:
        print name_h4

    for tag in div.children:
        if not tag.string:
            continue
        text = tag.string.strip(' \t\n\r')
        if len(text) == 0:
            continue
        for symbol, name in symbols.items():
            idx = text.find(symbol)
            if idx != -1:
                idx += len(symbol)
                value = text[idx:]
                if hasattr(employee, name):
                    setattr(employee, name, value)
                    symbols
                    # print (name + ":" + value)
                else:
                    print("no attr %s in employee" % name)
                break
    return employee
Example #30
0
	def test_callingCanAssociateNewPlanReturnsFalseIfTheEmployeeHasAnOpenDevelopmentPlan(self):
		employee = Employee()
		employee.pk = 38
		employee.user = User()
		employee.user.pk = 9
		CompetenceFieldCollectionToUserRelation.objects.filter = mock.MagicMock()
		CompetenceFieldCollectionToUserRelation.objects.filter.return_value.exists = mock.MagicMock()
		CompetenceFieldCollectionToUserRelation.objects.filter.return_value.exists.return_value = [CompetenceFieldCollectionToUserRelation(employee.user, finished_at=None),]
		self.assertFalse(employee.canAssociateNewPlan())
		CompetenceFieldCollectionToUserRelation.objects.filter.assert_called_once_with(user__pk=employee.user.pk, finished_at=None)
Example #31
0
def create_employee():
    # print request.
    employee_data = json.loads(request.data)
    emp = Employee()
    for k, v in employee_data.iteritems():
        if k == 'id': continue
        emp.__setattr__(k, v)
    db.session.add(emp)
    db.session.commit()
    return make_response()
Example #32
0
	def test_callingGetDevelopmentPlansCallsFilterAndOrderByOnDevelopmentPlanWithGivenUserAsArgument(self):
		employee = Employee()
		employee.pk = 38
		employee.user = User()
		employee.user.pk = 9
		DevelopmentPlan.objects.filter = mock.MagicMock()
		DevelopmentPlan.objects.filter.return_value.order_by = mock.MagicMock()
		employee.getDevelopmentPlans()
		DevelopmentPlan.objects.filter.assert_called_once_with(owner__pk=38)
		DevelopmentPlan.objects.filter.return_value.order_by.assert_called_once_with('-created_at')
Example #33
0
 def test_callingGetEmployeesCallsFilterOnEmployeeWithCompanyPkAsArgumentAndIsMangerEqualToTrue(
         self):
     employee = Employee()
     company = Company()
     company.pk = 8
     employee.company = company
     with mock.patch.object(Employee, 'objects') as query_mock:
         employee.getEmployees()
         query_mock.filter.assert_called_with(company__pk=company.pk,
                                              is_manager=True)
Example #34
0
 def test_callingCreatePlansCallsCreatePlanOneTimePerEmployeePk(self):
     Employee.objects.get = mock.MagicMock()
     Employee.createDevelopmentPlan = mock.MagicMock()
     Employee.objects.get.return_value = Employee()
     Employee.objects.get.return_value.user = User()
     Employee.objects.get.return_value.manager = Employee()
     Employee.objects.get.return_value.manager.user = User()
     DevelopmentPlan.save = mock.MagicMock()
     self.employee.createDevelopmentPlans([1, 3, 4], 1, self.current_user)
     self.assertEquals(3, Employee.createDevelopmentPlan.call_count)
Example #35
0
def profile_handler(doc,name,url,path):
    symbols = {
        u'电话:'      :'tel',  
        u'联系电话:'   :'tel',
        u'传真:'      :'fax',
    }
        
    employee = Employee(name=name,url=url)
    # 太乱了,只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div",class_="box_detail",limit=1)
    if not divs or len(divs) == 0:
        return employee
    div = divs[0]
    
    filename = path+name+".html"
    with open(filename,'wb') as fp:
        content = div.prettify()
        fp.write(content)
        fp.close()
    
    td_left = div.find_all("td",attrs={ "style":"line-height: 16px","align":"left"})
    if not td_left or len(td_left) == 0:
        return employee
    
    # 解析详细内容
    links = div.find_all("a",limit=2)
    for link in links:
        if link.string:
            if '@' in link.string:
                employee.email = link.string
    for count,tag in  enumerate(td_left[0].children):
        if not tag.string:
            continue
        if count > 15:
            break
        
        text = tag.string
        text = ''.join(text.split())
        if len(text) == 0:
            continue
        for symbol,name in symbols.items():
                idx = text.find(symbol)
                if idx != -1:
                    idx += len(symbol)
                    value = text[idx:]
                    if hasattr(employee, name):
                        setattr(employee, name, value)
                        symbols
                        # print (name + ":" + value)
                    else:
                        print ("no attr %s in employee" % name)
                    break
    return employee
Example #36
0
 def new(cls, title, employee, time, notes):
     """Create new entry"""
     try:
         emp = Employee.with_name(employee)
     except IntegrityError:
         emp = Employee.find_by_name(employee)[0]
     employee = emp.name
     return cls.create(title=title,
                       employee=employee,
                       time=time,
                       notes=notes)
Example #37
0
def add_recipient(hash_key, recipient):
    loveLink = LoveLink.query(LoveLink.hash_key == hash_key).get()
    if (loveLink is None):
        raise NoSuchLoveLink("Couldn't Love Link with id {}".format(hash_key))

    # check that user exists, get_key_for_username throws an exception if not
    recipient_username = logic.alias.name_for_alias(recipient)
    Employee.get_key_for_username(recipient_username)

    loveLink.recipient_list += ', ' + recipient
    loveLink.put()
Example #38
0
def handler(tag):
    employee = Employee()
    name_divs = tag.find_all("div", class_="teacher-title")
    if name_divs and len(name_divs) != 0:
        employee.name = name_divs[0].get_text()
        employee.name = ''.join(employee.name.split())

    # 使用纯文本方式处理
    lines = tag.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines, employee=employee)
    return parser.parse()
Example #39
0
def load_values():
    conn = mysql.connect()
    cursor = conn.cursor()
    print('\n\nINITIALIZING DB\n\n')

    query1 = """
        INSERT INTO department_lookup (token, department)
        VALUES (%s,%s)"""
    for i, dept in enumerate(client.departments):
        cursor.execute(query1, (dept.token, client.DEPARTMENT_LIST[i]))
        print(dept.token + client.DEPARTMENT_LIST[i] + ' has been inserted.',
              file=stderr)

    emp = Employee(cursor, conn, immediate_commit=False)
    for e in client.employees:
        emp.insert(e.token, e.first_name, e.last_name, e.parent_token)
        print(e.token + 'h has been inserted.', file=stderr)

    desc = "My primary role is managing different banking sectors involved in asset management, sanctioning loans, " \
           "mortgages, investments, and account operations. I oversee the efficient day to day processes as well as " \
           "preparing forecasts and reports to drive the overall success of our clients and the department. "

    man = Manager(cursor, conn, immediate_commit=False)
    for dept in client.DEPARTMENT_LIST:
        man.insert(client.MANAGERS[dept]['email'],
                   client.MANAGERS[dept]['pass'],
                   client.MANAGERS[dept]['first_name'],
                   client.MANAGERS[dept]['last_name'], 'Sr. Division Manager',
                   desc, client.MANAGERS[dept]['manager_dept_FK'],
                   client.MANAGERS[dept]['gender'])

    trans = Transaction(cursor, conn, immediate_commit=False)
    for t in client.transactions:
        if t.recipient_user_token is None:
            trans.insert(
                t.sender_business_token,
                t.recipient_business_token,
                Transaction.current_time(t.created_time),
                t.amount,
            )
        else:
            trans.insert(
                t.sender_business_token,
                t.recipient_user_token,
                Transaction.current_time(t.created_time),
                t.amount,
            )
    conn.commit()
    conn.close()
    simulate_startup()
    session['db_init'] = True

    create_background_scheduler()
Example #40
0
 def setUp(self):
     self.departament = Departament('project')
     self.employee_ivan = Employee('Ivan',
                                   'Ivanov',
                                   'engineer',
                                   'project')
     self.employee_petr = Employee('Petr',
                                   'Petrov',
                                   'lead_engineer',
                                   'project')
     self.departament.add_empoyees(self.employee_ivan)
     self.departament.add_empoyees(self.employee_petr)
Example #41
0
File: tests.py Project: Nkirui/kazi
    def test_new_model_creation(self):
        """Check new model instantiation."""
        initial_count = Employer.objects.count()
        self.new_employer.save()
        new_count = Employer.objects.count()
        self.assertNotEqual(initial_count, new_count)

        self.name2 = 'employe223'
        self.new_employee = Employee(name=self.name2,
                                     employer=self.new_employer)
        self.new_employee.save()
        self.assertEqual(len(Employee.objects.all()), 1)
Example #42
0
def make_emp(line, cp):
    flds = line.split('^')
    if Employee.has_payrecord(flds[1]):
        return Employee.get_by_name(flds[1])
    return Employee.create(
        dfn=flds[0],
        name=flds[1],
        grade=int(flds[2]),
        step=int(flds[3]),
        fte=int(float(flds[4]) * 100),
        cp=cp
    )
class TestEmployee():

    employees = [
        pytest.param(Employee(None, 'NameEmp1', 'LastnameEmp1', 100), id='Emp 1'),
        pytest.param(Employee(None, 'NameEmp2', 'LastnameEmp2', 450), id='Emp 2'),
        pytest.param(Employee(None, 'NameEmp3', 'LastnameEmp3', 3900), id='Emp 3'),
        pytest.param(Employee(None, 'NameEmp4', 'LastnameEmp4', 380), id='Emp 4')
    ]

    @pytest.mark.parametrize('employee', employees)
    def test_email(self, employee):
        assert employee.email == f'{employee.username}.{employee.lastname}@email.com'
Example #44
0
def handler(tag):
    employee = Employee()
    name_divs = tag.find_all("div",class_="teacher-title")
    if name_divs and len(name_divs) != 0:
        employee.name = name_divs[0].get_text()
        employee.name = ''.join(employee.name.split())
    
    # 使用纯文本方式处理
    lines = tag.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines,employee=employee)
    return parser.parse()
Example #45
0
def profile_handler(doc,name,url,path):
    # 太乱了,只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    div = soup.find_all(id="s2_right_con",limit=1)
    filename = path+name+".html"
    if not div or len(div) == 0:
        return Employee(name=name,url=url)
    with open(filename,'wb') as fp:
        content = div[0].prettify()
        fp.write(content)
        fp.close()
    return Employee(name=name,url=url)
Example #46
0
    def setUp(self):
        self.region = Region(name="test_region")
        self.region.save()
        self.company = Company(code="1001", name="test_company", region=self.region)
        self.company.save()

        self.store = Store(code="10011001", name="test_store", company=self.company)
        self.store.save()

        self.emp_region = Employee(username="******", organization=self.region)
        self.emp_company = Employee(username="******", organization=self.company)
        self.emp_store = Employee(username="******", organization=self.store)
Example #47
0
def new_user(request):
	use = User.objects.create_user(request.GET['username'],'',request.GET['pass'])
	use.last_name = request.GET['lname']
	use.first_name = request.GET['fname']
	use.save()
	new_date = datetime.date.today() - datetime.timedelta(days=1)
	e = Employee()
	e.user = use
	e.lastVoted = new_date
	e.save()
	user = authenticate(username=request.GET['username'],password=request.GET['pass'])
	login(request,user)
	return HttpResponseRedirect('/home/')
Example #48
0
File: web.py Project: sharan1/love
def me_or_explore(user):
    current_employee = Employee.get_current_employee()
    username = logic.alias.name_for_alias(user.lower().strip())

    try:
        user_key = Employee.get_key_for_username(username)
    except NoSuchEmployee:
        abort(404)

    if current_employee.key == user_key:
        return redirect(url_for('me'))
    else:
        return redirect(url_for('explore', user=username))
Example #49
0
    def post(self):
        dept = self.request.get("department")
        user = users.get_current_user()

        e = Employee(user=user, department=dept)
        e.put()

        mail.send_mail(sender="Random Lunch <*****@*****.**>",
              to=user.nickname(),
              subject="Get Ready to Meet HubSpotters",
              body="Thanks! You'll get an email soon matching you up with your first lunch date.")

        self.redirect("/thanks/")
Example #50
0
 def testCache(self):
     pin='5'
     self.assertEquals(Employee.objects.all().count(), self.c)
     self.assertEquals(Employee.objects.get(PIN=pin).PIN, pin)
     self.assertEquals(Employee.objects.count(), self.c)
     Employee.clear()
     self.assertEquals(Employee.objects.count(), 0)
     self.assertEquals(Employee.objects.filter(PIN=pin).count(), 0)
     try:
         emp=Employee.objects.get(PIN=pin)
     except:
         emp=None
     self.assertEquals(emp, None)
Example #51
0
	def test_callingGetDevelopmentPlansReturnsListOfDevelopmentPlans(self):
		employee = Employee()
		employee.pk = 38
		employee.user = User()
		employee.user.pk = 9
		development_plan_one = DevelopmentPlan()
		development_plan_two = DevelopmentPlan()
		DevelopmentPlan.objects.filter = mock.MagicMock()
		DevelopmentPlan.objects.filter.return_value.order_by = mock.MagicMock()
		DevelopmentPlan.objects.filter.return_value.order_by.return_value = [development_plan_one, development_plan_two]
		development_plans = employee.getDevelopmentPlans()
		self.assertEquals(2, len(development_plans))
		self.assertTrue(isinstance(development_plans[0], DevelopmentPlan))
Example #52
0
def profile_handler(doc, name, url, path):
    filename = os.path.join(path, name + ".html")
    employee = Employee(name=name, url=url)

    # 只保存名称和个人主页,个人简历文件另存当前目录
    soup = BeautifulSoup(doc, Config.SOUP_PARSER)
    divs = soup.find_all(name="div", attrs={"class":"page_right addpage_right"}, limit=1)
    if not divs or len(divs) == 0:
        div= soup
    else:
        div = divs[0]
    if not os.path.exists(filename):
        with open(filename, 'wb') as fp:
            content = div.prettify()
            fp.write(content)
            fp.close()

    tds = div.find_all('td')
    if tds and len(tds) == 11:
        department =  tds[2].get_text()
        if department:
            department = ''.join(department.split())
            if department and len(department) != 0:
                employee.departments = department

        title =  tds[4].get_text()
        if title:
            title = ''.join(title.split())
            if title and len(title) != 0:
                employee.title = title

        email = tds[8].get_text()
        if email:
            email = ''.join(email.split())
            if email and len(email) != 0:
                employee.email = email

        research =  tds[10].get_text()
        if research:
            research = ''.join(research.split())
            if research and len(research) != 0:
                employee.research = research

    divs = soup.find_all(name="div", attrs={"class":"text_more"}, limit=1)
    if divs and len(divs) != 0:
        div = divs[0]
    # 使用纯文本方式处理
    lines = div.stripped_strings
    # text=div.get_text(strip=True)
    parser = ProfileParser(lines=lines,employee=employee,set_attr_hook=set_attr_hook)
    return parser.parse()
Example #53
0
def handler(tag):
    employee = Employee()
    ass = tag.find_all('a',class_="orangea")
    if ass and len(ass) != 0:
        employee.name = ass[0].get_text()
        employee.name = ''.join(employee.name.split())
        employee.profile = ass[0]['href']
    
    ass = tag.find_all('a',class_="black01")
    if ass and len(ass) != 0:
        lines = ass[0].stripped_strings
        parser = ProfileParser(lines=lines,employee=employee)
        employee = parser.parse()
    return employee
Example #54
0
def handler(tag):
    employee = Employee()
    names = tag.get_text()
    names = ''.join(names.split())
    names = names.replace(')','')
    names = names.replace(')','')
    names = names.replace('(','(')
    names = names.split('(')
    employee.name = names[0]
    if len(names) >= 2:
        employee.title = names[1]
    employee.url = tag['href']
    print employee.name, employee.title
    return employee
Example #55
0
    def get(self):
        key = self.request.get("key", False)
        if not key or key != "hartley-rulez":
            self.error(401)
            return self.response.out.write("What's the magic password??")

        # commence shufflin' http://youtu.be/KQ6zr6kCPj8
        all_employees = [e for e in Employee.all()]  # lists are easier to work w than Query objects
        already_matched_employees = []
        created_lunches = []

        for employee in all_employees:
            if employee not in already_matched_employees:

                already_matched_employees.append(employee)
                employees_left = [e for e in all_employees if e not in already_matched_employees]
                partner = choose_partner(employees_left, employee)
                if partner:
                    logging.info("creating lunch between %s and %s" % (employee, partner))
                    already_matched_employees.append(partner)
                    l = Lunch(employees=[employee.key(), partner.key()])
                    l.put()
                    created_lunches.append(l)
                else:
                    logging.info("couldn't find lunch mate for %s" % employee)
                    already_matched_employees.remove(employee)

        logging.info("created lunches:")
        logging.info(created_lunches)
Example #56
0
def handler(tag):
    employee = Employee(url=tag['href'])
    # 刘全勇:                                        硕士生导师 
    string = ''.join(tag.get_text().split())
    string_splits = string.split(u':')
    if len(string_splits) == 1:
        employee.name = string_splits[0]
    elif len(string_splits) == 2:
        employee.name = string_splits[0]
        employee.title = string_splits[1]
    else:
        return None
    
    print("name:"+employee.name )

    return employee
Example #57
0
	def clean(self):
		"""
		Do validation
		"""
		super(EmployeeForm, self).clean()

		username = self.cleaned_data.get('user_name')

		if username:

			if not Employee.isValidUsername(username):
				raise forms.ValidationError(_(
					'Invalid username format. Accepted characters are A-Z,a-z,0-9,_-,.'
				))

			if User.objects.filter(username__exact = username).exists():
				raise forms.ValidationError(_('A user with the given username already exists'))

		email = self.cleaned_data.get('email')
		confirm_email = self.cleaned_data.get('confirm_email')
		if not email == confirm_email:
			raise forms.ValidationError(_('The emails are not equal'))
		if User.objects.filter(email__exact = self.cleaned_data.get('email')).exists():
			raise forms.ValidationError(_('A user with the given email already exists'))
		return self.cleaned_data
Example #58
0
    def post(self):
        employee_query = Employee.query(Employee.is_admin == False)
        employees = employee_query.fetch()

        employeeKeys = []
        for employee in employees:
            employeeKeys.append(employee.key)

        timesheet_query = Timesheet.query(Timesheet.time_period == self.request.get('time_period'), Timesheet.worked_by.IN(employeeKeys))
        timesheets = timesheet_query.fetch()

        employeeList = []
        for employee in employees:
            is_submitted = False
            is_approved = False
            hours = 0

            for timesheet in timesheets:
                if timesheet.worked_by == employee.key:
                    is_submitted = timesheet.is_submitted
                    is_approved = timesheet.is_approved
                    hours += sum(timesheet.hours_worked)

            employeeList.append({
                'username': employee.login_name, 
                'first_name': employee.first_name, 
                'last_name': employee.last_name,
                'is_submitted': is_submitted,
                'is_approved': is_approved,
                'hours': hours
            })

        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(employeeList))
Example #59
0
 def post(self):
     q_id = int(self.request.get('q_id'))
     q = QueueEntry.get_by_id(q_id)
     twilio_settings = TwilioSettings.all().get()
     schedule = SMSSchedule.all().get()
     tclient = TwilioRestClient(twilio_settings.account_sid, twilio_settings.auth_token)
     if q and q.status == 'P':
         employees = Employee.all()
         for employee in employees:
             entry = ReportingEntry.all().filter('reporting_date = ', q.report_date).filter('mobile_number =', employee.mobile_number).get()
             if not entry:
                 entry = ReportingEntry(name = employee.name, 
                            mobile_number = employee.mobile_number,
                            email = employee.email,
                            reporting_date = q.report_date,
                            reporting_location = "NOT REPORTED",
                            reporting_time = None,
                            employee = employee)
                 entry.put() 
             if schedule.status=='Active':                
                 tclient.sms.messages.create(to = employee.mobile_number, from_ = twilio_settings.twilio_number, body = schedule.message[:160])
                 smslog = SMSLog(message = schedule.message[:160],
                                 from_number = twilio_settings.twilio_number,
                                 to_number = employee.mobile_number,
                                 direction = 'outgoing-scheduled',
                                 employee_name = employee.name)
                 smslog.put()
         q.status = 'S'
         q.save()
Example #60
0
 def get(self):
     template_values = {
         "user":     users.get_current_user(),
         "gravatar": get_gravatar_from_email(users.get_current_user().nickname(), 40),
         "departments": DEPARTMENTS,
         "employee_count": Employee.all().count(),
     }
     self.response.out.write(template.render("templates/employee.html", template_values))