<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Entities.Mailing;
using Signum.Engine.Operations;
using Signum.Utilities;
using Signum.Engine.Maps;
using Signum.Engine.DynamicQuery;
using System.Reflection;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Engine.Basics;
using Signum.Entities.UserQueries;
using System.Net.Configuration;
using System.Globalization;
using System.Configuration;
using Signum.Engine.UserQueries;
using System.Linq.Expressions;
using Signum.Entities.Translation;
using Signum.Engine.Translation;
using System.Text.RegularExpressions;
using Signum.Entities.Basics;
using Signum.Engine.Templating;
using System.Net.Mail;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.Templating;
using Signum.Entities.Reflection;

namespace Signum.Engine.Mailing
{
    public static class EmailTemplateLogic
    {
        public static bool AvoidSynchronizeTokens = false;
        public static bool AvoidSynchronizeDefaultTemplates = true;

        public static EmailTemplateMessageEmbedded GetCultureMessage(this EmailTemplateEntity template, CultureInfo ci)
        {
            return template.Messages.SingleOrDefault(tm => tm.CultureInfo.ToCultureInfo() == ci);
        }
     
        static Expression<Func<SystemEmailEntity, IQueryable<EmailTemplateEntity>>> EmailTemplatesExpression =
            se => Database.Query<EmailTemplateEntity>().Where(et => et.SystemEmail == se);
        [ExpressionField]
        public static IQueryable<EmailTemplateEntity> EmailTemplates(this SystemEmailEntity se)
        {
            return EmailTemplatesExpression.Evaluate(se);
        }
        
        public static ResetLazy<Dictionary<Lite<EmailTemplateEntity>, EmailTemplateEntity>> EmailTemplatesLazy;
        public static ResetLazy<Dictionary<object, List<EmailTemplateEntity>>> TemplatesByQueryName;


        public static Polymorphic<Action<IAttachmentGeneratorEntity, FillAttachmentTokenContext>> FillAttachmentTokens =
           new Polymorphic<Action<IAttachmentGeneratorEntity, FillAttachmentTokenContext>>();

        public class FillAttachmentTokenContext
        {
            public QueryDescription QueryDescription;
            public Type ModelType;
            public List<QueryToken> QueryTokens;
        }

        public static Polymorphic<Func<IAttachmentGeneratorEntity, GenerateAttachmentContext, List<EmailAttachmentEmbedded>>> GenerateAttachment = 
            new Polymorphic<Func<IAttachmentGeneratorEntity, GenerateAttachmentContext, List<EmailAttachmentEmbedded>>>();

        public class GenerateAttachmentContext
        {
            public QueryDescription QueryDescription;
            public Type ModelType;
            public EmailTemplateEntity Template;
            public IEntity Entity;
            public ISystemEmail SystemEmail;
            public CultureInfo Culture;
            public Dictionary<QueryToken, ResultColumn> ResultColumns;
            public IEnumerable<ResultRow> CurrentRows;
        }


        public static Func<EmailTemplateEntity, Lite<Entity>, SmtpConfigurationEntity> GetSmtpConfiguration;

        public static void Start(SchemaBuilder sb, Func<EmailTemplateEntity, Lite<Entity>, SmtpConfigurationEntity> getSmtpConfiguration)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                CultureInfoLogic.AssertStarted(sb);
                TemplatingLogic.Start(sb);


                GetSmtpConfiguration = getSmtpConfiguration;

                sb.Include<EmailTemplateEntity>()
                    .WithQuery(() => t => new
                    {
                        Entity = t,
                        t.Id,
                        t.Name,
                        t.IsBodyHtml
                    });       

                EmailTemplatesLazy = sb.GlobalLazy(() => 
                Database.Query<EmailTemplateEntity>().ToDictionary(et => et.ToLite())
                , new InvalidateWith(typeof(EmailTemplateEntity)));
                
                TemplatesByQueryName = sb.GlobalLazy(() =>
                {
                    return EmailTemplatesLazy.Value.Values.SelectCatch(et => KVP.Create(et.Query.ToQueryName(), et)).GroupToDictionary();
                }, new InvalidateWith(typeof(EmailTemplateEntity)));
                
                SystemEmailLogic.Start(sb);
                EmailMasterTemplateLogic.Start(sb);
                
                sb.Schema.EntityEvents<EmailTemplateEntity>().PreSaving += new PreSavingEventHandler<EmailTemplateEntity>(EmailTemplate_PreSaving);
                sb.Schema.EntityEvents<EmailTemplateEntity>().Retrieved += EmailTemplateLogic_Retrieved;

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Text).StaticPropertyValidation +=
                    EmailTemplateMessageText_StaticPropertyValidation;

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Subject).StaticPropertyValidation +=
                    EmailTemplateMessageSubject_StaticPropertyValidation;<commit_msg>delete EmailTemplates when corresponding SystemEmail gets deleted<commit_after>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Entities.Mailing;
using Signum.Engine.Operations;
using Signum.Utilities;
using Signum.Engine.Maps;
using Signum.Engine.DynamicQuery;
using System.Reflection;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Engine.Basics;
using Signum.Entities.UserQueries;
using System.Net.Configuration;
using System.Globalization;
using System.Configuration;
using Signum.Engine.UserQueries;
using System.Linq.Expressions;
using Signum.Entities.Translation;
using Signum.Engine.Translation;
using System.Text.RegularExpressions;
using Signum.Entities.Basics;
using Signum.Engine.Templating;
using System.Net.Mail;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.Templating;
using Signum.Entities.Reflection;

namespace Signum.Engine.Mailing
{
    public static class EmailTemplateLogic
    {
        public static bool AvoidSynchronizeTokens = false;
        public static bool AvoidSynchronizeDefaultTemplates = true;

        public static EmailTemplateMessageEmbedded GetCultureMessage(this EmailTemplateEntity template, CultureInfo ci)
        {
            return template.Messages.SingleOrDefault(tm => tm.CultureInfo.ToCultureInfo() == ci);
        }
     
        static Expression<Func<SystemEmailEntity, IQueryable<EmailTemplateEntity>>> EmailTemplatesExpression =
            se => Database.Query<EmailTemplateEntity>().Where(et => et.SystemEmail == se);
        [ExpressionField]
        public static IQueryable<EmailTemplateEntity> EmailTemplates(this SystemEmailEntity se)
        {
            return EmailTemplatesExpression.Evaluate(se);
        }
        
        public static ResetLazy<Dictionary<Lite<EmailTemplateEntity>, EmailTemplateEntity>> EmailTemplatesLazy;
        public static ResetLazy<Dictionary<object, List<EmailTemplateEntity>>> TemplatesByQueryName;


        public static Polymorphic<Action<IAttachmentGeneratorEntity, FillAttachmentTokenContext>> FillAttachmentTokens =
           new Polymorphic<Action<IAttachmentGeneratorEntity, FillAttachmentTokenContext>>();

        public class FillAttachmentTokenContext
        {
            public QueryDescription QueryDescription;
            public Type ModelType;
            public List<QueryToken> QueryTokens;
        }

        public static Polymorphic<Func<IAttachmentGeneratorEntity, GenerateAttachmentContext, List<EmailAttachmentEmbedded>>> GenerateAttachment = 
            new Polymorphic<Func<IAttachmentGeneratorEntity, GenerateAttachmentContext, List<EmailAttachmentEmbedded>>>();

        public class GenerateAttachmentContext
        {
            public QueryDescription QueryDescription;
            public Type ModelType;
            public EmailTemplateEntity Template;
            public IEntity Entity;
            public ISystemEmail SystemEmail;
            public CultureInfo Culture;
            public Dictionary<QueryToken, ResultColumn> ResultColumns;
            public IEnumerable<ResultRow> CurrentRows;
        }


        public static Func<EmailTemplateEntity, Lite<Entity>, SmtpConfigurationEntity> GetSmtpConfiguration;

        public static void Start(SchemaBuilder sb, Func<EmailTemplateEntity, Lite<Entity>, SmtpConfigurationEntity> getSmtpConfiguration)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                CultureInfoLogic.AssertStarted(sb);
                TemplatingLogic.Start(sb);


                GetSmtpConfiguration = getSmtpConfiguration;

                sb.Include<EmailTemplateEntity>()
                    .WithQuery(() => t => new
                    {
                        Entity = t,
                        t.Id,
                        t.Name,
                        t.IsBodyHtml
                    });       

                EmailTemplatesLazy = sb.GlobalLazy(() => 
                Database.Query<EmailTemplateEntity>().ToDictionary(et => et.ToLite())
                , new InvalidateWith(typeof(EmailTemplateEntity)));
                
                TemplatesByQueryName = sb.GlobalLazy(() =>
                {
                    return EmailTemplatesLazy.Value.Values.SelectCatch(et => KVP.Create(et.Query.ToQueryName(), et)).GroupToDictionary();
                }, new InvalidateWith(typeof(EmailTemplateEntity)));
                
                SystemEmailLogic.Start(sb);
                EmailMasterTemplateLogic.Start(sb);
                
                sb.Schema.EntityEvents<EmailTemplateEntity>().PreSaving += new PreSavingEventHandler<EmailTemplateEntity>(EmailTemplate_PreSaving);
                sb.Schema.EntityEvents<EmailTemplateEntity>().Retrieved += EmailTemplateLogic_Retrieved;
                sb.Schema.Table<SystemEmailEntity>().PreDeleteSqlSync += e =>
                    Administrator.UnsafeDeletePreCommand(Database.Query<EmailTemplateEntity>()
                        .Where(a => a.SystemEmail.Is(e)));

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Text).StaticPropertyValidation +=
                    EmailTemplateMessageText_StaticPropertyValidation;

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Subject).StaticPropertyValidation +=
                    EmailTemplateMessageSubject_StaticPropertyValidation;
{'fraction_non_alphanumeric': 0.07648057336854017, 'fraction_numerical': 0.0, 'mean_word_length': 2.860575172915908, 'pattern_counts': {'":': 0, '<': 71, '<?xml version=': 0, '>': 95, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '251551', 'n_tokens_mistral': 2554, 'n_tokens_neox': 2497, 'n_words': 466}