예제 #1
0
 def destroy(self, request, *args, **kwargs):
     try:
         timelineidlist = request.data.get('timelines')
         timelinelist = []
         lang = request.GET.get('lang')
         if not timelineidlist or not  isinstance(timelineidlist,list):
             raise InvestError(code=20071, msg='except a not null list')
         with transaction.atomic():
             for timelineid in timelineidlist:
                 instance = self.get_object(timelineid)
                 if not (request.user.has_perm('timeline.admin_deleteline') or request.user.has_perm(
                         'timeline.user_deleteline', instance)):
                     raise InvestError(2009, msg='没有相应权限')
                 for link in ['timeline_transationStatus','timeline_remarks']:
                     if link in []:
                         manager = getattr(instance, link, None)
                         if not manager:
                             continue
                         # one to one
                         if isinstance(manager, models.Model):
                             if hasattr(manager, 'is_deleted') and not manager.is_deleted:
                                 raise InvestError(code=2010,msg=u'{} 上有关联数据'.format(link))
                         else:
                             try:
                                 manager.model._meta.get_field('is_deleted')
                                 if manager.all().filter(is_deleted=False).count():
                                     raise InvestError(code=2010,msg=u'{} 上有关联数据'.format(link))
                             except FieldDoesNotExist:
                                 if manager.all().count():
                                     raise InvestError(code=2010,msg=u'{} 上有关联数据'.format(link))
                     else:
                         manager = getattr(instance, link, None)
                         if not manager:
                             continue
                         # one to one
                         if isinstance(manager, models.Model):
                             if hasattr(manager, 'is_deleted') and not manager.is_deleted:
                                 manager.is_deleted = True
                                 manager.save()
                         else:
                             try:
                                 manager.model._meta.get_field('is_deleted')
                                 if manager.all().filter(is_deleted=False).count():
                                     manager.all().update(is_deleted=True)
                             except FieldDoesNotExist:
                                 pass
                 instance.is_deleted = True
                 instance.deleteduser = request.user
                 instance.deletedtime = datetime.datetime.now()
                 instance.save()
                 instance.timeline_transationStatus.all().update(is_deleted=True)
                 instance.timeline_remarks.all().update(is_deleted=True)
                 cache_delete_key(self.redis_key + '_%s' % instance.id)
                 timelinelist.append(TimeLineSerializer(instance).data)
             return JSONResponse(SuccessResponse(returnListChangeToLanguage(timelinelist, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #2
0
 def update(self, request, *args, **kwargs):
     try:
         orgremark = self.get_object()
         lang = request.GET.get('lang')
         if request.user.has_perm('org.admin_changeorgremark'):
             pass
         elif request.user.has_perm('org.user_changeorgremark', orgremark):
             pass
         else:
             raise InvestError(code=2009)
         data = request.data
         data['lastmodifyuser'] = request.user.id
         data['lastmodifytime'] = datetime.datetime.now()
         data['datasource'] = request.user.datasource.id
         with transaction.atomic():
             orgserializer = OrgRemarkDetailSerializer(orgremark, data=data)
             if orgserializer.is_valid():
                 org = orgserializer.save()
             else:
                 raise InvestError(code=20071,
                                   msg='data有误_%s' % orgserializer.errors)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         OrgRemarkDetailSerializer(org).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #3
0
def getMobilePhoneAddress(request):
    try:
        tokenkey = request.META.get('HTTP_TOKEN')
        checkrequesttoken(tokenkey)
        mobile = request.GET.get('mobile', None)
        if not mobile:
            raise InvestError(20072, msg='手机号码不能为空')
        response = requests.get(
            'http://apis.juhe.cn/mobile/get?phone={}&dtype=&key=f439062c59bb86db8156446aa9737c72'
            .format(mobile)).content
        response = json.loads(response.decode())
        if isinstance(response, dict):
            error_code = response.get('error_code')
            if error_code == 0:
                result = response.get('result', {})
            else:
                raise InvestError(20071, msg=response.get('reason', None))
        else:
            raise InvestError(20071, msg=response)
        return JSONResponse(SuccessResponse(result))
    except InvestError as err:
        return JSONResponse(InvestErrorResponse(err))
    except Exception:
        catchexcption(request)
        return JSONResponse(
            ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #4
0
def fetch_token():
    params = {
        'grant_type': 'client_credentials',
        'client_id': baiduaip_appkey,
        'client_secret': baiduaip_secretkey
    }
    post_data = urlencode(params).encode('utf-8')
    req = Request('https://aip.baidubce.com/oauth/2.0/token', post_data)
    try:
        f = urlopen(req, timeout=10)
        result_str = f.read()
    except URLError as err:
        raise InvestError(9999, msg='网络错误', detail=str(err))
    result_str = result_str.decode()
    result = json.loads(result_str)
    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'brain_all_scope' in result['scope'].split(' '):
            raise InvestError(20071,
                              msg='获取百度ocr token失败',
                              detail='please ensure has check the ability')
        return result['access_token']
    else:
        raise InvestError(20071,
                          msg='获取百度ocr token失败',
                          detail='client_id/client_secret参数错误')
예제 #5
0
 def _token_available(request, *args, **kwargs):
     try:
         tokenkey = request.META.get('HTTP_TOKEN')
         if tokenkey:
             try:
                 token = MyToken.objects.get(key=tokenkey,
                                             is_deleted=False)
             except MyToken.DoesNotExist:
                 return JSONResponse(
                     InvestErrorResponse(
                         InvestError(3000, msg='token不存在')))
             else:
                 if token.timeout():
                     return JSONResponse(
                         InvestErrorResponse(
                             InvestError(3000, msg='token过期')))
                 if token.user.is_deleted:
                     return JSONResponse(
                         InvestErrorResponse(
                             InvestError(3000, msg='用户不存在')))
                 request.user = token.user
                 return func(request, *args, **kwargs)
         else:
             return JSONResponse(
                 InvestErrorResponse(InvestError(3000, msg='token缺失')))
     except Exception as exc:
         return JSONResponse(
             InvestErrorResponse(InvestError(code=3000, msg=repr(exc))))
예제 #6
0
 def get_object(self, pk=None):
     if pk:
         obj = read_from_cache(self.redis_key + '_%s' % pk)
         if not obj:
             try:
                 obj = self.get_queryset().get(id=pk)
             except organization.DoesNotExist:
                 raise InvestError(code=5002)
             else:
                 write_to_cache(self.redis_key + '_%s' % pk, obj)
     else:
         lookup_url_kwarg = 'pk'
         obj = read_from_cache(self.redis_key +
                               '_%s' % self.kwargs[lookup_url_kwarg])
         if not obj:
             try:
                 obj = self.get_queryset().get(
                     id=self.kwargs[lookup_url_kwarg])
             except organization.DoesNotExist:
                 raise InvestError(code=5002)
             else:
                 write_to_cache(
                     self.redis_key + '_%s' % self.kwargs[lookup_url_kwarg],
                     obj)
     if obj.datasource != self.request.user.datasource:
         raise InvestError(code=8888, msg='资源非同源')
     return obj
예제 #7
0
def getcurrencyreat(request):
    try:
        checkrequesttoken(request)
        tcur = request.GET.get('tcur', None)
        scur = request.GET.get('scur', None)
        if not tcur or not scur:
            raise InvestError(20072)
        response = requests.get(
            'https://sapi.k780.com/?app=finance.rate&scur=%s&tcur=%s&appkey=18220&sign=9b97118c7cf61df11c736c79ce94dcf9'
            % (scur, tcur)).content
        response = json.loads(response)
        if isinstance(response, dict):
            success = response.get('success', False)
            if success in ['1', True]:
                result = response.get('result', {})
            else:
                raise InvestError(code=2007, msg=response.get('msg', None))
        else:
            raise InvestError(code=2007, msg=response)
        return JSONResponse(SuccessResponse(result))
    except InvestError as err:
        return JSONResponse(InvestErrorResponse(err))
    except Exception:
        catchexcption(request)
        return JSONResponse(
            ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #8
0
 def update(self, request, *args, **kwargs):
     try:
         id = request.GET.get('id')
         instance = self.queryset.get(id=ObjectId(id))
         if instance.createuser_id == request.user.id:
             pass
         else:
             raise InvestError(2009, msg='修改项目公司备注信息失败')
         data = request.data
         data.pop('createuser_id', None)
         data.pop('datasource', None)
         serializer = self.serializer_class(instance, data=data)
         if serializer.is_valid():
             serializer.save()
         else:
             raise InvestError(4014,
                               msg='修改项目公司备注信息失败',
                               detail=serializer.error_messages)
         return JSONResponse(SuccessResponse(serializer.data))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #9
0
 def update(self, request, *args, **kwargs):
     try:
         data = request.data
         traderid = data.get('trader', None)
         investorid = data.get('investor', None)
         projid = data.get('proj', None)
         isClose = data.get('isClose',False)
         if isClose in ['True', 1, '1', 'true', 'TRUE']:
             isClose = True
         else:
             isClose = False
         if not data or not traderid or not investorid or not projid:
             raise InvestError(code=20071)
         dataroomquery = self.get_queryset().filter(isPublic=False, proj_id=projid, investor_id=investorid,trader_id=traderid)
         if not dataroomquery.exists():
             raise InvestError(code=6002)
         if request.user.has_perm('dataroom.admin_closedataroom'):
             pass
         elif request.user.has_perm('dataroom.user_closedataroom',dataroomquery.get(user_id=investorid)):
             pass
         else:
             raise InvestError(code=2009)
         dataroomquery.update(isClose=isClose,closeDate=datetime.datetime.now())
         return JSONResponse(
             SuccessResponse(returnListChangeToLanguage(DataroomSerializer(dataroomquery, many=True).data)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #10
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     if self.proj.projstatus_id < 4:
         raise InvestError(5003, msg='项目尚未终审发布')
     if self.createdtime is None:
         self.createdtime = datetime.datetime.now()
     if not self.datasource or self.datasource != self.proj.datasource:
         raise InvestError(code=8888, msg='项目收藏datasource与项目不符')
     if not self.pk:  #交易师不能自己主动删除推荐,再次推荐同一个项目时删除旧的添加新的(暂定)
         # deletedata = {'is_deleted':True,'deleteduser':self.createuser.id,'deletedtime':datetime.datetime.now()}
         favoriteProject.objects.filter(
             proj=self.proj,
             user=self.user,
             trader=self.trader,
             favoritetype=self.favoritetype,
             is_deleted=False,
             datasource=self.datasource,
             createuser=self.createuser).update(
                 is_deleted=True,
                 deleteduser=self.createuser,
                 deletedtime=datetime.datetime.now())
     super(favoriteProject, self).save(force_insert, force_update, using,
                                       update_fields)
예제 #11
0
 def update(self, request, *args, **kwargs):
     try:
         remark = self.get_object()
         lang = request.GET.get('lang')
         if request.user.has_perm('timeline.admin_changelineremark'):
             pass
         elif request.user.has_perm('timeline.user_changelineremark',
                                    remark):
             pass
         else:
             raise InvestError(code=2009)
         data = request.data
         data['lastmodifyuser'] = request.user.id
         data['lastmodifytime'] = datetime.datetime.now()
         with transaction.atomic():
             serializer = TimeLineRemarkSerializer(remark, data=data)
             if serializer.is_valid():
                 newremark = serializer.save()
             else:
                 raise InvestError(
                     code=20071,
                     msg='data有误_%s\n%s' %
                     (serializer.error_messages, serializer.errors))
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         TimeLineRemarkSerializer(newremark).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #12
0
 def retrieve(self, request, *args, **kwargs):
     try:
         lang = request.GET.get('lang')
         instance = self.get_object()
         if request.user.has_perm('BD.manageMeetBD'):
             pass
         elif request.user.has_perm('BD.user_manageMeetBD', instance):
             pass
         elif request.user.has_perm('BD.user_getMeetBD'):
             if request.user not in [
                     instance.proj.takeUser, instance.proj.makeUser
             ]:
                 raise InvestError(2009)
         else:
             raise InvestError(2009)
         serializer = self.serializer_class(instance)
         return JSONResponse(
             SuccessResponse(
                 returnDictChangeToLanguage(serializer.data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #13
0
 def save(self,
          force_insert=False,
          validate=True,
          clean=True,
          write_concern=None,
          cascade=None,
          cascade_kwargs=None,
          _refs=None,
          save_condition=None,
          signal_kwargs=None,
          **kwargs):
     if self.investormerge == 1:
         if len(MergeFinanceData.objects.filter(
                 invse_id=self.invse_id)) > 0:
             raise InvestError(8001)
     elif self.investormerge == 2:
         if len(MergeFinanceData.objects.filter(
                 merger_id=self.merger_id)) > 0:
             raise InvestError(8001)
     else:
         raise InvestError(8001, msg='未知的类型')
     super(MergeFinanceData,
           self).save(force_insert, validate, clean, write_concern, cascade,
                      cascade_kwargs, _refs, save_condition, signal_kwargs,
                      **kwargs)
예제 #14
0
 def update(self, request, *args, **kwargs):
     try:
         lang = request.GET.get('lang')
         instance = self.get_object()
         if request.user.has_perm('msg.admin_manageSchedule'):
             pass
         elif request.user == instance.createuser:
             pass
         else:
             raise InvestError(code=2009)
         data = request.data
         data['lastmodifyuser'] = request.user.id
         data['lastmodifytime'] = datetime.datetime.now()
         data.pop('scheduledtime')  #客户端不能修改日程时间
         with transaction.atomic():
             serializer = ScheduleCreateSerializer(instance, data=data)
             if serializer.is_valid():
                 newinstance = serializer.save()
             else:
                 raise InvestError(code=20071,
                                   msg='data有误_%s' % serializer.errors)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         ScheduleSerializer(newinstance).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #15
0
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         lang = request.GET.get('lang')
         dataroomid = data.get('dataroom', None)
         if dataroomid:
             dataroomobj = self.get_dataroom(dataroomid)
             if dataroomobj.isClose:
                 raise InvestError(7012)
             elif request.user.has_perm('dataroom.admin_adddataroom'):
                 pass
             elif request.user.has_perm('dataroom.user_adddataroomfile', dataroomobj):
                 pass
             else:
                 raise InvestError(code=2009)
         else:
             raise InvestError(code=20072)
         data['createuser'] = request.user.id
         # createdtime = data.pop('createdtime', None)
         # if createdtime not in ['None', None, u'None', 'none']:
         #     data['createdtime'] = datetime.datetime.strptime(createdtime.encode('utf-8')[0:19], "%Y-%m-%d %H:%M:%S")
         # else:
         #     data['createdtime'] = datetime.datetime.now()
         # lastmodifytime = data.pop('lastmodifytime', None)
         # if lastmodifytime not in ['None', None, u'None', 'none']:
         #     data['lastmodifytime'] = datetime.datetime.strptime(lastmodifytime.encode('utf-8')[0:19], "%Y-%m-%d %H:%M:%S")
         data['datasource'] = request.user.datasource.id
         if data.get('parent', None):
             parentfile = self.get_object(data['parent'])
             if parentfile.isFile:
                 raise InvestError(7007, msg='非文件夹类型')
             if self.checkDirectoryIsShadow(parentfile):
                 raise InvestError(7009, msg='不能把文件f复制到复制体文件夹内')
             if parentfile.dataroom_id != dataroomid:
                 raise InvestError(7011, msg='dataroom下没有该目录')
         if data.get('isShadow', None):
             if data['shadowdirectory'] is None:
                 raise InvestError(2007,msg='\"shadowdirectory\" 不能为空')
             shadowdirectory = self.get_object(data['shadowdirectory'])
             if shadowdirectory.isShadow:
                 raise InvestError(7009,msg='影子目录不能复制')
             if shadowdirectory.dataroom_id == dataroomid:
                 raise InvestError(7011,msg='文件复制不能再同一个dataroom下')
         with transaction.atomic():
             directoryorfileserializer = DataroomdirectoryorfileCreateSerializer(data=data)
             if directoryorfileserializer.is_valid():
                 directoryorfile = directoryorfileserializer.save()
             else:
                 raise InvestError(code=20071, msg='data有误_%s' % directoryorfileserializer.errors)
             if directoryorfile.parent is not None:
                 destquery = directoryorfile.parent.asparent_directories.exclude(pk=directoryorfile.pk).filter(is_deleted=False,orderNO__gte=directoryorfile.orderNO)
                 if destquery.exists():
                     destquery.update(orderNO = F('orderNO') + 1)
             sendmessage_dataroomfileupdate(directoryorfile,directoryorfile.dataroom.investor,['sms','email','webmsg','app'],sender=request.user)
             return JSONResponse(SuccessResponse(returnDictChangeToLanguage(directoryorfileserializer.data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #16
0
 def update(self, request, *args, **kwargs):
     try:
         data = request.data
         token = data.get('token')
         signature = data.get('signature')
         if not checkSubhookKey(token, signature):
             raise InvestError(8888, msg='subhook验证未通过')
         send_id = data.get('send_id')
         data['isSend'] = True
         try:
             emailgroupsend = self.queryset.get(send_id=send_id)
         except emailgroupsendlist.DoesNotExist:
             return JSONResponse(SuccessResponse(None))
         with transaction.atomic():
             emailserializer = Emailgroupsendlistserializer(emailgroupsend,
                                                            data=data)
             if emailserializer.is_valid():
                 newemailgroupsend = emailserializer.save()
                 newemailgroupsend.isRead = True
                 newemailgroupsend.readtime = datetime.datetime.now()
                 newemailgroupsend.save()
             else:
                 raise InvestError(code=20071,
                                   msg='data有误_%s' % emailserializer.errors)
             return JSONResponse(SuccessResponse(None))
     except Exception:
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #17
0
 def save(self, *args, **kwargs):
     if not self.datasource:
         raise InvestError(code=8888, msg='datasource有误')
     if self.datasource != self.user.datasource or self.datasource != self.friend.datasource:
         raise InvestError(code=8888, msg='user.datasource不匹配')
     if self.user == self.friend:
         raise InvestError(2016)
     if not self.accepttime and self.isaccept:
         self.accepttime = datetime.datetime.now()
     if not self.pk:
         if UserFriendship.objects.filter(
                 Q(user=self.user, friend=self.friend, is_deleted=False)
                 | Q(friend=self.user, user=self.friend, is_deleted=False)
         ).exists():
             raise InvestError(2017)
     if not self.createdtime:
         self.createdtime = datetime.datetime.now()
     if self.pk:
         if self.isaccept is False:
             self.is_deleted = True
     if self.is_deleted is False:
         if self.isaccept and self.friendallowgetfavoriteproj:
             assign_perm('usersys.user_getfavorite', self.user, self.friend)
         else:
             remove_perm('usersys.user_getfavorite', self.user, self.friend)
         if self.isaccept and self.userallowgetfavoriteproj:
             assign_perm('usersys.user_getfavorite', self.friend, self.user)
         else:
             remove_perm('usersys.user_getfavorite', self.friend, self.user)
     super(UserFriendship, self).save(*args, **kwargs)
예제 #18
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     if not self.datasource:
         raise InvestError(code=8888, msg='机构datasource不能空')
     if self.industry:
         if self.industry.datasource != self.datasource_id:
             raise InvestError(8888)
     if self.pk:
         oldorg = organization.objects.get(pk=self.pk)
         if self.orgnameC:
             if organization.objects.exclude(pk=self.pk).filter(
                     is_deleted=False,
                     orgnameC=self.orgnameC,
                     datasource=self.datasource).exists():
                 raise InvestError(code=5001, msg='同名机构已存在,修改')
         if self.is_deleted and oldorg.createuser:
             remove_perm('org.user_getorg', oldorg.createuser, self)
             remove_perm('org.user_changeorg', oldorg.createuser, self)
             remove_perm('org.user_deleteorg', oldorg.createuser, self)
     else:
         if self.orgnameC:
             if organization.objects.filter(
                     is_deleted=False,
                     orgnameC=self.orgnameC,
                     datasource=self.datasource).exists():
                 raise InvestError(code=5001, msg='同名机构已存在,新增')
     super(organization, self).save(force_insert, force_update, using,
                                    update_fields)
예제 #19
0
 def save(self,
          force_insert=False,
          force_update=False,
          using=None,
          update_fields=None):
     if self.isFile:
         try:
             if self.pk:
                 dataroomdirectoryorfile.objects.exclude(pk=self.pk).get(
                     is_deleted=False, key=self.key)
             else:
                 dataroomdirectoryorfile.objects.get(is_deleted=False,
                                                     key=self.key)
         except dataroomdirectoryorfile.DoesNotExist:
             pass
         else:
             raise InvestError(code=7001, msg='相同key文件已存在')
     if self.pk is None:
         if self.dataroom.isClose or self.dataroom.is_deleted:
             raise InvestError(7012, msg='dataroom已关闭/删除,无法添加文件/目录')
     if self.parent:
         if self.parent.isFile:
             raise InvestError(7007, msg='非目录结构不能存储文件')
     if self.filename is None:
         raise InvestError(2007, msg='名称不能为空')
     super(dataroomdirectoryorfile, self).save(force_insert, force_update,
                                               using, update_fields)
예제 #20
0
 def create(self, request, *args, **kwargs):
     try:
         with transaction.atomic():
             data = request.data
             data['datasource'] = request.user.datasource_id
             if not data.get('nameC') and data.get('nameE'):
                 data['nameC'] = data['nameE']
             elif not data.get('nameE') and data.get('nameC'):
                 data['nameE'] = data['nameC']
             elif not data.get('nameC') and not data.get('nameE'):
                 raise InvestError(20071,
                                   msg='新建标签失败,名称不能为空',
                                   detail='新建标签名称不能为空')
             serializer = self.serializer_class(data=data)
             if serializer.is_valid():
                 instance = serializer.save()
             else:
                 raise InvestError(20071,
                                   msg='%s' % serializer.error_messages)
             return JSONResponse(
                 SuccessResponse(self.serializer_class(instance).data))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #21
0
 def destroy(self, request, *args, **kwargs):
     try:
         data = request.data
         traderid = data.get('trader', None)
         investorid = data.get('investor', None)
         projid = data.get('proj', None)
         if not data or not traderid or not investorid:
             raise InvestError(code=20071)
         dataroomquery = self.get_queryset().filter(isPublic=False, proj_id=projid, investor_id=investorid, trader_id=traderid)
         if not dataroomquery.exists():
             raise InvestError(code=6002)
         if request.user.has_perm('dataroom.admin_deletedataroom'):
             pass
         elif request.user.has_perm('dataroom.user_deletedataroom',dataroomquery.get(investor_id=investorid)):
             pass
         else:
             raise InvestError(code=2009)
         with transaction.atomic():
             for instance in dataroomquery:
                 instance.dataroom_directories.all().update(is_deleted=True,deletedtime=datetime.datetime.now())
                 for fileOrDirectory in instance.dataroom_directories.all():
                     if fileOrDirectory.isFile and fileOrDirectory.key:
                         deleteqiniufile(fileOrDirectory.bucket, fileOrDirectory.key)
                 instance.is_deleted = True
                 instance.deleteduser = request.user
                 instance.deletedtime = datetime.datetime.now()
                 instance.save()
             return JSONResponse(SuccessResponse(returnListChangeToLanguage(DataroomSerializer(dataroomquery,many=True).data)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #22
0
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         bdinstance = OrgBD.objects.get(id=int(data['orgBD']))
         if request.user.has_perm('BD.manageOrgBD'):
             pass
         elif request.user.has_perm('BD.user_manageOrgBD', bdinstance):
             pass
         else:
             raise InvestError(2009)
         lang = request.GET.get('lang')
         data['createuser'] = request.user.id
         data['datasource'] = request.user.datasource.id
         with transaction.atomic():
             commentinstance = OrgBDCommentsCreateSerializer(data=data)
             if commentinstance.is_valid():
                 newcommentinstance = commentinstance.save()
             else:
                 raise InvestError(5004,
                                   msg='创建机构BDcomments失败--%s' %
                                   commentinstance.error_messages)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         OrgBDCommentsSerializer(newcommentinstance).data,
                         lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #23
0
 def list(self, request, *args, **kwargs):
     try:
         lang = request.GET.get('lang',None)
         dataroomid = request.GET.get('dataroom',None)
         queryset = self.filter_queryset(self.get_queryset())
         if dataroomid and isinstance(dataroomid,(int,str,unicode)):
             dataroomobj = self.get_dataroom(dataroomid)
             if dataroomobj.isPublic:
                 pass
             elif request.user.has_perm('dataroom.admin_getdataroom'):
                 pass
             elif request.user.has_perm('dataroom.user_getdataroom', dataroomobj):
                 pass
             else:
                 raise InvestError(code=2009)
         else:
             raise InvestError(code=20072,msg='dataroom 不能空')
         count = queryset.count()
         serializer = DataroomdirectoryorfileSerializer(queryset, many=True)
         return JSONResponse(SuccessResponse({'count':count,'data':returnListChangeToLanguage(serializer.data,lang)}))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #24
0
 def get_object(self, pk=None):
     if pk:
         obj = read_from_cache(self.redis_key + '_%s' % pk)
         if not obj:
             try:
                 obj = self.Model.objects.get(id=pk, is_deleted=False)
             except self.Model.DoesNotExist:
                 raise InvestError(
                     code=6002,
                     msg='timeline with this "%s" is not exist' % pk)
             else:
                 write_to_cache(self.redis_key + '_%s' % pk, obj)
     else:
         lookup_url_kwarg = 'pk'
         obj = read_from_cache(self.redis_key +
                               '_%s' % self.kwargs[lookup_url_kwarg])
         if not obj:
             try:
                 obj = self.Model.objects.get(
                     id=self.kwargs[lookup_url_kwarg], is_deleted=False)
             except self.Model.DoesNotExist:
                 raise InvestError(
                     code=6002,
                     msg='timeline with this "%s" is not exist' %
                     self.kwargs[lookup_url_kwarg])
             else:
                 write_to_cache(
                     self.redis_key + '_%s' % self.kwargs[lookup_url_kwarg],
                     obj)
     if obj.datasource != self.request.user.datasource:
         raise InvestError(code=8888)
     return obj
예제 #25
0
 def get_dataroom(self,id):
     if self.request.user.is_anonymous:
         raise InvestError(code=8889)
     try:
         dataroomobj = dataroom.objects.get(id=id,is_deleted=False,datasource=self.request.user.datasource)
     except dataroom.DoesNotExist:
         raise InvestError(code=7002)
     return dataroomobj
예제 #26
0
def bigfileupload(request):
    """
    分片上传
    """
    try:
        bucket_name = request.GET.get('bucket')
        if bucket_name not in qiniu_url.keys():
            raise InvestError(2020, msg='bucket error')
        data_dict = request.FILES
        uploaddata = None
        for key in data_dict.keys():
            uploaddata = data_dict[key]
        q = qiniu.Auth(ACCESS_KEY, SECRET_KEY)
        filetype = str(uploaddata.name).split('.')[-1]
        key = datetime.datetime.now().strftime('%Y%m%d%H%M%s') + ''.join(
            random.sample(string.ascii_lowercase, 6)) + '.' + filetype
        if filetype != 'pdf' and bucket_name not in ['image', u'image']:
            saveas_key = qiniu.urlsafe_base64_encode(
                'file:%s' % (key.split('.')[0] + '.pdf'))
            persistentOps = fops + '|saveas/' + saveas_key
            policy = {
                'persistentOps': persistentOps,
                # 'persistentPipeline': pipeline,
                'deleteAfterDays': 1,
            }
        else:
            policy = None
        print key
        params = {'x:a': 'a'}
        mime_type = uploaddata.content_type
        token = q.upload_token(bucket_name, key, 3600, policy=policy)
        progress_handler = lambda progress, total: progress / total
        uploader = _Resume(token,
                           key,
                           uploaddata,
                           uploaddata.size,
                           params,
                           mime_type,
                           progress_handler,
                           upload_progress_recorder=MyUploadProgressRecorder(),
                           modify_time=None,
                           file_name=key)
        ret, info = uploader.upload()
        if info is not None:
            if info.status_code == 200:
                return_url = getUrlWithBucketAndKey(bucket_name, ret['key'])
            else:
                raise InvestError(2020, msg=str(info))
        else:
            raise InvestError(2020, msg=str(ret))
        if policy:
            key = key.split('.')[0] + '.pdf'
        return JSONResponse(SuccessResponse({'key': key, 'url': return_url}))
    except InvestError as err:
        return JSONResponse(InvestErrorResponse(err))
    except Exception:
        return JSONResponse(
            ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #27
0
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         lang = request.GET.get('lang')
         comments = data.get('comments', None)
         data['createuser'] = request.user.id
         data['datasource'] = request.user.datasource.id
         if request.user.has_perm('BD.manageOrgBD'):
             pass
         else:
             proj = data.get('proj', None)
             if proj:
                 projinstance = project.objects.get(
                     id=proj,
                     is_deleted=False,
                     datasource=request.user.datasource)
                 if request.user.has_perm('BD.user_addOrgBD'):
                     pass
                 elif request.user in [
                         projinstance.takeUser, projinstance.makeUser
                 ]:
                     pass
                 else:
                     raise InvestError(2009)
             else:
                 raise InvestError(2009)
         with transaction.atomic():
             orgBD = OrgBDCreateSerializer(data=data)
             if orgBD.is_valid():
                 neworgBD = orgBD.save()
                 if neworgBD.manager:
                     add_perm('BD.user_manageOrgBD', neworgBD.manager,
                              neworgBD)
             else:
                 raise InvestError(5004,
                                   msg='机构BD创建失败——%s' %
                                   orgBD.error_messages)
             if comments:
                 data['orgBD'] = neworgBD.id
                 commentinstance = OrgBDCommentsCreateSerializer(data=data)
                 if commentinstance.is_valid():
                     commentinstance.save()
             if request.user != neworgBD.manager:
                 sendmessage_orgBDMessage(neworgBD,
                                          receiver=neworgBD.manager,
                                          types=['app', 'webmsg', 'sms'],
                                          sender=request.user)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         OrgBDSerializer(neworgBD).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
예제 #28
0
 def save(self, *args, **kwargs):
     if not self.is_deleted:
         if not self.okr or self.okr.is_deleted:
             raise InvestError(20072, msg='okr字段 不能为空')
         if OKRResult.objects.exclude(pk=self.pk).filter(
                 is_deleted=False, okr=self.okr, krs=self.krs).exists():
             raise InvestError(20071, msg='该OKR已存在相同的关键结果')
     self.datasource = self.createuser.datasource
     return super(OKRResult, self).save(*args, **kwargs)
예제 #29
0
 def save(self, *args, **kwargs):
     self.datasource = self.user.datasource
     if self.user.datasource != self.proj.datasource:
         raise InvestError(code=8888,msg='项目用户datasource不合法')
     if not self.is_deleted:
         traders = projTraders.objects.exclude(pk=self.pk).filter(is_deleted=False, proj=self.proj, user=self.user, type=self.type)
         if traders.exists():
             raise InvestError(20071, msg='该交易师已存在一条相同记录了')
     super(projTraders, self).save(*args, **kwargs)
예제 #30
0
 def get_object(self):
     lookup_url_kwarg = 'pk'
     try:
         obj = dataroom.objects.get(id=self.kwargs[lookup_url_kwarg], is_deleted=False)
     except dataroom.DoesNotExist:
         raise InvestError(code=6002,msg='timeline with this "%s" is not exist' % self.kwargs[lookup_url_kwarg])
     if obj.datasource != self.request.user.datasource:
         raise InvestError(code=8888,msg='资源非同源')
     return obj