def get_context_data(self, **kwargs): category = kwargs.get('category') srid_from = self.request.data.get( 'srid_from', None) or self.request.GET.get('srid_from', None) srid_to = self.request.data.get( 'srid_to', None) or self.request.GET.get('srid_to', None) if not srid_from: raise CustomException( constants.ERROR_FIELD_REQUIRED.format(name='変更前のSRID')) elif not srid_to: raise CustomException( constants.ERROR_FIELD_REQUIRED.format(name='変更後のSRID')) elif not common.is_digit(srid_from) or not common.is_digit(srid_to): raise CustomException( constants.ERROR_REQUIRED_DIGIT.format(name='SRID')) if category == constants.SRID_TRANSFORM_CATEGORY_POINT: lng = self.request.data.get('lng', None) or self.request.GET.get( 'lng', None) lat = self.request.data.get('lat', None) or self.request.GET.get( 'lat', None) lng, lat = biz.transform_point(lng, lat, srid_from=srid_from, srid_to=srid_to) return {'lng': lng, 'lat': lat} else: return {}
def generate_partner_order_data( company, partner, order_no, year, month, publish_date, salesperson, end_year=None, end_month=None, project_member=None, contract=None, ): if not end_year or not end_month: end_year = year end_month = month elif '%04d%02d' % (int(year), int(month)) > '%04d%02d' % (int(end_year), int(end_month)): # 終了年月は開始年月の前の場合エラーとする。 raise CustomException(constants.ERROR_DELETE_PROTECTED.format(year=end_year, month=end_month)) interval = (int(end_year) * 12 + int(end_month)) - (int(year) * 12 + int(month)) + 1 if contract is None: member = project_member.member contract = get_partner_member_contract(partner, member, year, month) heading = generate_partner_order_heading( company, partner, contract, year, month, publish_date, interval, salesperson, project_member=project_member, ) order = {'order_no': order_no} return { 'order': order, 'heading': heading, 'signature': common.get_signature(), }
def check_email_address(cls, mail_address): if not mail_address: return False if isinstance(mail_address, str): mail_list = [mail_address] elif isinstance(mail_address, (tuple, list)): mail_list = mail_address else: raise CustomException('有効なメールアドレスを入れてください。') for email in mail_list: try: validate_email(email) except ValidationError: raise CustomException('有効なメールアドレスを入れてください。') return True
def get_context_data(self, **kwargs): category = kwargs.get('category') if category == 'member': # メンバー契約 order = models.BpMemberOrder.objects.get(pk=kwargs.get('pk')) heading = order.bpmemberorderheading template_name1 = 'partner/member_order.html' template_name2 = 'partner/member_order_request.html' elif category == 'lump': # 一括契約 order = models.BpLumpOrder.objects.get(pk=kwargs.get('pk')) heading = order.bplumporderheading template_name1 = 'partner/lump_order.html' template_name2 = 'partner/lump_order_request.html' else: raise CustomException(constants.ERROR_UNKNOWN_CATEGORY) data = { 'order': order, 'heading': heading, 'signature': common.get_signature(), } return { 'html': [ render_to_string(template_name1, {'data': data}), render_to_string(template_name2, {'data': data}) ] }
def get_request_members_in_project(project, customer_order, year, month): """指定案件の指定注文書の中に、対象のメンバーを取得する。 :param project: 指定案件 :param customer_order: 指定注文書 :param year: 対象年 :param month: 対象月 :return: メンバーのリスト """ first_day = common.get_first_day_from_ym(year + month) last_day = common.get_last_day_by_month(first_day) if customer_order.projects.filter(is_deleted=False).count() > 1: # 一つの注文書に複数の案件がある場合 projects = customer_order.projects.filter(is_deleted=False) project_members = models.ProjectMember.objects.filter( project__in=projects, start_date__lte=last_day, end_date__gte=first_day, is_deleted=False, ) elif project.customerorder_set.filter(start_date__lte=last_day, end_date__gte=first_day, is_deleted=False).count() > 1: # 1つの案件に複数の注文書ある場合 raise CustomException(constants.ERROR_NOT_IMPLEMENTED) else: project_members = project.get_project_members_by_month(year, month) return project_members
def get_mail_connection(cls): try: with connection.cursor() as cursor: cursor.execute( "select value from mst_config where name = %s " " union all " "select value from mst_config where name = %s " " union all " "select value from mst_config where name = %s " " union all " "select value from mst_config where name = %s ", [ constants.CONFIG_ADMIN_EMAIL_SMTP_HOST, constants.CONFIG_ADMIN_EMAIL_SMTP_PORT, constants.CONFIG_ADMIN_EMAIL_ADDRESS, constants.CONFIG_ADMIN_EMAIL_PASSWORD ]) host, port, username, password = cursor.fetchall() backend = get_connection() backend.host = str(host[0]) backend.port = int(port[0]) backend.username = str(username[0]) backend.password = str(password[0]) return backend except Exception as ex: logger.error(unicode(ex)) logger.error(traceback.format_exc()) raise CustomException(unicode(ex))
def get_mail_group_by_code(cls, code): """指定コードによってメールグループを取得する。 :param code: :return: """ try: return MailGroup.objects.get(code=code) except ObjectDoesNotExist: raise CustomException( constants.ERROR_MAIL_GROUP_NOT_FOUND.format( name=common.get_choice_name_by_key( constants.CHOICE_MAIL_GROUP, code))) except MultipleObjectsReturned: raise CustomException( constants.ERROR_MAIL_GROUP_MULTI_FOUND.format( name=common.get_choice_name_by_key( constants.CHOICE_MAIL_GROUP, code)))
def get_member_salesperson_by_month(member, date): """社員の営業員を取得する :param member: :param date: :return: """ try: return models.SalespersonPeriod.objects.get( Q(end_date__gte=date) | Q(end_date__isnull=True), start_date__lte=date, member=member, ).salesperson except ObjectDoesNotExist: raise CustomException( constants.ERROR_NO_SALESPERSON.format(name=member)) except MultipleObjectsReturned: raise CustomException( constants.ERROR_MULTI_SALESPERSON.format(name=member))
def check_attachment(self): if self.attachment_list: qs = Attachment.objects.filter(is_deleted=False, uuid__in=self.attachment_list) self.attachment_list = [ AttachmentFile(path=item.path.path, filename=item.name) for item in qs ] for attachment in self.attachment_list: if not attachment.is_valid(): raise CustomException("ファイル「%s」が見つかりません。" % attachment)
def get_attendance(self, year, month): """指定された年月によって、該当するメンバーの勤怠情報を取得する。 :param year: 対象年 :param month: 対象月 :return: MemberAttendanceのインスタンス、または None """ try: return self.memberattendance_set.get(year=year, month=month, is_deleted=False) except ObjectDoesNotExist: raise CustomException(constants.ERROR_NO_ATTENDANCE)
def get_partner_member_contract(partner, member, year=None, month=None): """協力社員の契約を取得 :param partner: 協力会社 :param member: 社員 :param year: 対象年 :param month: 対象月 :return: """ try: first_day = common.get_first_day_from_ym(year + month) last_day = common.get_last_day_by_month(first_day) return models.BpContract.objects.get( Q(end_date__gte=first_day) | Q(end_date__isnull=True), start_date__lte=last_day, company=partner, member=member, ) except ObjectDoesNotExist: raise CustomException(constants.ERROR_NO_PARTNER_CONTRACT.format(name=member, company=partner)) except MultipleObjectsReturned: raise CustomException(constants.ERROR_MULTI_PARTNER_CONTRACT.format(name=member, company=partner))
def get(self, request, *args, **kwargs): file_uuid = kwargs.get('uuid') attachment = get_object_or_404(models.Attachment, uuid=file_uuid) path = attachment.path.path if os.path.exists(path): with open(path, 'rb') as f: stream = base64.b64encode(f.read()) return Response({ 'name': attachment.name, 'blob': stream, }) else: raise CustomException(constants.ERROR_FILE_NOT_FOUND)
def delete(self, using=None, keep_parents=False): for f in self._meta.get_fields(): if not isinstance(f, ForeignObjectRel): continue related_name = f.get_accessor_name() if not related_name or not hasattr(self, related_name): continue elif f.on_delete == models.DO_NOTHING: continue elif not hasattr(f.related_model, 'is_deleted'): continue qs = getattr(self, related_name).filter(is_deleted=False) if f.on_delete == models.PROTECT and qs.count() > 0: raise CustomException(constants.ERROR_DELETE_PROTECTED.format( name=f.related_model._meta.verbose_name, )) self.is_deleted = True self.deleted_dt = timezone.now() self.save(update_fields=('is_deleted', 'deleted_dt'))
def check_mail_title(self): if not self.mail_title: raise CustomException("メールの題名を設定してください。")
def check_attachment(self): if self.attachment_list: for attachment in self.attachment_list: if not os.path.exists(attachment): raise CustomException("ファイル「%s」が見つかりません。" % attachment)
def check_recipient(self): if not self.recipient_list: raise CustomException("宛先はありません。")
def send_email(self, user=None): try: self.check_recipient() self.check_cc_list() self.check_bcc_list() self.check_attachment() self.check_mail_title() mail_connection = self.get_mail_connection() if not self.sender: self.sender = mail_connection.username email = EmailMultiAlternativesWithEncoding( subject=self.mail_title, body=self.mail_body, from_email=self.sender, to=self.recipient_list, cc=self.cc_list, bcc=self.bcc_list, connection=mail_connection) # email.attach_alternative(self.mail_body, constants.MIME_TYPE_HTML) if self.is_encrypt is False: for attachment in [item for item in self.attachment_list]: if attachment.is_bytes(): email.attach(attachment.filename, attachment.content, constants.MIME_TYPE_ZIP) else: email.attach_file(attachment.path, constants.MIME_TYPE_STREAM) else: attachments = self.zip_attachments() if attachments: email.attach('%s.zip' % self.mail_title, attachments, constants.MIME_TYPE_ZIP) email.send() # パスワードを送信する。 self.send_password(mail_connection, user=user) log_format = "題名: %s; TO: %s; CC: %s; 送信完了。" logger.info( log_format % (self.mail_title, ','.join(self.recipient_list) if self.recipient_list else '', ','.join(self.cc_list) if self.cc_list else '')) if user: # 送信ログ if self.attachment_list: attachment_name = ",".join( [item.filename for item in self.attachment_list]) else: attachment_name = None EMailLogEntry.objects.create( user=user, sender=self.sender, recipient=",".join(self.recipient_list), cc=",".join(self.cc_list) if self.cc_list else None, bcc=",".join(self.bcc_list) if self.bcc_list else None, title=self.mail_title, body=self.mail_body, attachment=attachment_name, ) except subprocess.CalledProcessError as e: logger.error(e.output) logger.error(traceback.format_exc()) raise CustomException(str(e.output)) except Exception as ex: logger.error(ex) logger.error(traceback.format_exc()) raise CustomException(str(ex)) finally: # 一時ファイルを削除 for path in self.temp_files: if os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path)
def check_recipient(self): if not self.recipient_list: raise CustomException("宛先はありません。") return self.check_email_address(self.recipient_list)