예제 #1
0
        /*public async Task<ActionResult<TicketUser>> GetTicketUser(long id)
         * {
         *  using var context = new DevTicketDatabaseContext(DevTicketDatabaseContext.ops.dbOptions);
         *  var ticketUser = await context.TicketsUsers.FindAsync(id);
         *
         *  return ticketUser;
         * }*/

        public async Task <int> CreateTicketUser(TicketUser ticketUser)
        {
            using var context = new DevTicketDatabaseContext(DevTicketDatabaseContext.ops.dbOptions);

            context.TicketsUsers.Add(ticketUser);
            return(await context.SaveChangesAsync());
        }
예제 #2
0
        /// <summary>
        /// Ricrea il Token per l'utente indicato
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public Token TokenRegenerate(Int64 UserId)
        {
            if (UserId <= 0)
            {
                return(new Token());
            }

            TicketUser Usr = this.UserGet(UserId);

            if (Usr == null || Usr.Id <= 0)
            {
                return(new Token());
            }


            Token Tok = Manager.GetAll <Token>(tok => tok.User.Id == UserId).FirstOrDefault();

            if (Tok == null || Tok.Id <= 0)
            {
                return(new Token());
            }

            Tok.Code = System.Guid.NewGuid();
            Manager.SaveOrUpdate <Token>(Tok);

            return(Tok);
        }
예제 #3
0
        public async Task <int> PutTicketUser(TicketUser ticketUser)
        {
            using var context = new DevTicketDatabaseContext(DevTicketDatabaseContext.ops.dbOptions);

            context.Entry(ticketUser).State = EntityState.Modified;
            return(await context.SaveChangesAsync());
        }
예제 #4
0
        /// <summary>
        /// Crea un nuovo token
        /// </summary>
        /// <param name="UserId">Id Utente</param>
        /// <returns>Oggetto Token creato o vecchio Token</returns>
        public Token TokenCreate(Int64 UserId, Domain.Enums.TokenType Type)
        {
            if (UserId <= 0)
            {
                return(new Token());
            }

            TicketUser Usr = this.UserGet(UserId);

            if (Usr == null || Usr.Id <= 0)
            {
                return(new Token());
            }


            Token Tok = Manager.GetAll <Token>(tok => tok.User.Id == UserId).FirstOrDefault();

            //(from Token tok in Manager.GetIQ<Token>() where tok.User.Id == UserId select tok.Code).FirstOrDefault();

            if (Tok == null || Tok.Id <= 0)
            {
                Tok      = new Token(Usr, true);
                Tok.Type = Type;
                Manager.SaveOrUpdate <Token>(Tok);
            }

            return(Tok);
        }
예제 #5
0
        /// <summary>
        /// Crea un utente da una persona
        /// </summary>
        /// <param name="PersonId">Id Persona</param>
        /// <param name="Settings">Impostazioni</param>
        /// <returns>New User Id</returns>
        public Domain.TicketUser UserCreateFromPerson(
            Int32 PersonId,
            Domain.Enums.MailSettings Settings)
        {
            litePerson Person = Manager.GetLitePerson(PersonId);//Manager.Get<Person>(PersonId);

            if (Person == null)
            {
                return(null);
            }

            TicketUser User = new TicketUser();

            User.CreateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
            User.Person      = Person;
            User.Enabled     = true;
            User.MailChecked = false;
            //Viene messo a false, poichè NECESSITA comunque di registrazione e convalida via mail da pagine esterne.
            //VEDI: TokenValidate()

            Manager.SaveOrUpdate <TicketUser>(User);

            //Imposto i parametri globali per quell'utente, quando lo aggiungo come User nei Ticket...
            SettingsSetGlobalUser(User.Id, Settings, true, true);

            return(User);
        }
예제 #6
0
        /// <summary>
        /// Recupera un utente da una Person,
        /// SE non trova l'utente, lo crea da Person.
        /// </summary>
        /// <param name="PersonId">Id Person</param>
        /// <returns>Oggetto User</returns>
        public Int64 UserGetIdfromPerson(int PersonId)
        {
            if (PersonId <= 0)
            {
                return(-1);
            }

            Int64 UserId = (from TicketUser tu in Manager.GetIQ <Domain.TicketUser>()
                            where tu.Person != null &&
                            tu.Person.Id == PersonId
                            select tu.Id).FirstOrDefault();

            if (UserId > 0)
            {
                return(UserId);
            }
            else
            {
                TicketUser TkUser = this.UserGetfromPerson(PersonId);
                if (TkUser != null && TkUser.Id > 0)
                {
                    return(TkUser.Id);
                }
            }

            return(-1);
        }
예제 #7
0
        public async Task <ActionResult <bool> > Save([FromBody] VMs.Ticket ticket)
        {
            try
            {
                //Validation
                if (!context.Tickets
                    .Where(x => x.RowStatus == Data.enRowStatus.Active && x.Code == ticket.Code && x.Description == x.Description)
                    .Any())
                {
                    // TICKETS

                    var ticketId = context.Tickets
                                   .Max(x => x.Id);

                    var dataTicket = new Data.Ticket
                    {
                        Id            = ++ticketId,
                        Code          = ticket.Code,
                        Description   = ticket.Description,
                        UserId        = ticket.Owner.Id,
                        OpeningDate   = ticket.OpeningDate,
                        ClosingDate   = ticket.ClosingDate,
                        TypeInner     = (short)Enum.Parse(typeof(enType), ticket.Type),
                        StatusInner   = (short)Enum.Parse(typeof(enStatus), ticket.Status),
                        PriorityInner = (short)Enum.Parse(typeof(enPriority), ticket.Priority),
                        RowStatus     = enRowStatus.Active,
                        RowDate       = DateTime.Now,
                    };

                    context.Tickets.Add(dataTicket);

                    // TICKET USER

                    var idTicketUser = context.TicketUser
                                       .Max(x => x.Id);

                    var ticketUser = new TicketUser
                    {
                        Id        = ++idTicketUser,
                        UserId    = ticket.Owner.Id,
                        TicketId  = ticketId,
                        RowStatus = enRowStatus.Active,
                        RowDate   = DateTime.Now
                    };

                    context.TicketUser.Add(ticketUser);

                    await context.SaveChangesAsync();

                    return(OkResponse(true));
                }
                else
                {
                    throw new Exception("Ticket já cadastrado!");
                }
            }
            catch (Exception ex) { return(BadRequestResponse(ex)); }
            finally { context.Dispose(); }
        }
예제 #8
0
        //private bool MessageDraftUpdate(
        //    String HtmlMessage,
        //    String Preview,
        //    Int64 TicketId,
        //    Int64 MessageId,
        //    Int64 UserId)
        //{
        //    Message msg = Manager.Get<Message>(MessageId);
        //    TicketUser usr = Manager.Get<TicketUser>(UserId);

        //    if (
        //        usr != null ||
        //        msg == null ||
        //        msg.Ticket == null ||
        //        msg.Ticket.Id != TicketId ||
        //        msg.Creator == null ||
        //        msg.Creator.Id != usr.Id ||
        //        !msg.IsDraft ||
        //        msg.Deleted != BaseStatusDeleted.None)
        //        return false;

        //    msg.UpdateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
        //    msg.Text = HtmlMessage;
        //    msg.Preview = Preview;

        //    Manager.SaveOrUpdate<Message>(msg);



        //    return true;
        //}
        /// <summary>
        /// Dato un Ticket e l'utente recupera il relativo messaggio DRAFT.
        /// Nel caso non esista, viene creato.
        /// </summary>
        /// <param name="TicketId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        private Message MessageDraftGet(
            Ticket Ticket, TicketUser User,
            Domain.Enums.MessageUserType UserType = Domain.Enums.MessageUserType.Partecipant,
            Domain.Enums.MessageType MessageType  = Domain.Enums.MessageType.FeedBack
            )
        {
            //if(!Manager.IsInTransaction())
            //{
            //    Manager.BeginTransaction();
            //}


            Message msg = Manager.GetAll <Message>(m =>
                                                   m.IsDraft == true && m.Deleted == BaseStatusDeleted.None &&
                                                   m.Creator != null && m.Creator.Id == User.Id &&
                                                   m.Ticket != null && m.Ticket.Id == Ticket.Id).FirstOrDefault();

            if (msg == null)
            {
                //if (!Manager.IsInTransaction())
                //    Manager.BeginTransaction();

                msg = new Message();
                msg.CreateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
                msg.Creator      = User;
                msg.Action       = Domain.Enums.MessageActionType.normal;
                msg.Attachments  = new List <TicketFile>();
                msg.DisplayName  = User.DisplayName;
                msg.IsDraft      = true;
                msg.Preview      = "";
                msg.ShowRealName = true;
                msg.Type         = MessageType;
                msg.UserType     = UserType;
                msg.Visibility   = true;
                msg.Ticket       = Ticket;
                msg.ToStatus     = Ticket.Status;
                msg.ToCondition  = Ticket.Condition;

                msg.ToCategory = (from Assignment ass in Ticket.Assignemts
                                  where ass.AssignedCategory != null
                                  orderby ass.CreatedOn
                                  select ass.AssignedCategory).LastOrDefault()
                                 ?? Ticket.CreationCategory;


                Manager.SaveOrUpdate <Message>(msg);
            }
            else
            {
                Manager.Refresh <Message>(msg);
            }

            //Manager.Flush();

            return(msg);
        }
예제 #9
0
        public static liteUser UserConvetToLiteUser(TicketUser user)
        {
            liteUser usr = new liteUser();

            usr.Id      = user.Id;
            usr.Name    = user.Name;
            usr.Surname = user.Sname;
            usr.Person  = user.Person;
            return(usr);
        }
예제 #10
0
        public async Task <ActionResult <bool> > Save([FromBody] VMs.Comment comment)
        {
            try
            {
                var ticketUserID = -1;

                var tickerUser = await context.TicketUser
                                 .Where(x => x.RowStatus == enRowStatus.Active && x.TicketId == comment.TicketId && x.UserId == comment.User.Id)
                                 .FirstOrDefaultAsync();

                if (tickerUser != null)
                {
                    ticketUserID = tickerUser.Id;
                }
                else
                {
                    // TICKET USER
                    ticketUserID = context.TicketUser
                                   .Max(x => x.Id);

                    var ticketUser = new TicketUser
                    {
                        Id        = ++ticketUserID,
                        UserId    = comment.User.Id,
                        TicketId  = comment.TicketId,
                        RowStatus = enRowStatus.Active,
                        RowDate   = DateTime.Now
                    };

                    context.TicketUser.Add(ticketUser);
                    await context.SaveChangesAsync();
                }

                // COMMENT
                var commentId = context.Comments
                                .Max(x => x.Id);

                var dataComment = new Data.Comments
                {
                    Id           = ++commentId,
                    Comment      = comment.Description,
                    TicketUserId = ticketUserID,
                    RowStatus    = enRowStatus.Active,
                    RowDate      = DateTime.Now,
                };

                context.Comments.Add(dataComment);

                await context.SaveChangesAsync();

                return(OkResponse(true));
            }
            catch (Exception ex) { return(BadRequestResponse(ex)); }
            finally { context.Dispose(); }
        }
예제 #11
0
        /*private static TicketUserDTO ItemToDTO(TicketUser ticketUser) =>
         *  new TicketUserDTO
         *  {
         *      Id = ticketUser.Id,
         *      UserId = ticketUser.UserId,
         *      TicketStoreId = ticketUser.TicketStoreId,
         *      Punch = ticketUser.Punch,
         *      Status = ticketUser.Status,
         *      CreatedDate = ticketUser.CreatedDate,
         *      LastPunching = ticketUser.LastPunching,
         *      TempCode = ticketUser.TempCode,
         *      CreatedTempCode = ticketUser.CreatedTempCode
         *  };*/

        private static TicketUserDTO ItemToDTO(TicketUser ticketUser,
                                               int totalPunches, string storeName, int ticketTypeId, long punchValue, string giftDescription) =>
        new TicketUserDTO
        {
            Id              = ticketUser.Id,
            UserId          = ticketUser.UserId,
            TicketStoreId   = ticketUser.TicketStoreId,
            Punch           = ticketUser.Punch,
            Status          = ticketUser.Status,
            CreatedDate     = ticketUser.CreatedDate,
            LastPunching    = ticketUser.LastPunching,
            TempCode        = ticketUser.TempCode,
            CreatedTempCode = ticketUser.CreatedTempCode,
            TotalPunches    = totalPunches,
            StoreName       = storeName,
            TicketTypeId    = ticketTypeId,
            PunchValue      = punchValue,
            GiftDescription = giftDescription
        };
예제 #12
0
        private bool MessageDraftUpdate(
            String HtmlMessage,
            String Preview,
            Int64 TicketId,
            Int64 MessageId,
            TicketUser usr)
        {
            //if(!Manager.IsInTransaction())
            //{
            //    Manager.BeginTransaction();
            //}

            Message msg = Manager.Get <Message>(MessageId);


            if (
                usr == null ||
                msg == null ||
                msg.Ticket == null ||
                msg.Ticket.Id != TicketId ||
                msg.Creator == null ||
                msg.Creator.Id != usr.Id ||
                !msg.IsDraft ||
                msg.Deleted != BaseStatusDeleted.None)
            {
                return(false);
            }

            msg.UpdateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
            msg.Text    = HtmlMessage;
            msg.Preview = Preview;

            Manager.SaveOrUpdate <Message>(msg);

            //Manager.Flush();

            return(true);
        }
예제 #13
0
        /// <summary>
        /// Convalida un Token: se User valido lo cancella.
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public Domain.Enums.TokenValidationResult TokenValidate(Guid Code, Int64 UserId, Domain.Enums.TokenType Type)
        {
            if (Code == Guid.Empty)
            {
                return(Domain.Enums.TokenValidationResult.InvalidFormat);
            }

            if (UserId <= 0)
            {
                return(Domain.Enums.TokenValidationResult.UserNotFound);
            }

            TicketUser User = Manager.Get <TicketUser>(UserId);

            if (User == null || User.Id <= 0)
            {
                return(Domain.Enums.TokenValidationResult.UserNotFound);
            }

            IList <Token> Tokens = Manager.GetAll <Token>(tok => tok.Code == Code && tok.User.Id == UserId && tok.Type == Type);

            if (User.MailChecked == true)
            {
                Manager.DeletePhysicalList <Token>(Tokens);
                return(Domain.Enums.TokenValidationResult.Validated);
            }

            if (Tokens != null && Tokens.Any())
            {
                User.MailChecked = true;
                Manager.SaveOrUpdate <TicketUser>(User);
                Manager.DeletePhysicalList <Token>(Tokens);
                return(Domain.Enums.TokenValidationResult.Validated);
            }

            return(Domain.Enums.TokenValidationResult.TokenNotFound);
        }
예제 #14
0
        private async Task <VMs.Comment> ConvertVMComment(Data.Comments comment)
        {
            VMs.Comment result = new VMs.Comment();

            try
            {
                result.Id          = comment.Id;
                result.Description = comment.Comment;

                using (var user = new UserController(context))
                {
                    TicketUser ticketUserId = await context.TicketUser
                                              .Where(x => x.RowStatus == Data.enRowStatus.Active && x.Id == comment.TicketUserId)
                                              .FirstOrDefaultAsync();

                    result.TicketId = ticketUserId.TicketId;
                    result.User     = await user.GetUserData(ticketUserId.UserId);
                }

                return(result);
            }
            catch (Exception ex) { throw ex; }
            finally { context.Dispose(); }
        }
예제 #15
0
 /// <summary>
 /// Costruttore
 /// </summary>
 public DTO_UserRole()
 {
     User      = new TicketUser();
     IsManager = false;
 }
예제 #16
0
        public async Task <ActionResult <TicketUserDTO> > GenerateTempCode(IIdentity userIdentity, long ticketStoreId)
        {
            int tempCode = 0;

            #region// Get user id
            string userIdStr = Identity.GetValueFromClaim(userIdentity, "Id");
            long   userId    = Convert.ToInt64(userIdStr);
            #endregion

            #region// Get ticket user
            ActionResult <TicketUser> actionTicketUser = await ticketUserDA.GetTicketUser(userId,
                                                                                          ticketStoreId, TICKET_ACTIVE);

            if (actionTicketUser == null || actionTicketUser.Value == null)
            {
                return(new NotFoundObjectResult("The ticket not exist or unactive"));
                //return new NotFoundResult();
            }
            TicketUser ticketUser = actionTicketUser.Value;
            #endregion

            #region// Get ticket store
            ActionResult <TicketStore> actionStore = await ticketStoreDA.GetTicketStore(ticketStoreId);

            if (actionStore == null || actionStore.Value == null)
            {
                return(new NotFoundResult());
            }
            TicketStore ticketStore = actionStore.Value;
            #endregion

            // Generate temp code(1 - 99999) and insert to ticket user(database)
            tempCode = new Random().Next(10001, 100000);

            int i = 0;
            for (i = 0; i < 10; i++)
            {
                ActionResult <TicketUser> actionTicketUserWithSameTempCode = await ticketUserDA.GetTicketUser(tempCode, ticketStoreId);

                if (actionTicketUserWithSameTempCode != null &&
                    actionTicketUserWithSameTempCode.Value != null)
                {
                    tempCode = new Random().Next(10001, 100000);
                    continue;
                }
                break;
            }
            // 10 time generate same code with same store id
            if (i == 10)
            {
                return(new NotFoundObjectResult("Please try again or talk with customer service"));
            }

            // Insert temp code to ticket user
            ticketUser.TempCode        = tempCode;
            ticketUser.CreatedTempCode = DateTime.Now;

            #region// Insert to database
            try
            {
                await ticketUserDA.PutTicketUser(ticketUser);
            }
            catch (DbUpdateConcurrencyException) when(!ticketUserDA.Exists(ticketUser.Id))
            {
                return(new NotFoundResult());
            }
            #endregion

            // Get store name
            ActionResult <Store> storeAction = await storeDA.GetStore(ticketStore.StoreId);

            if (storeAction == null || storeAction.Value == null)
            {
                return(new NotFoundResult());
            }
            Store store = storeAction.Value;

            return(new OkObjectResult(
                       ItemToDTO(ticketUser, ticketStore.TotalPunches, store.Name, ticketStore.TicketTypeId,
                                 ticketStore.PunchValue, ticketStore.GiftDescription)));
        }
예제 #17
0
        /// <summary>
        /// Valida la mail di un utente, in automatico al primo tentativo di accesso
        /// </summary>
        /// <param name="Mail">Mail utente</param>
        /// <param name="Code">Codice utente</param>
        /// <returns>Eventuali segnalazioni errori</returns>
        public Domain.DTO.DTO_User UserValidateExternal(
            String Mail,
            String Code,
            String Token,
            ref Domain.Enums.ExternalUserValidateError Err)
        {
            Err = Domain.Enums.ExternalUserValidateError.none;

            TicketUser User = Manager.GetAll <TicketUser>(u => u.mail == Mail || (u.Person != null && u.Person.Mail == Mail)).Skip(0).Take(1).ToList().FirstOrDefault();

            if (User == null || User.Id <= 0)
            {
                Err = Domain.Enums.ExternalUserValidateError.invalidMail;
                return(new Domain.DTO.DTO_User());
            }
            //else if (String.IsNullOrEmpty(User.Code))
            //{
            //    Err = Domain.Enums.ExternalUserValidateError.invalidCode;
            //    return new Domain.DTO.DTO_User();
            //}
            else if (User.Code != AuthenticationHelper.Encrypt(Code))
            {
                Err = Domain.Enums.ExternalUserValidateError.invalidCode;
                return(new Domain.DTO.DTO_User());
            }

            //Controllo Token
            if (User.MailChecked == false)
            {
                Domain.Enums.TokenValidationResult TokErr = this.TokenValidate(Token, User.Id, Domain.Enums.TokenType.Registration);

                switch (TokErr)
                {
                //case Domain.Enums.TokenValidationResult.UserNotFound
                case Domain.Enums.TokenValidationResult.TokenNotFound:
                    Err = Domain.Enums.ExternalUserValidateError.TokenEmpty;
                    //return new Domain.DTO.DTO_User();
                    break;

                case Domain.Enums.TokenValidationResult.InvalidFormat:
                    Err = Domain.Enums.ExternalUserValidateError.TokenInvalid;
                    //return new Domain.DTO.DTO_User();
                    break;

                case Domain.Enums.TokenValidationResult.Exired:
                    Err = Domain.Enums.ExternalUserValidateError.TokenExpired;
                    //return new Domain.DTO.DTO_User();
                    break;
                    //case Domain.Enums.TokenValidationResult.Validated:
                }
            }

            Boolean IsInternal = (User.Person != null);

            String LangCode = "";

            if (!String.IsNullOrEmpty(User.LanguageCode))
            {
                LangCode = User.LanguageCode;
            }
            else if (IsInternal)
            {
                Language lang = Manager.Get <Language>(User.Person.LanguageID);
                if (lang != null)
                {
                    LangCode = lang.Code;
                }
            }
            else
            {
                Language lang = Manager.GetDefaultLanguage();
                LangCode = lang.Code;
            }

            Domain.DTO.DTO_User Usr = new Domain.DTO.DTO_User
            {
                UserId       = User.Id,
                PersonId     = (IsInternal) ? User.Person.Id : -1,
                LanguageCode = LangCode,
                Mail         = (IsInternal) ? User.Person.Mail : User.mail,
                Name         = (IsInternal) ? User.Person.Name : User.Name,
                SName        = (IsInternal) ? User.Person.Surname : User.Sname,
                IsOwnerNotificationEnable = User.IsNotificationActiveUser
            };

            //UserId = User.Id;

            return(Usr);
        }
예제 #18
0
 public async Task <ActionResult <TicketUserDTO> > CreateTicketUser(TicketUser ticketUser,
                                                                    int userTempCode, string userEmail)
 {
     return(await ticketUserBL.CreateTicketUser(HttpContext.User.Identity, ticketUser,
                                                userTempCode, userEmail, hub));
 }
예제 #19
0
 public async Task <ActionResult <TicketUserDTO> > CreateTicketUser(TicketUser ticketUser)
 {
     return(await ticketUserBL.CreateTicketUser(HttpContext.User.Identity, ticketUser, 0, "", hub));
 }
예제 #20
0
        /// <summary>
        /// Invio Token/URL per la validazione dell'utente
        /// </summary>
        /// <param name="NotificationType">Tipo notifica</param>
        /// <returns></returns>
        public bool NotificationSendToken(TicketUser User, Domain.DTO.DTO_NotificationSettings Settings, Token Token, String Password)
        {
            //Testo esempio:

            /* Gentile [PlaceHoldersType.UserSureName] [PlaceHoldersType.UserName]
             * Il suo account è stato registrato nel sistema.
             *
             * Dati Account:
             * Mail: [PlaceHoldersType.UserMail]
             * Password: [PlaceHoldersType.UserPassword]
             * Lingua: [PlaceHoldersType.UserLanguageCode]
             *
             * Per attivarlo è necessario accedere con le proprie credenziali al seguente indirizzo:
             * [PlaceHoldersType.UserTokenUrl]
             *
             * Oppure dalla pagine di accesso, al primo tentativo verrà richiesto il seguente codice di convalida:
             * [PlaceHoldersType.UserToken]
             *
             * La conferma dell'account può essere effettuata entro il: [PlaceHoldersType.UserTokenExpiration]
             */


            //To Do!!!
            //Domain.Enums.Notification NotificationType = Domain.Enums.Notification.ExternalRegistration;

            //Creo oggetto SETTINGS (me lo farò passare...)
            //Domain.DTO.DTO_NotificationSettings Settings = new Domain.DTO.DTO_NotificationSettings
            //{
            //    BaseUrl = "http://blablalba",
            //    DateTimeFormat = "0:dd/MM/yy H:mm:ss",
            //    LangCode = User.LanguageCode,
            //    CategoriesTemplate = "",
            //    IntCategoryType = null, IntTicketStatus= null,
            //    SmtpConfig = null
            //};

            //Creo oggetto DATA
            Domain.DTO.DTO_NotificationData Data = new Domain.DTO.DTO_NotificationData();
            bool   IsPerson = (User.Person == null) ? false : true;
            String Mail     = IsPerson ? User.Person.Mail : User.mail;

            Data.User = new Domain.DTO.Notification.DTO_User
            {
                LanguageCode = User.LanguageCode,
                Mail         = Mail,
                Name         = IsPerson ? User.Person.Name : User.Name,
                Surname      = IsPerson ? User.Person.Surname : User.Sname,
                Password     = Password,
                Token        = new Domain.DTO.Notification.DTO_User.DTO_Token
                {
                    Code     = Token.Code.ToString(),
                    Creation = Token.CreatedOn
                }
            };

            //Recupero messaggio
            lm.Comol.Core.Notification.Domain.dtoNotificationMessage msg =
                ServiceTemplate.GetNotificationMessage(
                    Data.User.LanguageCode,
                    ModuleTicket.UniqueCode,
                    (Int64)ModuleTicket.MailSenderActionType.externalRegistration);

            if (msg == null)
            {
                return(false);
            }

            // Invio Mail.
            return(NotificationSendMail(Settings, Data, msg, Mail));
        }
예제 #21
0
        public async Task <ActionResult <TicketUserDTO> > CreatePunch(long ticketStoreId, int tempCode,
                                                                      IHubContext <ChatHub> hub)
        {
            #region// Get ticket user with temp code
            ActionResult <TicketUser> actionTicketUser = await ticketUserDA.GetTicketUser(tempCode, ticketStoreId);

            if (actionTicketUser == null || actionTicketUser.Value == null)
            {
                return(new NotFoundObjectResult("Wrong temp code "));
            }
            TicketUser ticketUser = actionTicketUser.Value;

            if (ticketUser.CreatedTempCode.Value.AddMinutes(5) < DateTime.Now)
            {
                return(new NotFoundObjectResult("More than five minutes have passed, please try again"));
            }
            #endregion

            #region// Get ticket store
            ActionResult <TicketStore> actionStore = await ticketStoreDA.GetTicketStore(ticketStoreId);

            if (actionStore == null || actionStore.Value == null)
            {
                return(new NotFoundResult());
            }
            TicketStore ticketStore = actionStore.Value;
            #endregion

            if (ticketUser.Punch >= ticketStore.TotalPunches || ticketUser.Status == TICKET_UNACTIVE)
            {
                return(new BadRequestObjectResult("Ticket id '" + ticketUser.Id + "' is finish"));
            }

            // Make punch in the ticket
            ticketUser.Punch++;
            ticketUser.LastPunching = DateTime.Now;
            // Remove tempCode and createdTempCode from database
            ticketUser.TempCode        = null;
            ticketUser.CreatedTempCode = null;

            if (ticketUser.Punch >= ticketStore.TotalPunches)
            {
                ticketUser.Status = TICKET_UNACTIVE;
            }

            #region// Insert to database
            try
            {
                await ticketUserDA.PutTicketUser(ticketUser);
            }
            catch (DbUpdateConcurrencyException) when(!ticketUserDA.Exists(ticketUser.Id))
            {
                return(new NotFoundResult());
            }
            #endregion

            // Get store name
            ActionResult <Store> storeAction = await storeDA.GetStore(ticketStore.StoreId);

            if (storeAction == null || storeAction.Value == null)
            {
                return(new NotFoundResult());
            }
            Store store = storeAction.Value;

            // Caller chat notification
            await hub.Clients.All.SendAsync(ticketUser.UserId.ToString(), "success", ticketUser);

            // Create punch history
            PunchHistory punchHistory = new PunchHistory
            {
                Id            = Guid.NewGuid().ToString(),
                UserId        = ticketUser.UserId,
                TicketStoreId = ticketUser.TicketStoreId,
                Punch         = ticketUser.Punch,
                CreatedDate   = (DateTime)ticketUser.LastPunching
            };
            await punchHistoryDA.CreatePunchHistory(punchHistory);

            return(new OkObjectResult(
                       ItemToDTO(ticketUser, ticketStore.TotalPunches, store.Name, ticketStore.TicketTypeId,
                                 ticketStore.PunchValue, ticketStore.GiftDescription)));
        }
예제 #22
0
        /// <summary>
        /// Crea utente da esterno
        /// </summary>
        /// <param name="Name">Nome</param>
        /// <param name="Sname">cognome</param>
        /// <param name="Mail">Mail</param>
        /// <returns></returns>
        public Domain.DTO.DTO_ExtUserAddResult UserCreateFromExternal(
            String Name,
            String Sname,
            String Mail,
            String LangCode,
            String Code,
            Domain.DTO.DTO_NotificationSettings Settings)
        {
            Domain.DTO.DTO_ExtUserAddResult response = new Domain.DTO.DTO_ExtUserAddResult();
            response.Errors = Domain.Enums.ExternalUserCreateError.none;

            // 1. Check formato MAIL
            if (!MailCheckFormat(Mail))
            {
                response.User.UserId   = 0;
                response.User.PersonId = 0;
                response.Errors        = Domain.Enums.ExternalUserCreateError.invalidMail;
                return(response);
            }



            litePerson SysPerson  = null;
            Boolean    IsInternal = false;



            // 2. Controllo se In TicketSystem
            TicketUser User = (from TicketUser usr in Manager.GetIQ <TicketUser>()
                               where usr.mail == Mail ||
                               usr.Person != null && usr.Person.Mail == Mail
                               select usr).Skip(0).Take(1).ToList().FirstOrDefault();

            // Utente in Ticket System, con password già impostata: Utilizzare RECUEPRA PASSWORD (err.TicketMail)
            if (User != null && User.Id > 0)
            {
                response.User.UserId = User.Id;

                //Utente INTERNO!    -   MAIL VALIDA!!!
                if (User.Person != null)
                {
                    response.User.PersonId = User.Person.Id;
                    SysPerson  = User.Person;
                    IsInternal = true;

                    if (!String.IsNullOrEmpty(User.Code))
                    {
                        response.Errors = Domain.Enums.ExternalUserCreateError.TicketMail;
                        return(response);
                    }
                }
                else
                {
                    // UTENTE INTERNO - contorllo se MAIL CHECKATA:
                    // Sì: usare recupera password
                    // NO: ovverride Utente con dati forniti!

                    response.User.PersonId = 0;

                    if (User.MailChecked)
                    {
                        response.Errors = Domain.Enums.ExternalUserCreateError.TicketMail;
                        return(response);
                    }
                }

                //L'utente verrà aggiornato!
                User.UpdateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
            }
            else
            {
                //NUOVO UTENTE TICKET!
                User = new TicketUser();
                User.CreateMetaInfo(CurrentPerson, UC.IpAddress, UC.ProxyIpAddress);
                User.Enabled = true;

                //3. Controllo se In Sistema
                SysPerson = (from litePerson prsn in Manager.GetIQ <litePerson>() where prsn.Mail == Mail select prsn).Skip(0).Take(1).ToList().FirstOrDefault();

                if (SysPerson != null && SysPerson.Id > 0)
                {
                    IsInternal      = true;
                    response.Errors = Domain.Enums.ExternalUserCreateError.internalMail;
                }
                else
                {
                    IsInternal = false;
                    SysPerson  = null;
                }
            }


            if (IsInternal)
            {
                User.Name   = "";
                User.Sname  = "";
                User.mail   = "";
                User.Person = SysPerson;
            }
            else
            {
                User.Name  = Name;
                User.Sname = Sname;
                User.mail  = Mail;
            }

            User.MailChecked  = false;
            User.LanguageCode = LangCode;
            User.Code         = AuthenticationHelper.Encrypt(Code);
            Manager.SaveOrUpdate <TicketUser>(User);

            //Aggiorno i campi di REsponse con quelli in dB.
            if (IsInternal)
            {
                response.User.Name  = User.Person.Name;
                response.User.SName = User.Person.Surname;
            }
            else
            {
                response.User.Name  = User.Name;
                response.User.SName = User.Sname;
            }
            //response.DisplayName = (String.IsNullOrEmpty(User.DisplayName) ? User.Sname + " " + User.Name : User.DisplayName);

            response.User.Mail = User.mail;

            //MAIL CONVALIDA:
            // 1. GENERO CODICE VERIFICA
            Token tok = this.TokenCreate(User.Id, Domain.Enums.TokenType.Registration);

            // 2. Lo invio
            Boolean Sended = this.NotificationSendToken(User, Settings, tok, Code);

            response.Note = "<br/>Token: " + tok.Code.ToString() + "<br/>Expire on: " + tok.CreatedOn.Add(TokenLifeTime).ToString();
            //x TEST:
            if (Sended)
            {
                response.Note += "<br/> - SENDED -";
            }
            else
            {
                response.Note += "<br/> - SENDING ERROR! -";
            }

            // Eventuali errori:    response.Errors = Domain.Enums.ExternalUserCreateError.internalError;

            return(response);
        }
        public List <TicketFile> AttachmentsLinkFiles(Message message, List <ModuleActionLink> links)
        {
            List <TicketFile> attachments = null;

            if (message == null || links == null || !links.Any())
            {
                return(null);
            }

            TicketUser usr = this.UserGetfromPerson(UC.CurrentUserID);

            if (message.Creator == null || message.Creator.Id != usr.Id)
            {
                return(null);
            }

            Boolean isInTransaction = Manager.IsInTransaction();

            try
            {
                if (!isInTransaction)
                {
                    Manager.BeginTransaction();
                }
                litePerson person = CurrentLitePerson;

                if (person != null && person.Id > 0)
                {
                    DateTime date = DateTime.Now;
                    attachments = new List <TicketFile>();
                    foreach (ModuleActionLink link in links)
                    {
                        TicketFile attachment = QueryAttachments(a => a.Deleted == BaseStatusDeleted.None && a.Message != null && a.Message.Id == message.Id).ToList().Where(a => a.Item == (liteRepositoryItem)link.ModuleObject.ObjectOwner).Skip(0).Take(1).ToList().FirstOrDefault();
                        if (attachment == null)
                        {
                            attachment = new TicketFile();
                            attachment.CreateMetaInfo(person, UC.IpAddress, UC.ProxyIpAddress, date);
                            attachment.Item       = (liteRepositoryItem)link.ModuleObject.ObjectOwner;
                            attachment.Message    = message;
                            attachment.TicketId   = ((message != null && message.Ticket != null) ? message.Ticket.Id : 0);
                            attachment.Name       = attachment.Item.DisplayName;
                            attachment.Visibility = Domain.Enums.FileVisibility.visible;

                            Manager.SaveOrUpdate(attachment);


                            liteModuleLink mLink = new liteModuleLink(link.Description, link.Permission, link.Action);
                            mLink.CreateMetaInfo(person.Id, UC.IpAddress, UC.ProxyIpAddress, date);
                            mLink.DestinationItem = (ModuleObject)link.ModuleObject;
                            mLink.AutoEvaluable   = false;
                            mLink.SourceItem      = ModuleObject.CreateLongObject(message.Id, message, (int)ModuleTicket.ObjectType.Message, 0, ModuleTicket.UniqueCode, ServiceModuleID());
                            Manager.SaveOrUpdate(mLink);
                            attachment.Link = mLink;
                            Manager.SaveOrUpdate(attachment);
                        }
                        else if (attachment.Deleted != BaseStatusDeleted.None)
                        {
                            attachment.RecoverMetaInfo(person, UC.IpAddress, UC.ProxyIpAddress, date);
                            if (attachment.Item != null && attachment.Item.IsInternal && attachment.Item.Deleted != BaseStatusDeleted.None)
                            {
                                attachment.Item.Deleted = BaseStatusDeleted.None;
                                attachment.Item.UpdateMetaInfo(person.Id, UC.IpAddress, UC.ProxyIpAddress, date);
                                Manager.SaveOrUpdate(attachment.Item);
                            }
                            Manager.SaveOrUpdate(attachment);
                        }
                        attachments.Add(attachment);
                    }
                }
                if (!isInTransaction)
                {
                    Manager.Commit();
                }
            }
            catch (Exception ex)
            {
                if (!isInTransaction)
                {
                    Manager.RollBack();
                }
                attachments = null;
            }
            return(attachments);
        }
        public List <TicketFile> AttachmentsAddFiles(Message message, TicketUser user, List <dtoModuleUploadedItem> items)
        {
            List <TicketFile> attachments = null;

            if (message == null || message.Ticket == null || user == null || items == null || !items.Any())
            {
                return(null);
            }
            if (message.Creator == null || message.Creator.Id != user.Id)
            {
                return(null);
            }
            Boolean isInTransaction = Manager.IsInTransaction();

            try
            {
                if (!isInTransaction)
                {
                    Manager.BeginTransaction();
                }
                litePerson person = (user.Person ?? Manager.GetLiteUnknownUser());
                if (items.Any() && person != null && person.TypeID != (int)UserTypeStandard.Guest && person.TypeID != (int)UserTypeStandard.PublicUser)
                {
                    attachments = new List <TicketFile>();
                    DateTime date = DateTime.Now;
                    foreach (dtoModuleUploadedItem item in items)
                    {
                        TicketFile attachment = new TicketFile();
                        attachment.CreateMetaInfo(person, UC.IpAddress, UC.ProxyIpAddress, date);
                        attachment.Item       = item.ItemAdded;
                        attachment.Message    = message;
                        attachment.TicketId   = ((message != null && message.Ticket != null) ? message.Ticket.Id : 0);
                        attachment.Name       = attachment.Item.DisplayName;
                        attachment.Visibility = Domain.Enums.FileVisibility.visible;
                        Manager.SaveOrUpdate(attachment);
                        liteModuleLink link = new liteModuleLink(item.Link.Description, item.Link.Permission, item.Link.Action);
                        link.CreateMetaInfo(person.Id, UC.IpAddress, UC.ProxyIpAddress, date);
                        link.DestinationItem = (ModuleObject)item.Link.ModuleObject;
                        link.AutoEvaluable   = false;
                        link.SourceItem      = ModuleObject.CreateLongObject(message.Id, message, (int)ModuleTicket.ObjectType.Message, 0, ModuleTicket.UniqueCode, ServiceModuleID());
                        Manager.SaveOrUpdate(link);
                        attachment.Link = link;

                        if (item.ItemAdded.IsInternal)
                        {
                            if (item.ItemAdded.Module == null)
                            {
                                item.ItemAdded.Module = new lm.Comol.Core.FileRepository.Domain.ItemModuleSettings();
                            }
                            item.ItemAdded.Module.IdObject     = message.Id;
                            item.ItemAdded.Module.IdObjectType = (int)ModuleTicket.ObjectType.Message;
                            Manager.SaveOrUpdate(item.ItemAdded);
                        }

                        Manager.SaveOrUpdate(attachment);
                        attachments.Add(attachment);
                    }
                }
                if (!isInTransaction)
                {
                    Manager.Commit();
                }
            }
            catch (Exception ex)
            {
                if (!isInTransaction)
                {
                    Manager.RollBack();
                }
                attachments = null;
            }
            return(attachments);
        }
예제 #25
0
        /////// X NOTIFICATION!!!

        public Domain.DTO.Notification.DTO_UserNotificationData UserGetNotificationData(TicketUser user)
        {
            if (user == null || (!user.MailChecked && user.Person == null) || !user.Enabled)
            {
                return(null);
            }

            Domain.DTO.Notification.DTO_UserNotificationData data = new DTO_UserNotificationData();

            data.Channel = NotificationChannel.Mail;

            data.LanguageCode = (user.Person == null) ? user.LanguageCode : this.Manager.GetLanguageByIdOrDefault(user.Person.LanguageID).Code;
            //data.LanguageCode = user.LanguageCode;


            data.UserId = user.Id;

            if (user.Person != null)
            {
                data.ChannelAddress = user.Person.Mail;
                data.FullUserName   = user.Person.SurnameAndName;
                data.PersonId       = user.Person.Id;
            }
            else
            {
                data.ChannelAddress = string.Format("{0} {1}", user.Sname, user.Name);
                data.FullUserName   = user.mail;
                data.PersonId       = -1;
            }


            //NOTA DATI FARLOCCHI!
            //RETURN VALORI OK con configurazione!


            return(data);
        }
예제 #26
0
        /*public async Task<IActionResult> GetTicketUser(long id)
         * {
         *  ActionResult<TicketUser> action = await ticketUserDA.GetTicketUser(id);
         *
         *  if (action == null || action.Value == null)
         *  {
         *      return new NotFoundResult();
         *  }
         *
         *  TicketUser ticketUser = action.Value;
         *
         *  // Get total punches
         *  ActionResult<TicketStore> ticketStoreAction = await ticketStoreDA.GetTicketStore(ticketUser.TicketStoreId);
         *  if (ticketStoreAction == null || ticketStoreAction.Value == null)
         *  {
         *      return new NotFoundResult();
         *  }
         *  TicketStore ticketStore = ticketStoreAction.Value;
         *
         *  // Get store name
         *  ActionResult<Store> storeAction = await storeDA.GetStore(ticketStore.StoreId);
         *  if (storeAction == null || storeAction.Value == null)
         *  {
         *      return new NotFoundResult();
         *  }
         *  Store store = storeAction.Value;
         *
         *  // Get ticket type
         *  ActionResult<TicketType> ticketTypeAction = await ticketTypeDA.GetTicketType(ticketStore.TicketTypeId);
         *  if (ticketTypeAction == null || ticketTypeAction.Value == null)
         *  {
         *      return new NotFoundResult();
         *  }
         *  TicketType ticketType = ticketTypeAction.Value;
         *
         *  TicketUserDTO ticketUserDTO = ItemToDTO(ticketUser, ticketStore.TotalPunches, store.Name, ticketType.Id);
         *
         *  return new OkObjectResult(ticketUserDTO);
         * }*/
        public async Task <ActionResult <TicketUserDTO> > CreateTicketUser(IIdentity userIdentity, TicketUser ticketUser,
                                                                           int userTempCode, string userEmail, IHubContext <ChatHub> hub)
        {
            string userIdStr = null;
            long   userId    = 0;
            User   user      = null;

            // Check if Cash ticket
            ActionResult <TicketStore> action = await ticketStoreDA.GetTicketStore(ticketUser.TicketStoreId);

            if (action == null || action.Value == null)
            {
                return(new NotFoundResult());
            }
            TicketStore ticketStore = action.Value;

            // Cash ticket
            if (ticketStore.TicketTypeId == CASH_TICKET)
            {
                if (string.IsNullOrEmpty(userEmail))
                {
                    return(new ConflictObjectResult("Please pass email"));
                }

                ActionResult <User> actionUser = await userDA.GetUser(userEmail);

                if (actionUser == null || actionUser.Value == null)
                {
                    //return new NotFoundResult();
                    return(new NotFoundObjectResult("user id : " + userId + " not found"));
                }
                user = actionUser.Value;

                userId = user.Id;
                //ticketUser.UserId = userId;
            }
            // Regular ticket
            else
            {
                userIdStr = Identity.GetValueFromClaim(userIdentity, "Id");
                userId    = Convert.ToInt64(userIdStr);
                //ticketUser.UserId = userId;
            }

            ticketUser.UserId = userId;

            #region// Get ticket user
            //TicketUser existTicketUser = null;
            ActionResult <TicketUser> actionTicketUser = await ticketUserDA.GetTicketUser(userId,
                                                                                          ticketUser.TicketStoreId, TICKET_ACTIVE);

            if (actionTicketUser != null && actionTicketUser.Value != null)
            {
                return(new ConflictObjectResult("The ticket already exists and active"));
            }
            #endregion

            if (ticketStore.TicketTypeId == CASH_TICKET)
            {
                if (userTempCode == EMPTY_CODE)
                {
                    return(new ConflictObjectResult("Please generate code and pass him"));
                }

                /*if (string.IsNullOrEmpty(userEmail))
                 * {
                 *  return new ConflictObjectResult("Please pass email");
                 * }*/
                /*ActionResult<User> actionUser = await userDA.GetUser(userId);
                 * if (actionUser == null || actionUser.Value == null)
                 * {
                 *  //return new NotFoundResult();
                 *  return new NotFoundObjectResult("user id : " + userId + " not found");
                 * }*/
                /*ActionResult<User> actionUser = await userDA.GetUser(userEmail);
                 * if (actionUser == null || actionUser.Value == null)
                 * {
                 *  //return new NotFoundResult();
                 *  return new NotFoundObjectResult("user id : " + userId + " not found");
                 * }
                 * User user = actionUser.Value;*/

                if (user.TempCode != userTempCode)
                {
                    return(new ConflictObjectResult("Wrong temp code"));
                }
                if (user.CreatedTempCode.Value.AddMinutes(5) < DateTime.Now)
                {
                    return(new NotFoundObjectResult("More than five minutes have passed, please try again"));
                }

                // Remove tempCode and createdTempCode from database
                user.TempCode        = null;
                user.CreatedTempCode = null;

                #region// Insert to database
                try
                {
                    await userDA.PutUser(user);
                }
                catch (DbUpdateConcurrencyException) when(!userDA.Exists(user.Id))
                {
                    return(new NotFoundResult());
                }
                #endregion
            }

            await ticketUserDA.CreateTicketUser(ticketUser);

            // Caller chat notification
            await hub.Clients.All.SendAsync(ticketUser.UserId.ToString(), "Ticket user created successfully", ticketUser);

            ActionResult <List <TicketUserJoinTicketStoreJoinStore> > actionJoin =
                await ticketUserDA.GetTicketUserWithJoin(userId, ticketUser.TicketStoreId);

            if (actionJoin == null || actionJoin.Value == null)
            {
                return(new NotFoundResult());
            }
            List <TicketUserJoinTicketStoreJoinStore> ticketJoin = actionJoin.Value;

            return(new CreatedAtRouteResult(new { Id = ticketUser.Id }, ticketJoin[0]));
        }