Ejemplo n.º 1
0
Archivo: doc.py Proyecto: cash2one/bmp
    def check_uid(self, submit):
        uids = User.uids()
        if submit.__contains__("mainten_uid") and submit["mainten_uid"]:
            if submit["mainten_uid"] not in uids:
                raise ExceptionEx("不存在维护人 %s" % submit["mainten_uid"])

        if submit.__contains__("opt_uid") and submit["opt_uid"]:
            if submit["opt_uid"] not in uids:
                raise ExceptionEx("不存在业务人 %s" % submit["opt_uid"])
Ejemplo n.º 2
0
    def add(_dict):
        from bmp.models.user import User

        if Project.query.filter(Project.name == _dict["name"]).count():
            raise ExceptionEx("项目名 %s 已存在" % _dict["name"])

        uids = User.uids()
        for uid in [_dict[u] for u in _dict if "_uid" in u]:
            if uid not in uids:
                raise ExceptionEx("用户 %s 不存在" % uid)

        proj = Project(_dict)
        db.session.add(proj)
        db.session.commit()
        return proj
Ejemplo n.º 3
0
    def delete(self, tid, eid):
        team = ReportTeam.get(tid)
        if session[USER_SESSION]["uid"] != team["create_uid"]:
            raise ExceptionEx("当前用户无法删除编辑人")

        ReportEditor.delete(eid)
        return self.succ()
Ejemplo n.º 4
0
    def to(self, l):
        try:
            uids = [l.uid, l.approval_uid] + l.copy_to_uid.split(",")
            if l.status == LEAVE.PASS:
                uids += [u.uid for u in Group.get_users(DEFAULT_GROUP.LEAVE.MAIL)]
                to = [User.get(uid)["mail"] for uid in uids]
                to.append("*****@*****.**")
            else:
                to = [User.get(uid)["mail"] for uid in uids]

            status = l.status
            if status != LEAVE.PASS:
                status = u"已退回"

            sub = u"%s的请假申请%s 审批时间:%s 编号:%d" % ( l.uid,status,l.approval_time.strftime("%Y-%m-%d"),l.id)

            self.send(
                to,
                sub,
                "/templates/leave/approval.html",
                "mail.leave.tpl.html",
                leave=l,
                leave_type=Ref.map(LEAVE.TYPE)[int(l.type_id)])

        except Exception,e:
            log.exception(e)
            raise ExceptionEx("邮件发送失败,请重试!")
Ejemplo n.º 5
0
    def add(self, name, obj, expire_time, lead_times):
        try:
            _id = "_".join([obj.__class__.__name__, str(obj.id)])

            if not isinstance(lead_times, list):
                lead_times = [lead_times]

            content = "神盾局OPS系统:前方英雄【%s 编号:%s】即将在【%s】过期,请及时充能!!" % (
                name, str(obj.id), expire_time.strftime("%Y-%m-%d"))

            for lead_time in lead_times:
                date = expire_time - lead_time

                BaseSms.send(self, [
                    u.mobile for u in Group.get_users(DEFAULT_GROUP.SMS.ALERT)
                ],
                             content,
                             date=date,
                             _id="_".join([_id, str(lead_time.days)]))

                BaseMail.send(self, [app.config["MAIL_ALERT"]],
                              content,
                              "",
                              "mail.alert.tpl.html",
                              date=date,
                              _id="_".join([_id, str(lead_time.days)]))

        except Exception, e:
            traceback.print_exc()
            log.exception(e)
            raise ExceptionEx("添加邮件或短信提示失败!")
Ejemplo n.º 6
0
    def delete(pid):
        release = Release.query.filter(Release.id == pid).one()
        if not release.is_draft:
            raise ExceptionEx("该申请已提交,无法删除")

        db.session.delete(release)
        db.session.commit()
Ejemplo n.º 7
0
    def delete(self, lid):
        leave = Leave.get(lid)
        if leave["uid"] != session.get_uid():
            raise ExceptionEx("权限不足")

        Leave.delete(lid)
        return self.succ()
Ejemplo n.º 8
0
    def __init__(self, _dict):
        if not _dict.__contains__("id"):
            _dict["status"] = ""
        elif _dict["type"] == SCRAP.TYPE:
            _dict["approval_uid"] = session[USER_SESSION]["uid"]
            _dict["approval_time"] = datetime.now().strftime("%Y-%m-%d")
            _dict["update_time"] = datetime.now().strftime("%Y-%m-%d")
        else:
            _dict["update_time"] = datetime.now().strftime("%Y-%m-%d")

        if not _dict.__contains__("stock_id"):
            raise ExceptionEx("库存不能为空")
        elif not Stock.query.filter(Stock.id == _dict["stock_id"]).count():
            raise ExceptionEx("库存不存在")

        BaseModel.__init__(self, _dict)
Ejemplo n.º 9
0
    def get_search_fields(self, _clss, is_fuzzy=True):
        _filters = []

        if not isinstance(_clss, list):
            _clss = [_clss]

        for keys in [arg for arg in request.args.keys() if arg != "_"]:
            __filters = []
            for key in keys.split(","):
                has_key = False
                for _cls in _clss:
                    if not hasattr(_cls, key):
                        continue

                    if is_fuzzy:
                        __filters.extend([
                                             getattr(_cls, key).like("%" + arg + "%") for arg in
                                             request.args.getlist(keys)
                                             ])
                    else:
                        __filters.extend([
                                             getattr(_cls, key).like(arg) for arg in request.args.getlist(keys)
                                             ])

                    has_key = True
                    break

                if not has_key:
                    raise ExceptionEx("查询字段%s不存在" % key)

            _filters.append(or_(*__filters))

        return _filters
Ejemplo n.º 10
0
 def delete(name):
     group = Group.query.filter(Group.name == name).one()
     if group.is_buildin:
         raise ExceptionEx("禁止删除内建组")
     db.session.delete(group)
     db.session.commit()
     return True
Ejemplo n.º 11
0
    def edit(id, submit):
        approval = PurchaseApproval.query \
            .filter(PurchaseApproval.purchase_id == id) \
            .filter(PurchaseApproval.type == submit["type"])
        if approval.count():
            raise ExceptionEx("该节点已审批")

        _approval = PurchaseApproval(submit)
        purchase = Purchase.query.filter(Purchase.id == id).one()
        purchase.approvals.append(_approval)

        purchase.cur_approval_type = PurchaseApproval.__next_approval_type(
            _approval.type)

        if _approval.status == PURCHASE.FAIL:
            purchase.is_finished = True
        else:
            if _approval.type == PURCHASE.FLOW_TWO:
                total = sum([g.price * g.amount for g in purchase.goods])
                if total < PURCHASE.PRICE_LIMIT:
                    if not purchase.contract:
                        purchase.is_finished = True
                    else:
                        purchase.cur_approval_type = PURCHASE.FLOW_FOUR
            elif _approval.type == PURCHASE.FLOW_THREE:
                if not purchase.contract:
                    purchase.is_finished = True
            elif _approval.type == PURCHASE.FLOW_FOUR:
                purchase.is_finished = True

        db.session.commit()
        return purchase
Ejemplo n.º 12
0
    def delete(self, uid):
        ldap = Ldap()

        if uid in ["*", u"*"]:
            raise ExceptionEx("无效的uid")
        else:
            ldap.delete(uid)

        User.update()
        return self.succ()
Ejemplo n.º 13
0
    def edit(name, new_name, new_desc):
        name, new_name = name.upper(), new_name.upper()
        group = Group.query.filter(Group.name == name).one()
        if name != new_name and group.is_buildin:
            raise ExceptionEx("内建组禁止修改组名")

        group.name = new_name
        group.desc = new_desc
        db.session.commit()
        return True
Ejemplo n.º 14
0
    def add(cls, _dicts, auto_commit=True):
        '''
        固定资产编号 格式固定一下
        部门+年+月+0001
        比如:IT2015050001
        :param auto_commit:
        :return:
        '''
        if not _dicts.__contains__("no") or Stock.query \
                .filter(Stock.no == _dicts["no"]).count():
            raise ExceptionEx("库存编号已存在")

        if not _dicts.__contains__("category_id"):
            raise ExceptionEx("名称不能为空")

        def create_no():
            businessCategory = session[USER_SESSION]["businessCategory"]
            today = datetime.strptime(_dicts["stock_in_time"], "%Y-%m-%d")
            year, month = today.year, today.month
            beg = datetime(year, month, 1)
            if month == 12:
                end = datetime(year, month, 31)
            else:
                end = datetime(year, month + 1, 1) - timedelta(days=1)

            stocks = [
                int(s.no[-4:]) for s in Stock.query.filter(
                    Stock.stock_in_time.between(beg, end)).all()
            ]
            stocks.append(0)
            return "%s%d%02d%04d" % (businessCategory.upper(), year, month,
                                     max(stocks) + 1)

        _dicts["no"] = create_no()
        stock = Stock(_dicts)
        db.session.add(stock)

        if auto_commit:
            db.session.commit()
        else:
            db.session.flush()

        return stock
Ejemplo n.º 15
0
    def post(self, tid):
        submit = self.request()
        team = ReportTeam.get(tid)
        if session[USER_SESSION]["uid"] != team["create_uid"]:
            raise ExceptionEx("当前用户无法新建编辑人")

        submit["team_id"] = tid

        ReportEditor.add(submit)
        return self.succ()
Ejemplo n.º 16
0
    def __init__(self, _dict):
        BaseModel.__init__(self)

        for k, v in _dict.items():
            if k == "category_id":
                query = Category.query.filter(Category.id == v)
                if not query.count():
                    raise ExceptionEx("不存在的商品id")
                self.category = query.one()
            if k == "spec_id":
                query = Category.query.filter(Category.id == v)
                if not query.count():
                    raise ExceptionEx("不存在的规格id")
                self.spec = query.one()
            if "time" in k:
                setattr(self, k, datetime.strptime(v, "%Y-%m-%d"))
            elif k == "id":
                pass
            else:
                setattr(self, k, v)
Ejemplo n.º 17
0
    def put(self, aid):
        submit = self.request()
        access = Access.get(aid)
        if access["status"] != ACCESS.APPROVAL:
            raise ExceptionEx("申请未提交")

        submit["approval_uid"] = session.get_uid()
        submit["approval_time"] = datetime.now()
        submit["id"] = aid
        Access.edit(submit)
        return self.succ()
Ejemplo n.º 18
0
    def edit(cls, _dicts, auto_commit=True):
        if Stock.query.filter(Stock.no == _dicts["no"]).count():
            raise ExceptionEx("库存编号已存在")

        stock = Database.to_cls(Stock, _dicts)

        if auto_commit:
            db.session.commit()
        else:
            db.session.flush()

        return stock
Ejemplo n.º 19
0
    def put(self, uid, oldpass=None, newpass=None):
        if not oldpass:
            if not session.__contains__(USER_SESSION):
                raise ExceptionEx("未登录")

            if not User.get(session[USER_SESSION]["uid"])["is_admin"]:
                raise ExceptionEx("权限不足")

        if not uid or uid in ["*", u"*"]:
            return self.fail("无效的用户名")

        newpass = newpass if newpass else crypt.randpass()

        ldap = Ldap()
        if not ldap.reset_pwd(uid, newpass, oldpass):
            return self.fail()

        mail = Mail()
        mail.to(uid, newpass)

        return self.succ() if oldpass else self.succ(newpass)
Ejemplo n.º 20
0
    def get(self):
        _filters = []
        for key in [arg for arg in request.args.keys() if arg != "_"]:
            if not hasattr(Domain, key):
                raise ExceptionEx("查询字段%s不存在" % key)

            _filters.append(
                or_(*[
                    getattr(Domain, key).like("%" + arg + "%")
                    for arg in request.args.getlist(key)
                ]))

        return self.succ(Domain.select(_filters=_filters))
Ejemplo n.º 21
0
    def post(self):
        submit = self.request()
        submit["uid"] = session.get_uid()
        submit["apply_time"] = datetime.now()
        if Leave.check_overlap(submit):
            raise ExceptionEx("起止时间不能与已提交申请重叠,"
                              "可在请假审批中修改已提交的申请")

        leave = Leave.add(submit, auto_commit=False)
        Mail().to(leave)

        db.session.commit()
        return self.succ()
Ejemplo n.º 22
0
    def add(name, type, parent_id=0):
        query = Ref.query \
            .filter(Ref.type == type) \
            .filter(Ref.name == name) \
            .filter(Ref.parent_id == parent_id)

        if query.filter(Ref.is_del != True).count():
            raise ExceptionEx("该分类已存在")

        if query.filter(Ref.is_del).count():
            ref = query.filter(Ref.is_del).one()
            ref.is_del = False
        else:
            db.session.add(Ref(name, type, parent_id))
        db.session.commit()
Ejemplo n.º 23
0
    def put(self, aid):
        submit = self.request()
        submit["id"] = aid
        if submit.__contains__("content"):
            submit["content"] = json.dumps(submit["content"])

        access = Access.edit(submit, auto_commit=False)

        if submit["status"] == ACCESS.APPROVAL:
            mail = Mail()
            if not mail.to(access):
                raise ExceptionEx("邮件发送失败")

        db.session.commit()
        return self.succ()
Ejemplo n.º 24
0
    def add(_dict):

        if ProjectSchedule.query \
                .filter(ProjectSchedule.type == _dict["type"]) \
                .filter(ProjectSchedule.project_id == _dict["project_id"]).count():
            raise ExceptionEx("该阶段已添加")

        _dict["begin_time_create"] = _dict["begin_time"]
        _dict["end_time_create"] = _dict["end_time"]

        schedule = ProjectSchedule(_dict)

        db.session.add(schedule)
        db.session.commit()
        return True
Ejemplo n.º 25
0
    def add(cls, _dicts, auto_commit=True):
        query = Category.query \
            .filter(Category.parent_id == _dicts["parent_id"]) \
            .filter(Category.name == _dicts["name"])

        if query.filter(Category.is_del == False).count():
            raise ExceptionEx("分类%s已经存在" % _dicts["name"])

        if query.filter(Category.is_del == True).count():
            category = query.one()
            category.is_del = False
        else:
            db.session.add(Category(_dicts))

        db.session.commit()
        return True
Ejemplo n.º 26
0
    def to(self, l):
        try:
            uids = [l.approval_uid] + l.copy_to_uid.split(",")
            to = [User.get(uid)["mail"] for uid in uids]

            sub = u"请假申请 申请人:%s 申请时间:%s 编号:%d" % (
                l.uid, l.apply_time.strftime("%Y-%m-%d"), l.id)

            self.send(to,
                      sub,
                      "/templates/leave/approval.html",
                      "mail.leave.tpl.html",
                      leave=l,
                      leave_type=Ref.map(LEAVE.TYPE)[int(l.type_id)])
        except Exception, e:
            log.exception(e)
            raise ExceptionEx("邮件发送失败,请重试!")
Ejemplo n.º 27
0
    def edit(id, submit):
        approval = ReleaseApproval.query.filter(
            ReleaseApproval.release_id == id,
            ReleaseApproval.type == submit["type"])

        if approval.count():
            raise ExceptionEx("%s 已审批" % submit["type"])
        _approval = ReleaseApproval(submit)
        _approval.release_id = id

        release = Release.query.filter(Release.id == id).one()

        if _approval.status == RELEASE.FAIL or len(release.approvals) == 2:
            release.is_finished = True

        db.session.add(_approval)
        db.session.commit()
        return True
Ejemplo n.º 28
0
    def __init__(self, _dict):
        self.name = _dict["name"]
        self.type = _dict["type"]
        databases = [d for d in _dict["database"].split("|") if d != ""]
        tables = [t for t in _dict["table"].split("|") if t != ""]
        if len(databases) != len(tables):
            raise ExceptionEx("表格式错误")

        def format_database(database, table):
            _database = {"name": database.strip()}

            def format_tables(table):
                return [{"name": t.strip()} for t in table.split(",")]

            _database["table"] = [t for t in format_tables(table)]
            return _database

        _dict["database"] = [format_database(databases[i], tables[i]) for i in range(0, len(databases))]

        self.databases = [Database.to_cls(ReleaseDatabase, t) for t in _dict["database"]]
Ejemplo n.º 29
0
    def delete(self, obj, lead_times):
        try:
            for lead_time in lead_times:
                try:
                    _id = "_".join([
                        obj.__class__.__name__,
                        str(obj.id),
                        str(lead_time.days)
                    ])
                    BaseSms.remove(self, _id)
                    BaseMail.remove(self, _id)
                except JobLookupError, e:
                    traceback.print_exc()
                    log.exception(e)
                    continue

        except Exception, e:
            traceback.print_exc()
            log.exception(e)
            raise ExceptionEx("删除邮件或短信提示失败!")
Ejemplo n.º 30
0
    def post(self):
        submit = self.request()

        if not submit.__contains__("create_time"):
            submit["create_time"] = datetime.now()
        else:
            submit["create_time"] = datetime.strptime(submit["create_time"], "%Y-%m-%d")

        beg_time = (submit["create_time"] - timedelta(days=submit["create_time"].weekday())).replace(hour=0, minute=0,
                                                                                                     second=0)
        end_time = (submit["create_time"] + timedelta(days=6 - submit["create_time"].weekday())).replace(hour=23,
                                                                                                         minute=59,
                                                                                                         second=59)

        if Report.query.filter(Report.create_time.between(beg_time, end_time)) \
                .filter(Report.team_id == submit["team_id"]).count():
            raise ExceptionEx("本周计划已添加")

        Report.add(submit)
        return self.succ()