Пример #1
0
    def set_coupon(self):
        """
        创建/编辑/删除优惠券
        """
        if not is_admin():
            return AuthorityError('无权限')
        data = parameter_required(('costarttime', "coendtime", "cosubtration", "colimitnum")
                                  if not request.json.get('delete') else('coid',))
        if data.get('codownline'):
            codownline = data.get('codownline')
        else:
            codownline = 0
        costarttime = data.get('costarttime')
        coendtime = data.get('coendtime')
        if costarttime:
            start_time = datetime.datetime.strptime(costarttime, "%Y-%m-%d %H:%M:%S")
        else:
            start_time = datetime.datetime.now()
        if coendtime:
            end_time = datetime.datetime.strptime(coendtime, "%Y-%m-%d %H:%M:%S")
        else:
            end_time = datetime.datetime.now()
        co_dict = {
            'COstarttime': costarttime,
            'COendtime': coendtime,
            'COdownline': codownline,
            'COlimitnum': data.get('colimitnum'),
            'COsubtration': Decimal(str(data.get('cosubtration') or 0)),
            'COgetnum': 0
        }
        coid = data.get('coid')
        with db.auto_commit():
            if not coid:
                """新增"""
                if end_time < start_time or datetime.datetime.now() > start_time:
                    return TimeError()
                co_dict['COid'] = str(uuid.uuid1())
                co_dict["COstatus"] = 501
                co_instance = Coupon.create(co_dict)
                msg = '添加成功'

                # 添加优惠券到期时的定时任务
                add_async_task(func=change_coupon_status, start_time=end_time,
                               func_args=(co_dict['COid'],), conn_id='end_coupon{}'.format(co_dict['COid']))
            else:
                """修改/删除"""
                co_instance = Coupon.query.filter(Coupon.COid == coid).first_('未找到该优惠券信息')
                cancel_async_task(conn_id='end_coupon{}'.format(co_instance.COid))  # 取消已有定时任务
                if data.get('delete'):
                    co_instance.update({'isdelete': 1})
                    msg = '删除成功'
                else:
                    if not (end_time > start_time >= datetime.datetime.now()):
                        raise TimeError('结束时间需大于开始时间,开始时间需大于当前时间')
                    co_instance.update(co_dict, null='not')
                    msg = '编辑成功'

                    # 重新添加优惠券到期时的定时任务
                    add_async_task(func=change_coupon_status, start_time=end_time,
                                   func_args=(co_instance.COid,), conn_id='end_coupon{}'.format(co_instance.COid))
            db.session.add(co_instance)
        return Success(message=msg)
Пример #2
0
    def add_or_update_consultation(self):
        data = parameter_required()
        doid = getattr(request, 'user').id
        conid = data.get('conid')
        constarttime, conendtime, conlimit, constatus = data.get('constarttime'), data.get('conendtime'), \
                                                        data.get('conlimit'), data.get('constatus')

        constarttime = self._check_time(constarttime)
        conendtime = self._check_time(conendtime)
        now = datetime.now()
        if constarttime and constarttime < now:
            raise ParamsError('开始时间不能小于当前时间')
        if constarttime and conendtime and constarttime > conendtime:
            raise ParamsError('结束时间不能小于开始时间')

        if conlimit:
            try:
                conlimit = int(str(conlimit))
                if conlimit < 0:
                    raise ParamsError('限制人数只能为正整数')
            except:
                raise ParamsError('限制人数只能为正整数')

        if constatus:
            try:
                constatus = ConsultationStatus(int(str(constatus))).value
            except:
                raise ParamsError('状态修改参数异常')

        with db.auto_commit():
            if conid:
                con = Consultation.query.filter(
                    Consultation.CONid == conid,
                    Consultation.isdelete == 0).first()
                current_app.logger.info('get doctor {} '.format(con))
                # 优先判断删除
                if data.get('delete'):
                    if not con:
                        raise ParamsError('医生已删除')
                    current_app.logger.info('删除会诊 {}'.format(conid))
                    con.isdelete = 1
                    db.session.add(con)
                    cancel_async_task(conn_id='change_consultation{}'.format(
                        conid))  # 取消已有定时任务
                    return Success('删除成功', data=conid)

                # 执行update
                if con:
                    cancel_async_task(conn_id='change_consultation{}'.format(
                        conid))  # 取消已有定时任务
                    #  只能修改这个4个字段
                    update_dict = {}
                    if constarttime:
                        update_dict['CONstartTime'] = constarttime
                    if conendtime:
                        update_dict['CONendTime'] = conendtime
                    if constatus:
                        update_dict['CONstatus'] = constatus
                    if conlimit:
                        update_dict['CONlimit'] = conlimit
                    con.update(update_dict)
                    current_app.logger.info('更新会诊信息 {}'.format(conid))
                    db.session.add(con)
                    # 到开始时间更改状态, 除手动关闭外
                    if constatus != ConsultationStatus.finish.value:
                        add_async_task(
                            func=change_consultation_status,
                            start_time=constarttime,
                            func_args=(conid, ),
                            conn_id='change_consultation{}'.format(conid))
                    return Success('更新成功', data=conid)
            # 添加
            data = parameter_required({
                'constarttime': '开始时间',
                'conlimit': '限制人数'
            })

            conid = str(uuid.uuid1())
            doctor = Doctor.query.filter(Doctor.DOid == doid,
                                         Doctor.isdelete == 0).first_('医生已删除')
            dep = Departments.query.filter(
                Departments.DEid == doctor.DEid,
                Departments.isdelete == 0).first_('科室已删除')
            con = Consultation.create({
                'CONid': conid,
                'DOid': doid,
                'CONstartTime': constarttime,
                'CONendTime': conendtime,
                'CONlimit': conlimit,
                'CONnote': data.get('connote'),
                'DOname': doctor.DOname,
                'DOtel': doctor.DOtel,
                'DOtitle': doctor.DOtitle,
                'DOdetails': doctor.DOdetails,
                'DOwxid': doctor.DOwxid,
                'DOskilledIn': doctor.DOskilledIn,
                'DEname': dep.DEname,
                'DEid': dep.DEid,
            })

            current_app.logger.info('创建会诊 {}'.format(doid))
            db.session.add(con)
            # 到开始时间更改状态
            add_async_task(func=change_consultation_status,
                           start_time=constarttime,
                           func_args=(conid, ),
                           conn_id='change_consultation{}'.format(conid))
        return Success('创建会诊成功', data=conid)
Пример #3
0
    def create(self):
        data = parameter_required()
        usid = getattr(request, 'user').id
        ucid = data.get('ucid')
        prid = data.get('prid')
        omnum = data.get('omnum', 1)
        uaid = data.get('uaid')
        smid = data.get('smid')
        clid = data.get('clid')
        omtype = data.get('omtype')
        wallet_payment = True if str(
            data.get('wallet_payment')) == '1' else False

        omid = str(uuid.uuid1())

        with db.auto_commit():

            now = datetime.now()

            user = User.query.filter(User.USid == usid,
                                     User.isdelete == 0).first_('token过期, 请刷新')
            if omtype == OrderMainType.product.value:
                ua = UserAddress.query.filter(
                    UserAddress.UAid == uaid, UserAddress.USid == usid,
                    UserAddress.isdelete == 0).first_('地址已删除')
                apname, acname, aaname = db.session.query(
                    AddressProvince.APname, AddressCity.ACname,
                    AddressArea.AAname).filter(
                        AddressArea.AAid == ua.AAid,
                        AddressCity.ACid == AddressArea.ACid,
                        AddressProvince.APid == AddressCity.APid,
                    ).first()
                omrecvaddress = '{}{}{}{}'.format(apname, acname, aaname,
                                                  ua.UAtext)
            else:
                ua = None
                omrecvaddress = None

            uc = None
            if ucid:
                # 优惠券是否可用
                uc = CouponUser.query.filter(
                    CouponUser.UCid == ucid, CouponUser.isdelete == 0,
                    CouponUser.COstarttime <= now, CouponUser.COendtime >= now,
                    CouponUser.UCalreadyuse ==
                    CouponUserStatus.not_use.value).first_('优惠券已使用')
            # usecoupon = False
            try:
                omnum = int(omnum)
                if omnum <= 0:
                    raise ParamsError('{} 需要是正整数'.format('商品数量'))
            except:
                raise ParamsError('{}需要是整数'.format('商品数量'))

            opayno = wx_pay.nonce_str
            try:
                omtype = OrderMainType(int(str(omtype))).value
            except:
                raise ParamsError('订单创建异常')

            if omtype == OrderMainType.product.value:
                body, truemount, omintegralpayed = self._create_product_order(
                    prid, omid, omnum, user, opayno, ua, omrecvaddress, uc)
            elif omtype == OrderMainType.setmeal.value:
                omintegralpayed = 0
                if smid == "1":
                    omnum = 1
                elif smid == "2":
                    pass
                else:
                    setmeal = Setmeal.query.filter(
                        Setmeal.SMid == smid, Setmeal.isdelete == 0).first()
                    omnum = setmeal.SMnum
                body, truemount = self._create_setmeal_order(
                    smid, clid, omid, user, uc, omnum, opayno, wallet_payment)
            else:
                raise ParamsError('订单创建异常')

        from ..extensions.tasks import auto_cancle_order
        # auto_cancle_order.apply_async(args=(omid,), countdown=30 * 60, expires=40 * 60, )
        # todo 修改自动取消为30 minute
        add_async_task(func=auto_cancle_order,
                       start_time=now + timedelta(minutes=30),
                       func_args=(omid, ))
        # # 生成支付信息
        # body = product.PRtitle
        openid = user.USopenid

        # todo 修改支付参数获取
        if not truemount:
            pay_type = OrderPayType.integral.value
            pay_args = 'integralpay'
            self._over_ordermain(omid)
        elif not omintegralpayed:
            if wallet_payment and omtype == OrderMainType.setmeal.value:
                if truemount > user.USbalance:
                    raise StatusError('用户余额不足: {}'.format(user.USbalance))
                self._wallet_trade_setmeal(user, truemount, omid)
                pay_args = 'wallet_payment'
                pay_type = OrderPayType.wallet.value
            else:
                pay_args = self._pay_detail(opayno,
                                            float(truemount),
                                            body,
                                            openid=openid)
                # pay_args = 'wxpay'
                pay_type = OrderPayType.wx.value
        else:
            pay_args = self._pay_detail(opayno,
                                        float(truemount),
                                        body,
                                        openid=openid)
            # pay_args = 'wxpay'
            pay_type = OrderPayType.mix.value

        response = {'paytype': pay_type, 'args': pay_args}
        return Success('下单成功', data=response)
Пример #4
0
 def set_activity(self):
     """管理员 添加/编辑活动"""
     data = request.json
     acstarttime, acnumber = data.get('acstarttime'), data.get('acnumber')
     acid = data.get('acid')
     time_now = datetime.now()
     if acstarttime and not validate_datetime(acstarttime):
         raise ParamsError('活动时间格式错误')
     acstarttime = datetime.strptime(
         acstarttime, format_for_web_second) if acstarttime else None
     if acstarttime and acstarttime <= time_now:
         raise ParamsError('活动时间应大于当前时间')
     if acnumber and (not str(acnumber).isdigit() or int(acnumber) == 0):
         raise ParamsError('活动人数应为大于0的整数')
     required_dict = {
         'acname': '活动名称',
         'acbanner': '活动图片',
         'acorganizer': '举办人',
         'acstarttime': '活动时间',
         'aclocation': '活动地点',
         'acdetail': '活动介绍',
         'acnumber': '活动人数'
     }
     ac_dict = {
         'ACname': data.get('acname'),
         'ACbanner': data.get('acbanner'),
         'ACorganizer': data.get('acorganizer'),
         'ACstartTime': acstarttime,
         'AClocation': data.get('aclocation'),
         'ACdetail': data.get('acdetail'),
         'ACnumber': acnumber
     }
     with db.auto_commit():
         if not acid:
             if Activity.query.filter(
                     Activity.isdelete == false(),
                     Activity.ACname == data.get('acname'),
                     Activity.ACstartTime == acstarttime).first():
                 raise ParamsError('您已添加过 {} 活动'.format(data.get('acname')))
             parameter_required(required_dict, datafrom=data)
             ac_dict['ACid'] = str(uuid.uuid1())
             ac_dict['ADid'] = getattr(request, 'user').id
             ac_dict['ACstatus'] = ActivityStatus.ready.value
             activity = Activity.create(ac_dict)
             msg = '添加成功'
             # 添加异步任务
             add_async_task(func=change_activity_status,
                            start_time=acstarttime,
                            func_args=(ac_dict['ACid'], ),
                            conn_id='start_activity{}'.format(
                                ac_dict['ACid']))
         else:
             activity = Activity.query.filter(
                 Activity.isdelete == false(),
                 Activity.ACid == acid).first_('活动不存在')
             self._can_activity_edit(activity)
             # 取消已有的异步任务
             cancel_async_task(
                 conn_id='start_activity{}'.format(activity.ACid))
             if data.get('delete'):
                 activity.update({'isdelete': True})
                 msg = '删除成功'
             elif data.get('close'):
                 activity.update({'ACstatus': ActivityStatus.close.value})
                 msg = '活动关闭成功'
             else:
                 parameter_required(required_dict, datafrom=data)
                 # 重新添加异步任务
                 add_async_task(func=change_activity_status,
                                start_time=acstarttime,
                                func_args=(activity.ACid, ),
                                conn_id='start_activity{}'.format(
                                    activity.ACid))
                 ac_dict['ACstatus'] = ActivityStatus.ready.value
                 activity.update(ac_dict)
                 msg = '更新成功'
         db.session.add(activity)
         return Success(message=msg, data={'acid': activity.ACid})
Пример #5
0
    def set_course(self):
        """
        课程排班
        """
        data = parameter_required(
            ('clid', 'costarttime', 'coendtime', 'conum'))
        coid = data.get('coid')
        classes = Classes.query.filter(
            Classes.CLid == data.get('clid')).first_("未找到课程信息,请联系管理员")
        doctor = Doctor.query.filter(Doctor.DOid == request.user.id,
                                     Doctor.isdelete == 0).first()
        # 时间控制
        start_time = datetime.datetime.strptime(data.get('costarttime'),
                                                "%Y-%m-%d %H:%M:%S")
        end_time = datetime.datetime.strptime(data.get('coendtime'),
                                              "%Y-%m-%d %H:%M:%S")
        if not (end_time > start_time > datetime.datetime.now()):
            raise ParamsError('课程结束时间要大于开始时间, 开始时间要大于当前时间')
        if start_time.date() != end_time.date():
            return {
                "status": 405,
                "status_code": 405301,
                "message": "课程开始结束时间需要同一天"
            }
        co_dict = {
            "CLid": data.get("clid"),
            "CLname": classes["CLname"],
            "DOid": request.user.id,
            "DOname": doctor["DOname"],
            "COstarttime": data.get("costarttime"),
            "COendtime": data.get("coendtime"),
            "COnum": data.get("conum"),
            "COstatus": 101
        }
        with db.auto_commit():
            if not coid:
                co_dict["COid"] = str(uuid.uuid1())
                co_instance = Course.create(co_dict)
                msg = "创建成功"

                # 添加开始异步任务
                add_async_task(func=change_course_status,
                               start_time=start_time,
                               func_args=(co_dict["COid"], ),
                               conn_id='start_course{}'.format(
                                   co_dict["COid"]))
                # 添加结束异步任务
                add_async_task(func=change_course_status,
                               start_time=end_time,
                               func_args=(co_dict["COid"], True),
                               conn_id='end_course{}'.format(co_dict["COid"]))
            else:
                # 判断课程排班状态和已报名人数,已开始/已结束或者存在报名人员不可修改
                course = Course.query.filter(Course.COid == coid).first()
                if course["COstatus"] != 101:
                    return AuthorityError("无权限")
                subscribe = Subscribe.query.filter(
                    Subscribe.COid == coid).all()
                if subscribe:
                    return AuthorityError("已有人报名,不可修改")
                co_instance = Course.query.filter(
                    Course.COid == coid).first_('未找到该课程排班信息')
                co_instance.update(co_dict, null='not')
                msg = '编辑成功'

                cancel_async_task(conn_id='start_course{}'.format(
                    co_instance.COid))  # 取消已有的开始时间异步任务
                cancel_async_task(conn_id='end_course{}'.format(
                    co_instance.COid))  # 取消已有的结束时间异步任务
                # 重新添加开始异步任务
                add_async_task(func=change_course_status,
                               start_time=start_time,
                               func_args=(co_instance.COid, ),
                               conn_id='start_course{}'.format(
                                   co_instance.COid))
                # 重新添加结束异步任务
                add_async_task(func=change_course_status,
                               start_time=end_time,
                               func_args=(co_instance.COid, True),
                               conn_id='end_course{}'.format(co_instance.COid))
            db.session.add(co_instance)
        return Success(message=msg, data={"coid": co_instance.COid})