def create(self, request, *args, **kwargs):
     data = request.data
     lang = request.GET.get('lang')
     data['createuser'] = request.user.id
     data['datasource'] = request.user.datasource.id
     try:
         with transaction.atomic():
             scheduleserializer = ScheduleCreateSerializer(data=data)
             if scheduleserializer.is_valid():
                 scheduleserializer.save()
             else:
                 raise InvestError(code=20071,
                                   msg='data有误_%s\n%s' %
                                   (scheduleserializer.error_messages,
                                    scheduleserializer.errors))
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(scheduleserializer.data,
                                                lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 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]))
Exemple #3
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]))
 def deleteAttachment(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 in [
                 instance.proj.takeUser, instance.proj.makeUser
         ]:
             pass
         else:
             raise InvestError(2009)
         with transaction.atomic():
             bucket = instance.attachmentbucket
             key = instance.attachment
             deleteqiniufile(bucket, key)
             instance.attachmentbucket = None
             instance.attachment = None
             instance.save()
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         MeetingBDSerializer(instance).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
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]))
 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]))
 def list(self, request, *args, **kwargs):
     try:
         page_size = request.GET.get('page_size')
         page_index = request.GET.get('page_index')
         if not page_size:
             page_size = 10
         if not page_index:
             page_index = 1
         queryset = self.filter_queryset(self.get_queryset())
         count = queryset.count()
         try:
             queryset = Paginator(queryset, page_size)
             queryset = queryset.page(page_index)
         except EmptyPage:
             return JSONResponse(SuccessResponse({'count': 0, 'data': []}))
         serializer = self.serializer_class(queryset, many=True)
         return JSONResponse(
             SuccessResponse({
                 'count': count,
                 'data': serializer.data
             }))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
Exemple #8
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]))
Exemple #9
0
 def audioFileTranslateToWord(self, request, *args, **kwargs):
     try:
         speaker_number = request.data.get('speaker_number', 0)
         uploaddata = request.FILES.get('file')
         dirpath = APILOG_PATH['audioTranslateFile']
         file_key = request.data.get('key')
         if not file_key:
             filetype = str(uploaddata.name).split('.')[-1]
             randomPrefix = datetime.datetime.now().strftime(
                 '%Y%m%d%H%M%S') + ''.join(
                     random.sample(string.ascii_lowercase, 6))
             file_key = randomPrefix + '.' + filetype
         if not os.path.exists(dirpath):
             os.makedirs(dirpath)
         file_Path = os.path.join(dirpath, file_key)
         with open(file_Path, 'wb+') as destination:
             for chunk in uploaddata.chunks():
                 destination.write(chunk)
         api = TransferRequestApi(upload_file_path=file_Path,
                                  speaker_number=speaker_number)
         task_id = api.all_api_request()
         instance = AudioTranslateTaskRecord(task_id=task_id,
                                             file_key=file_key,
                                             file_name=uploaddata.name,
                                             speaker_number=speaker_number,
                                             cretateUserId=request.user.id)
         instance.save()
         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]))
Exemple #10
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]))
 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]))
Exemple #12
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]))
 def list(self, request, *args, **kwargs):
     try:
         page_size = request.GET.get('page_size')
         page_index = request.GET.get('page_index')  # 从第一页开始
         if not page_size:
             page_size = 10
         if not page_index:
             page_index = 1
         queryset = self.filterqueryset(request, self.queryset)
         if request.user.has_perm('usersys.admin_getmongoprojremark'):
             queryset = queryset(datasource=request.user.datasource_id)
         else:
             queryset = queryset(createuser_id=request.user.id)
         try:
             count = queryset.count()
             queryset = Paginator(queryset, page_size)
             queryset = queryset.page(page_index)
         except EmptyPage:
             return JSONResponse(SuccessResponse({'count': 0, 'data': []}))
         serializer = self.serializer_class(queryset, many=True)
         return JSONResponse(
             SuccessResponse({
                 'count': count,
                 'data': serializer.data
             }))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
Exemple #14
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]))
    def destroy(self, request, *args, **kwargs):
        try:
            lang = request.GET.get('lang')
            instance = self.get_object()

            if request.user.has_perm('timeline.admin_deletelineremark'):
                pass
            elif request.user.has_perm('timeline.user_deletelineremark',
                                       instance):
                pass
            else:
                raise InvestError(code=2009, msg='没有权限')
            with transaction.atomic():
                instance.is_deleted = True
                instance.deleteduser = request.user
                instance.deletedtime = datetime.datetime.now()
                instance.save()
                return JSONResponse(
                    SuccessResponse(
                        returnDictChangeToLanguage(
                            TimeLineRemarkSerializer(instance).data, lang)))
        except InvestError as err:
            return JSONResponse(InvestErrorResponse(err))
        except Exception:
            catchexcption(request)
            return JSONResponse(
                ExceptionResponse(traceback.format_exc().split('\n')[-2]))
Exemple #16
0
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         com_qs = ProjectData.objects.filter(com_id=data['com_id'])
         if com_qs.count() > 0:
             com_name = data.get('com_name', None)
             if com_name and (u'...' in com_name or u'403' in com_name
                              or u'www.itjuzi.com' in com_name):
                 data.pop('com_name', None)
             serializer = self.serializer_class(com_qs.first(), data=data)
         else:
             serializer = self.serializer_class(data=data)
         if serializer.is_valid():
             proj = serializer.save()
             event_qs = MergeFinanceData.objects.filter(com_id=proj.com_id)
             if event_qs.count():
                 event_qs.update(com_cat_name=proj.com_cat_name)
                 event_qs.update(com_sub_cat_name=proj.com_sub_cat_name)
                 event_qs.update(com_addr=proj.com_addr)
         else:
             raise InvestError(4012,
                               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]))
Exemple #17
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]))
 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]))
 def list(self, request, *args, **kwargs):
     try:
         page_size = request.GET.get('page_size')
         page_index = request.GET.get('page_index')  # 从第一页开始
         if not page_size:
             page_size = 10
         if not page_index:
             page_index = 1
         queryset = self.filterqueryset(request, self.queryset)
         sort = request.GET.get('sort')
         if sort not in [
                 'True', 'true', True, 1, 'Yes', 'yes', 'YES', 'TRUE'
         ]:
             queryset = queryset.order_by('-date', )
         else:
             queryset = queryset.order_by('date', )
         try:
             count = queryset.count()
             queryset = Paginator(queryset, page_size)
             queryset = queryset.page(page_index)
         except EmptyPage:
             return JSONResponse(SuccessResponse({'count': 0, 'data': []}))
         serializer = self.serializer_class(queryset, many=True)
         return JSONResponse(
             SuccessResponse({
                 'count': count,
                 'data': serializer.data
             }))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 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]))
Exemple #21
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]))
 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]))
Exemple #23
0
 def list(self, request, *args, **kwargs):
     try:
         page_size = request.GET.get('page_size', 10)
         page_index = request.GET.get('page_index', 1)  # 从第一页开始
         queryset = self.filterqueryset(request, self.queryset)
         com_addr = request.GET.get('com_addr')
         finance_date = request.GET.get('finance_date')
         if finance_date:
             finance_date_list = finance_date.split(',')
             filters = Q(date__startswith=finance_date)
             for finance_date in finance_date_list:
                 filters = filters | Q(date__startswith=finance_date)
             comid_QS = MergeFinanceData.objects.all().filter(
                 filters).values_list('com_id').distinct('com_id')
             queryset = queryset.filter(com_id__in=comid_QS)
         if com_addr:
             com_addr = com_addr.split(',')
             if '其他' in com_addr:
                 queryset = queryset.filter(
                     Q(com_addr__nin=ChinaList) | Q(com_addr__in=com_addr))
             else:
                 queryset = queryset(Q(com_addr__in=com_addr))
         sortfield = request.GET.get('sort')
         if sortfield:
             queryset = queryset.order_by(sortfield)
         else:
             queryset = queryset.order_by('-id')
         count = queryset.count()
         if count == 0:
             if request.GET.get('com_name', None):
                 searchuser_id = None
                 if not request.user.is_anonymous:
                     searchuser_id = request.user.id
                 saveCompanySearchName(request.GET.get('com_name'),
                                       searchuser_id)
         try:
             queryset = Paginator(queryset, page_size)
             queryset = queryset.page(page_index)
         except EmptyPage:
             return JSONResponse(SuccessResponse({'count': 0, 'data': []}))
         serializer = self.serializer_class(queryset, many=True)
         return JSONResponse(
             SuccessResponse({
                 'count': count,
                 'data': serializer.data
             }))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 def update(self, request, *args, **kwargs):
     try:
         id = request.GET.get('id')
         instance = self.queryset.get(id=ObjectId(id))
         proj = ProjectData.objects(com_id=instance.com_id).first()
         instance.update(com_cat_name=proj.com_cat_name)
         instance.update(com_sub_cat_name=proj.com_sub_cat_name)
         instance.update(com_addr=proj.com_addr)
         return JSONResponse(SuccessResponse(True))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         serializer = self.serializer_class(data=data)
         if serializer.is_valid():
             serializer.save()
         else:
             raise InvestError(2001, msg=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]))
Exemple #26
0
def sendSmscode(request):
    try :
        source = request.META['HTTP_SOURCE']
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']
        if ip:
            if not checkIPAddressCanPass(ip):
                raise InvestError(code=3004,msg='单位时间内只能获取三次验证码')
        else:
            raise InvestError(code=3003)
        destination = request.data.get('mobile')
        areacode = request.data.get('areacode')
        now = datetime.datetime.now()
        start = now - datetime.timedelta(minutes=1)
        if MobileAuthCode.objects.filter(createTime__gt=start).filter(mobile=destination,is_deleted=False).exists():
            raise InvestError(code=3004)
        mobilecode = MobileAuthCode(mobile=destination)
        mobilecode.save()
        try:
            datasource = DataSource.objects.get(id=source)
        except DataSource.DoesNotExist:
            raise InvestError(8888, msg='未知来源码,请联系工作人员', detail='datasource不合法')
        varsdict = {'code': mobilecode.code, 'time': '30'}
        if areacode in [u'86', '86', 86, None]:
            projectsign = SMSCODE_projectsign.get(str(source), {}).get('in')
            if projectsign:
                response = xsendSms(destination, projectsign, varsdict)
            else:
                raise InvestError(30011, msg='短信发送失败', detail='没有建立相应短信模板')
        else:
            projectsign = SMSCODE_projectsign.get(str(source), {}).get('out')
            if projectsign:
                response = xsendInternationalsms('+%s'%areacode + destination, projectsign, varsdict)
            else:
                raise InvestError(30012, msg='短信发送失败', detail='没有建立相应短信模板')
        success = response.get('status',None)
        if success:
            response['smstoken'] = mobilecode.token
        else:
            raise InvestError(code=30011,msg='短信发送失败', detail=response)
        return JSONResponse(SuccessResponse(response))
    except InvestError as err:
        return JSONResponse(InvestErrorResponse(err))
    except Exception:
        catchexcption(request)
        return JSONResponse(ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 def update(self, request, *args, **kwargs):
     try:
         data = request.data
         lang = request.GET.get('lang')
         instance = self.get_object()
         oldmanager = instance.manager
         data.pop('createuser', None)
         data.pop('datasource', None)
         if request.user.has_perm('BD.manageOrgBD'):
             pass
         elif request.user.has_perm('BD.user_manageOrgBD', instance):
             data = {
                 'bd_status':
                 data.get('bd_status', instance.bd_status_id),
                 'isimportant':
                 bool(data.get('isimportant', instance.isimportant))
             }
         else:
             raise InvestError(2009)
         with transaction.atomic():
             orgBD = OrgBDCreateSerializer(instance, data=data)
             if orgBD.is_valid():
                 neworgBD = orgBD.save()
                 oldmanager_id = data.get('manager', None)
                 if oldmanager_id and oldmanager_id != oldmanager.id:
                     add_perm('BD.user_manageOrgBD', neworgBD.manager,
                              neworgBD)
                     rem_perm('BD.user_manageOrgBD', oldmanager, neworgBD)
                     if request.user != neworgBD.manager:
                         sendmessage_orgBDMessage(
                             neworgBD,
                             receiver=neworgBD.manager,
                             types=['app', 'wenmsg', 'sms'],
                             sender=request.user)
             else:
                 raise InvestError(5004,
                                   msg='机构BD修改失败——%s' %
                                   orgBD.error_messages)
             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]))
 def create(self, request, *args, **kwargs):
     try:
         data = request.data
         lang = request.GET.get('lang')
         data['createuser'] = request.user.id
         data['datasource'] = request.user.datasource.id
         if request.user.has_perm('BD.manageMeetBD'):
             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_addMeetBD'):
                     pass
                 elif request.user in [
                         projinstance.takeUser, projinstance.makeUser
                 ]:
                     pass
                 else:
                     raise InvestError(2009)
             else:
                 raise InvestError(2009)
         with transaction.atomic():
             meetBD = MeetingBDCreateSerializer(data=data)
             if meetBD.is_valid():
                 newMeetBD = meetBD.save()
                 if newMeetBD.manager:
                     add_perm('BD.user_manageMeetBD', newMeetBD.manager,
                              newMeetBD)
             else:
                 raise InvestError(5005,
                                   msg='会议BD创建失败——%s' %
                                   meetBD.error_messages)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         MeetingBDSerializer(newMeetBD).data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
 def create(self, request, *args, **kwargs):
     data = request.data
     lang = request.GET.get('lang')
     timelineid = data.get('timeline', None)
     if timelineid:
         line = self.get_timeline(timelineid)
         if request.user.has_perm('timeline.admin_addlineremark'):
             pass
         elif request.user.has_perm(
                 'timeline.user_getline', line) or request.user in [
                     line.proj.takeUser, line.proj.makeUser
                 ]:
             pass
         else:
             raise InvestError(code=2009)
     else:
         raise InvestError(code=20072)
     data['createuser'] = request.user.id
     data['datasource'] = request.user.datasource.id
     try:
         with transaction.atomic():
             timeLineremarkserializer = TimeLineRemarkSerializer(data=data)
             if timeLineremarkserializer.is_valid():
                 timeLineremark = timeLineremarkserializer.save()
             else:
                 raise InvestError(code=20071,
                                   msg='data有误_%s\n%s' %
                                   (timeLineremarkserializer.error_messages,
                                    timeLineremarkserializer.errors))
             if timeLineremark.createuser:
                 add_perm('timeline.user_getlineremark',
                          timeLineremark.createuser, timeLineremark)
                 add_perm('timeline.user_changelineremark',
                          timeLineremark.createuser, timeLineremark)
                 add_perm('timeline.user_deletelineremark',
                          timeLineremark.createuser, timeLineremark)
             return JSONResponse(
                 SuccessResponse(
                     returnDictChangeToLanguage(
                         timeLineremarkserializer.data, lang)))
     except InvestError as err:
         return JSONResponse(InvestErrorResponse(err))
     except Exception:
         catchexcption(request)
         return JSONResponse(
             ExceptionResponse(traceback.format_exc().split('\n')[-2]))
Exemple #30
0
 def retrieve(self, request, *args, **kwargs):
     try:
         lang = request.GET.get('lang')
         instance = self.get_object()
         if request.user.has_perm('dataroom.admin_getdataroom'):
             serializerclass = DataroomSerializer
         elif request.user.has_perm('dataroom.user_getdataroom', instance):
             serializerclass = DataroomSerializer
         else:
             raise InvestError(code=2009)
         serializer = serializerclass(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]))