def handler_function(self):
        args = self.get_request_data()

        userId = AuthenticationUtil.getUserIdByToken(self.request)

        startDate, endDate, searchParams = self.getSearchParams(args['search'])

        orders = None
        if args['orderListType'] == 'self':
            searchParams.update({'userId': userId})
            orders = DBOps.getSomeDoc(DBCollonfig.orders, searchParams)
        elif args['orderListType'] == 'company':
            company = DBOps.getOneDoc(
                DBCollonfig.users,
                {'_id': userId},
                {'company': 1}
            )['company']
            searchParams.update({'company': company})
            orders = DBOps.getSomeDoc(DBCollonfig.orders, searchParams)
        elif args['orderListType'] == 'summary':
            orders = DBOps.getSomeDoc(DBCollonfig.orders, searchParams)

        self.result['result'] = {
            'orders': list(orders.sort('createTimeStamp', -1)),
            'searchDate': [startDate.split(' ')[0], endDate.split(' ')[0]],
            'totalCount': orders.count()
        }
        return self.response_success()
Exemple #2
0
    def handler_function(self):
        args = self.get_request_data()

        userId = args['userId']

        user = DBOps.getOneDoc(DBCollonfig.users, {'_id': userId},
                               {'orders': 0})

        companies = DBOps.getOneDoc(DBCollonfig.options,
                                    {'_id': DBCollonfig.orderOption},
                                    {'companies': 1})['companies']

        user['setPermissions'] = [
            k for k, v in user['permissions'].iteritems() if v == 1
        ]

        user['pmsListName'] = [
            UserConfig.permissions[k]
            for k, v in user['permissions'].iteritems() if v == 1
        ]

        self.result['result'] = {
            'user':
            user,
            'companies': [{
                'label': c['name'],
                'value': c['name']
            } for c in companies],
            'permissions': [{
                'key': k,
                'label': v
            } for k, v in UserConfig.permissions.iteritems()],
        }
        self.response_success()
Exemple #3
0
    def handler_function(self):
        args = self.get_request_data()

        newPermissions = {}
        for p in UserConfig.permissions:
            if p in args['setPermissions']:
                newPermissions[p] = 1
            else:
                newPermissions[p] = 0

        DBOps.setOneDoc(
            DBCollonfig.users,
            {'_id': args['_id']},
            {
                '$set': {
                    # 'department': args['department'],
                    'company': args['company'],
                    'tel': args['tel'],
                    'email': args['email'],
                    'qq': args['qq'],
                    'permissions': newPermissions
                }
            })

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doEditUser)

        args['permissions'] = newPermissions
        self.result['result'] = {'userObj': AccountUtil.resUserData(args)}
        return self.response_success(msg=args['username'] + u'用户信息设置成功!')
Exemple #4
0
    def createUser(self, username, password):
        """
            创建账户
        """
        userNum = DBOps.getDocNum(DBCollonfig.users)

        userId = DBCollonfig.startNum + userNum + 1

        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # 初始化用户数据
        user = {
            '_id': userId,
            'username': username,
            'password': Encrypt.password_encrypt(password),
            'permissions': {p: 0
                            for p in UserConfig.permissions},
            'createTime': now,
            'createTimeStamp': TimeUtil.time_conversion(now, 1),
            'lastLogin': now,
            # 'department': '',
            'company': '',
            'tel': '',
            'email': '',
            'qq': ''
        }

        DBOps.insertDoc(DBCollonfig.users, user)

        self.result['result'] = {
            'userObj': AccountUtil.resUserData(user),
            'token': Authentication.generateToken(userId)
        }

        return userId
Exemple #5
0
    def handler_function(self):
        args = self.get_request_data()
        token = args.get('token', None)

        if token:
            setToken, header = Authentication.getVerifyToken(token)
            if setToken.has_key('userId'):
                userId = setToken['userId']
                user = DBOps.getOneDoc(DBCollonfig.users, {'_id': userId})

                DBOps.setOneDoc(DBCollonfig.users, {'_id': user['_id']}, {
                    '$set': {
                        'lastLogin':
                        datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    }
                })

                self.result['result'] = {
                    'userObj': AccountUtil.resUserData(user)
                }

                return self.response_success()
            else:
                self.result['result'] = {'userObj': None}
                return self.response_failure(u'登录过期')
        else:
            self.result['result'] = {'userObj': None}
            return self.response_failure(u'没有登录')
Exemple #6
0
    def handler_function(self):
        args = self.get_request_data()

        username = args['username']
        password = args['password']

        user = DBOps.getOneDoc(DBCollonfig.users, {'username': username})

        if not user:
            return self.response_failure(username + u'用户不存在')

        if user['password'] != Encrypt.password_encrypt(password):
            return self.response_failure(username + u'用户密码错误')

        DBOps.setOneDoc(DBCollonfig.users, {'_id': user['_id']}, {
            '$set': {
                'lastLogin': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        })

        self.result['result'] = {
            'userObj': AccountUtil.resUserData(user),
            'token': Authentication.generateToken(user['_id'])
        }

        # 记录日志
        LogDBOps.writeLog(user['_id'], LogDBConfig.doLogin)

        return self.response_success()
Exemple #7
0
    def handler_function(self):
        args = self.get_request_data()

        DBOps.setOneDoc(DBCollonfig.users, {'_id': args['userId']},
                        {'$set': {
                            'navCollapse': args['setCollapse']
                        }})

        self.response_success()
    def handler_function(self):
        args = self.get_request_data()

        DBOps.removeDoc(DBCollonfig.orders, {'_id': args['orderId']})

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doDelOrder)

        self.response_success()
    def handler_function(self):
        args = self.get_request_data()

        createUser = args.get('createUser', None)
        newContacts = args.get('contacts', None)

        error_list = []
        for each in newContacts:
            isExist = DBOps.getOneDoc(
                DBCollonfig.options,
                {
                    '_id': DBCollonfig.orderOption,
                    'contacts.name': each['name']
                }
            )
            if isExist:
                error_list.append(each['name'])

        if error_list:
            msg = u','.join([err for err in error_list]) + u'已存在'
            return self.response_failure(msg=msg)

        for each in newContacts:
            DBOps.setOneDoc(
                DBCollonfig.options,
                {'_id': DBCollonfig.orderOption},
                {
                    '$push': {
                        'contacts': {
                            'name': each['name'],
                            'realName': each['realName'],
                            'createTime': TimeUtil.time_conversion(
                                each['time'], 2
                            ),
                            'createTimeStamp': each['time'],
                            'createUser': createUser,
                            'tel': each['tel'],
                            'email': each['email'],
                            'qq': each['qq'],
                            'payInfo': each['payInfo'],
                            'workClass': each['workClass']
                        }
                    }
                }
            )

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doCreateContact)

        return self.response_success()
    def handler_function(self):
        args = self.get_request_data()

        now = datetime.now()
        orderId = str(args['userId']) + now.strftime('%Y%m%d%H%M%S')
        nowString = now.strftime('%Y-%m-%d %H:%M:%S')
        order = {
            '_id': orderId,
            'orderId': orderId,
            'userId': args['userId'],
            'title': args['title'],
            'createUser': args['createUser'],
            # 'department': args['department'],
            'company': args['company'],
            'className': args['className'],
            'customerName': args['customerName'],
            'contactName': args['contactName'],
            'expectDate': args['expectDate'],
            'expect': {
                'price': args['price'],
                'tax': args['tax'],
                'num': args['num'],
                'unit': args['unit'],
                'unitNum': args['unitNum'],
                'sumPrice': round(args['sumPrice'], 2),
            },
            'price': args['price'],
            'sumPrice': round(args['sumPrice'], 2),
            'tax': args['tax'],
            'num': args['num'],
            'unit': args['unit'],
            'unitNum': args['unitNum'],
            'desc': args['desc'],
            'createTime': nowString,
            'completeTime': '',
            'paymentTime': '',
            'createTimeStamp': TimeUtil.time_conversion(nowString, 1),
            'completeTimeStamp': 0,
            'paymentTimeStamp': 0,
            'status': 1,
            'evaluation': 0
        }

        DBOps.insertDoc(DBCollonfig.orders, order)

        # 记录日志
        LogDBOps.writeLog(args['userId'], LogDBConfig.doCreateOrder)

        self.response_success()
Exemple #11
0
    def handler_function(self):
        args = self.get_request_data()
        username = args.get('username', None)
        password1 = args.get('password1', None)
        password2 = args.get('password2', None)
        key = args.get('registerKey', None)

        if key != 'szx2018':
            return self.response_failure(username + u'验证码错误')

        if password1 != password2:
            return self.response_failure(username + u'两次密码不一致')

        if re.findall(' ', username):
            return self.response_failure(u'账号不能有空格符号')

        if re.findall(' ', password1):
            return self.response_failure(u'密码不能有空格符号')

        user = DBOps.getOneDoc(DBCollonfig.users, {'username': username})

        if user:
            return self.response_failure(username + u'用户已存在')

        userId = self.createUser(username, password1)

        # 记录日志
        LogDBOps.writeLog(userId, LogDBConfig.doRegister)
        LogDBOps.writeLog(userId, LogDBConfig.doLogin)

        self.response_success()
    def handler_download(self):
        tableData = self.get_argument('tableDate')
        tableType = self.get_argument('tableType')

        filename = tableType + '_' + \
                   datetime.now().strftime('%Y-%m-%d') + '.csv'

        searchParams = {}

        if tableData:
            startDate = time.strptime(tableData, DATE_FORMAT)
            endDateList = tableData.split('-')
            if int(endDateList[1]) + 1 > 12:
                endDateList[0] = '{0:02}'.format(int(endDateList[0]) + 1)
                endDateList[1] = '01'
            else:
                endDateList[1] = '{0:02}'.format(int(endDateList[1]) + 1)
            endDate = time.strptime('-'.join(endDateList), DATE_FORMAT)
            searchParams.update({
                'createTimeStamp': {
                    '$gte': TimeUtil.time_conversion(startDate, 3),
                    '$lte': TimeUtil.time_conversion(endDate, 3)
                }
            })

        if tableType == 'summaryExpect':
            searchParams.update({'status': {'$in': [1, 2]}})
        elif tableType == 'summaryPayment':
            searchParams.update({'status': 3})

        orders = DBOps.getSomeDoc(DBCollonfig.orders, searchParams)

        self.initContactsData()
        self.createToDownload(orders, filename)
    def writeToDB(cls, msg, status):

        if status == 2:
            DBOps.setOneDoc(DBCollonfig.users, {'permissions.summaryOrder': 1},
                            {'$push': {
                                'msg': msg
                            }},
                            multi=True)
        elif status == 3 or status == 1:
            DBOps.setOneDoc(
                DBCollonfig.users,
                {'_id': msg['rcvUserId']},
                {'$push': {
                    'msg': msg
                }},
            )
    def handler_function(self):
        orderOptions = DBOps.getOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderOption},
            {'workClasses': 0}
        )
        classes = orderOptions['classes']
        customers = orderOptions['customers']
        contacts = orderOptions['contacts']
        companies = orderOptions['companies']
        helpInfo = orderOptions['helpInfo']

        self.result['result'] = {
            'classes': [
                {'label': cl['name'], 'value': cl['name']} for cl in classes
            ],
            'customers': [
                {'label': cu['name'], 'value': cu['name']} for cu in customers
            ],
            'contacts': [
                {
                    'label': con['name'] + ' | ' + con['workClass'],
                    'value': con['name']
                } for con in contacts
            ],
            'companies': [
                {'label': com['name'], 'value': com['name']}
                for com in companies
            ],
            'helpInfo': helpInfo
        }

        return self.response_success()
    def handler_function(self):
        args = self.get_request_data()
        userType = args.get('userType', None)
        params = []

        if userType and userType != 'all':
            params.append({'$match': {'userId': int(userType)}})
        params.extend([{
            '$group': {
                '_id': '$contactName',
                'num': {
                    '$sum': 1
                }
            }
        }, {
            '$sort': {
                'num': -1
            }
        }])
        top10Contacts = list(DBOps.getAggregate(DBCollonfig.orders, params))

        if top10Contacts:
            if len(top10Contacts) <= 10:
                self.result['result'] = top10Contacts
            else:
                self.result['result'] = top10Contacts[:10]
            return self.response_success()
        else:
            return self.response_failure(msg=u'暂无数据')
Exemple #16
0
    def writeLog(cls, userId, action, content=None):
        """
            基础结构
        """
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data = {
            'logTime': now,
            'logTimeStamp': int(
                time.mktime(time.strptime(now, '%Y-%m-%d %H:%M:%S')) * 1000
            ),
            'userId': userId,
            'action': action,
            'contact': content
        }

        DBOps.insertDoc(DBCollonfig.log, data)
    def handler_function(self):
        args = self.get_request_data()

        DBOps.setOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderOption},
            {
                '$pull': {
                    args['optionType']: {
                        'name': args['name']
                    }
                }
            }
        )

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], self.LogAction[args['optionType']])

        return self.response_success()
    def handler_function(self):
        args = self.get_request_data()

        customerData = DBOps.getOneDoc(DBCollonfig.options, {
            '_id': DBCollonfig.orderCustomer,
            'contacts.name': args['contactName']
        }, {'contacts.$': 1})
        if customerData:
            self.result['result'] = customerData['contacts'][0]
            self.response_success()
        else:
            self.response_failure(msg=u'该外包已删除')
    def handler_function(self):
        args = self.get_request_data()

        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        DBOps.setOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderHelpInfo},
            {
                '$set': {
                    'helpInfo': [{
                        'content': args['helpInfo'],
                        'createTime': now,
                        'createTimeStamp': TimeUtil.time_conversion(now, 1)
                    }]
                }
            }
        )

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doEditHelpInfo)

        return self.response_success()
Exemple #20
0
    def handler_function(self):
        departments = DBOps.getOneDoc(DBCollonfig.options,
                                      {'_id': DBCollonfig.orderOption},
                                      {'departments': 1})['departments']

        self.result['result'] = {
            'departments': [{
                'label': d['name'],
                'value': d['name']
            } for d in departments]
        }

        return self.response_success()
    def handler_function(self):
        args = self.get_request_data()

        initData = DBOps.getOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderOption},
            {args['optionType']: 1}
        )[args['optionType']]

        if args['optionType'] == 'contacts':
            self.result['result'] = self.initContactsData(args, initData)
        elif args['optionType'] == 'customers':
            self.result['result'] = self.initCustomersData(args, initData)
        else:
            self.result['result'] = OrderUtil.orderListByTime(initData)
        return self.response_success()
    def initContactsData(self):
        """
            初始化外包信息
        """
        contacts = DBOps.getOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderContact},
            {'contacts': 1}
        )['contacts']

        for contact in contacts:
            realName = contact['realName']
            payInfo = contact['payInfo']
            self.contacts[contact['name']] = {
                'realName': realName if realName else u'未设置',
                'payInfo': payInfo if payInfo else u'未设置'
            }
Exemple #23
0
    def handler_function(self):
        total = DBOps.getSomeDoc(DBCollonfig.users, {}, {'orders': 0})

        userList = []
        for user in total:
            user.update({
                'userId':
                user['_id'],
                'pmsListName': [
                    UserConfig.permissions[k]
                    for k, v in user['permissions'].iteritems() if v == 1
                ]
            })
            userList.append(user)

        self.result['result'] = OrderUtil.orderListByTime(userList,
                                                          reverse=False)
        return self.response_success()
    def initContactsData(self, args, initData):
        """
            初始化外包人员信息
        """

        # 搜索删选
        keyName = args['keyName']
        workClass = args['workClass']
        orderContacts = OrderUtil.orderListByTime(initData)

        if keyName or workClass:
            try:
                totalContacts = [
                    o for o in orderContacts
                    if re.match(r'.*' + keyName + '.*', o['name']) and \
                       re.match(workClass, o['workClass'])
                ]
            except Exception as e:
                totalContacts = []
        else:
            totalContacts = orderContacts

        # 分页处理
        page = args['page']
        pageSize = OrderConfig.optionPageSize
        pageStart = (page - 1) * pageSize
        pageEnd = page * pageSize
        contacts = totalContacts[pageStart:pageEnd]

        workClasses = DBOps.getOneDoc(
            DBCollonfig.options,
            {'_id': DBCollonfig.orderOption},
            {'workClasses': 1}
        )['workClasses']

        return {
            'contacts': contacts,
            'totalCount': len(totalContacts),
            'pageSize': OrderConfig.optionPageSize,
            'workClasses': [
                {'label': w['name'], 'value': w['name']}
                for w in workClasses
            ],
        }
Exemple #25
0
    def getlist(cls, page, pageSize, logType):
        skip = (page - 1) * pageSize

        # 条件搜搜参数
        params = []

        if logType != 'all':
            params.append({
                '$match': {
                    'userId': int(logType)
                }
            })

        params.extend([{
            '$lookup': {
                'from': "users",
                'localField': "userId",
                'foreignField': "_id",
                'as': "user"
            }
        }, {
            '$sort': {'logTimeStamp': -1},
        }, {
            '$skip': skip
        }, {
            '$limit': pageSize
        }])

        searchLogs = DBOps.getAggregate(DBCollonfig.log, params)

        resLogs = []
        for log in searchLogs:
            resLogs.append({
                'userId': log['userId'],
                'username': log['user'][0]['username'],
                'logTime': log['logTime'],
                'action': log['action']
            })

        # 求和搜索参数
        params = []
        if logType != 'all':
            params.append({
                '$match': {
                    'userId': int(logType)
                }
            })
        params.append({'$group': {'_id': None, 'count': {'$sum': 1}}})

        totalCount = list(
            DBOps.getAggregate(DBCollonfig.log, params)
        )[0]['count']

        res = {
            'page': page,
            'pageSize': pageSize,
            'totalCount': totalCount,
            'logs': resLogs
        }

        return res
 def init(cls):
     DBManager.init()
     DBOps.init()
    def handler_function(self):
        args = self.get_request_data()
        option = args['option']
        createUser = args['createUser']
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if args['optionType'] == 'contacts':
            oldContact = DBOps.getOneDoc(
                DBCollonfig.options,
                {
                    '_id': DBCollonfig.orderContact,
                    'contacts.name': option['oldName']
                }
            )
            if not oldContact:
                return self.response_failure(msg=u'外包人员不存在')
            DBOps.setOneDoc(
                DBCollonfig.options,
                {
                    '_id': DBCollonfig.orderContact,
                    'contacts.name': option['oldName']
                },
                {
                    '$set': {
                        'contacts.$.name': option['name'],
                        'contacts.$.realName': option['realName'],
                        'contacts.$.tel': option['tel'],
                        'contacts.$.email': option['email'],
                        'contacts.$.workClass': option['workClass'],
                        'contacts.$.payInfo': option['payInfo'],
                        'contacts.$.qq': option['qq'],
                        'contacts.$.createUser': createUser,
                        'contacts.$.createTime': now,
                        'contacts.$.createTimeStamp': TimeUtil.time_conversion(
                            now, 1
                        ),
                    }
                }
            )

            # 记录日志
            LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doEditContact)

            return self.response_success()
        elif args['optionType'] == 'customers':
            DBOps.setOneDoc(
                DBCollonfig.options,
                {
                    '_id': DBCollonfig.orderCustomer,
                    'customers.name': option['name']
                },
                {
                    '$set': {
                        'customers.$.billInfo': option['billInfo'],
                        'customers.$.mailAddress': option['mailAddress'],
                        'customers.$.createUser': createUser,
                        'customers.$.createTime': now,
                        'customers.$.createTimeStamp': TimeUtil.time_conversion(
                            now, 1
                        ),
                    }
                }
            )

            # 记录日志
            LogDBOps.writeLog(args['opsUserId'], LogDBConfig.doEditCustomer)

            return self.response_success()
        else:
            return self.response_failure(msg=u'没有需要修改的信息')
    def handler_function(self):
        args = self.get_request_data()

        setStatus = args.get('status', None)
        orderId = args.get('orderId', None)

        nowStatus = DBOps.getOneDoc(
            DBCollonfig.orders,
            {'_id': orderId}
        )['status']

        if nowStatus == setStatus:
            return self.response_failure(msg='订单状态已被修改!')

        logAction = None

        nowString = datetime.now().strftime(DATETIME_FORMAT)
        setParams = {}
        if setStatus == 1:
            setParams = self.setStatus1(setStatus, args)
            logAction = LogDBConfig.doEditOrder
            if args['opsUserId'] != args['userId']:
                content = {
                    'status': setStatus,
                    'sendUserId': args['opsUserId'],
                    'rcvUserId': args['userId'],
                    'orderTitle': args['title'],
                    'createUser': args['createUser']
                }
                AccountMsg.setOrderMsg(content)

        elif setStatus == 2:
            setParams = self.setStatus2(setStatus, nowString, args)
            logAction = LogDBConfig.doCompleteOrder
            content = {
                'status': setStatus,
                'sendUserId': args['opsUserId'],
                'rcvUserId': 'summaryUser',
                'orderTitle': args['title'],
                'createUser': args['createUser']
            }
            AccountMsg.setOrderMsg(content)

        elif setStatus == 3:
            setParams = self.setStatus3(setStatus, nowString, args)
            logAction = LogDBConfig.doPaymentOrder
            if args['opsUserId'] != args['userId']:
                content = {
                    'status': setStatus,
                    'sendUserId': args['opsUserId'],
                    'rcvUserId': args['userId'],
                    'orderTitle': args['title'],
                    'createUser': args['createUser']
                }
                AccountMsg.setOrderMsg(content)

        DBOps.setOneDoc(
            DBCollonfig.orders,
            {'_id': orderId},
            {'$set': setParams}
        )

        # 记录日志
        LogDBOps.writeLog(args['opsUserId'], logAction)
        self.result['result'] = {'opsTime': nowString}
        return self.response_success(msg='订单状态修改成功!')