Пример #1
0
        private void UpdateInvoiceRegistFee(ref InvoiceWaitingConfirm invoiceWaitingConfirm)
        {
            int learnerId = invoiceWaitingConfirm.LearnerId.Value;

            var learner = _ablemusicContext.Learner.
                          Where(i => i.LearnerId == learnerId).FirstOrDefault();

            if (learner == null || learner.EnrollDate == null)
            {
                return;
            }
            if ((invoiceWaitingConfirm.BeginDate - learner.EnrollDate).Value.Days >= 60)
            {
                return;
            }

            //find if exist a not trial invoice
            var invoice = _ablemusicContext.InvoiceWaitingConfirm.
                          Where(i => i.LearnerId == learnerId &&
                                i.BeginDate != i.EndDate).FirstOrDefault();

            if (invoice != null)
            {
                invoiceWaitingConfirm.Other1Fee     = 20;
                invoiceWaitingConfirm.Other1FeeName = "Enrolment Fee";
                invoiceWaitingConfirm.TotalFee     += 20;
                invoiceWaitingConfirm.OwingFee     += 20;
            }
        }
Пример #2
0
        private bool updateInvoiceWaitingConfirm(ref InvoiceWaitingConfirm invoice)
        {
            var unitPrice = invoice.LessonFee / invoice.LessonQuantity;

            invoice.LessonQuantity--;
            invoice.LessonFee -= unitPrice;
            invoice.TotalFee  -= unitPrice;
            invoice.OwingFee  -= unitPrice;
            if (invoice.LessonQuantity == 0)
            {
                return(false);
            }
            return(true);
        }
Пример #3
0
        private string MailContentGenerator(InvoiceWaitingConfirm invoiceWaitingConfirmUpdate)
        {
            string mailContent = "<div><p>Dear " + invoiceWaitingConfirmUpdate.LearnerName + ":</p>" + "<p>Here is the invoice for your" +
                                 invoiceWaitingConfirmUpdate.CourseName + " lesson from " + invoiceWaitingConfirmUpdate.BeginDate.ToString() +
                                 " to " + invoiceWaitingConfirmUpdate.EndDate.ToString() + "</p>" + "<p>Invoice Number: " +
                                 invoiceWaitingConfirmUpdate.InvoiceNum + "</p>" + "<p>Lesson fee: " + invoiceWaitingConfirmUpdate.LessonFee +
                                 "</p><p>Concert fee: " + invoiceWaitingConfirmUpdate.ConcertFee + "</p><p>Note fee " +
                                 invoiceWaitingConfirmUpdate.NoteFee + "</p><p>Other fee: " + (invoiceWaitingConfirmUpdate.Other1Fee +
                                                                                               invoiceWaitingConfirmUpdate.Other2Fee + invoiceWaitingConfirmUpdate.Other3Fee).ToString() + "</p><p> Total fee " +
                                 invoiceWaitingConfirmUpdate.TotalFee + "</p><p>Due date: " + invoiceWaitingConfirmUpdate.DueDate.ToString() +
                                 "</p><p>Paid fee: " + invoiceWaitingConfirmUpdate.PaidFee + "</p><p>Owing fee: " + invoiceWaitingConfirmUpdate.OwingFee +
                                 "</p>";

            return(mailContent);
        }
Пример #4
0
        private bool findInvoice(int lessonId)
        {
            string invoiceNum = _ablemusicContext.Lesson.Where(i => i.LessonId == lessonId)
                                .Select(i => i.InvoiceNum).FirstOrDefault();

            if (invoiceNum == null)
            {
                throw new Exception("Can not find this lessons!");
            }
            InvoiceWaitingConfirm invoiceWaitingConfirm = _ablemusicContext.InvoiceWaitingConfirm
                                                          .Where(i => i.InvoiceNum == invoiceNum && i.IsActivate == 1).FirstOrDefault();

            if (invoiceWaitingConfirm == null)
            {
                throw new Exception("Can not find draft invoice!");
            }
            if (updateInvoiceWaitingConfirm(ref invoiceWaitingConfirm))
            {
                _ablemusicContext.Update(invoiceWaitingConfirm);
            }
            else
            {
                _ablemusicContext.Remove(invoiceWaitingConfirm);
            }

            Invoice invoice = _ablemusicContext.Invoice
                              .Where(i => i.InvoiceNum == invoiceNum && i.IsActive == 1).FirstOrDefault();

            if (invoice != null)
            {
                if (invoice.IsPaid == 1)
                {
                    throw new Exception("This lesson is paid ,can not be change!");
                }
                if (updateInvoice(ref invoice))
                {
                    _ablemusicContext.Update(invoice);
                }
                else
                {
                    _ablemusicContext.Remove(invoice);
                }
            }

            return(true);
        }
Пример #5
0
        private bool parseExp(int whichTerm, List <PromotionInvoice> promotionObj, ref InvoiceWaitingConfirm invoice)
        {
            PromotionInvoice termInvoice = promotionObj[whichTerm];
            decimal          feeAmt      = termInvoice.Amt;

            SetInvoiceInitFee(ref invoice, feeAmt);
            int idx = 0;

            if (termInvoice.Item == null)
            {
                return(true);
            }
            foreach (var item in termInvoice.Item)
            {
                SetInvoiceItem(ref invoice, item.Name, item.Amount, idx++);
            }
            return(true);
        }
Пример #6
0
        private void SetInvoiceInitFee(ref InvoiceWaitingConfirm invoice, decimal feeAmt)
        {
            invoice.TotalFee = feeAmt;
            invoice.OwingFee = feeAmt;

            invoice.LessonFee = feeAmt;

            invoice.ConcertFee        = null;
            invoice.ConcertFeeName    = null;
            invoice.NoteFee           = null;
            invoice.LessonNoteFeeName = null;

            invoice.Other1Fee     = null;
            invoice.Other1FeeName = null;
            invoice.Other2Fee     = null;
            invoice.Other2FeeName = null;
            invoice.Other3Fee     = null;
            invoice.Other3FeeName = null;
        }
Пример #7
0
        private void SetInvoiceItem(ref InvoiceWaitingConfirm invoice, string name, decimal?feeAmt, int index)
        {
            switch (index)
            {
            // case 0:
            //     invoice.LessonFee=feeAmt;
            //     invoice.CourseName=name;
            //     break;
            case 0:
                invoice.ConcertFee     = feeAmt;
                invoice.ConcertFeeName = name;
                break;

            case 1:
                invoice.NoteFee           = feeAmt;
                invoice.LessonNoteFeeName = name;
                break;

            case 2:
                invoice.NoteFee           = feeAmt;
                invoice.LessonNoteFeeName = name;
                break;

            case 3:
                invoice.Other1Fee     = feeAmt;
                invoice.Other1FeeName = name;
                break;

            case 4:
                invoice.Other2Fee     = feeAmt;
                invoice.Other2FeeName = name;
                break;

            case 5:
                invoice.Other3Fee     = feeAmt;
                invoice.Other3FeeName = name;
                break;

            default:
                break;
            }
        }
Пример #8
0
        public bool PromotionInvoice(ref InvoiceWaitingConfirm invoice)
        {
            List <PromotionInvoice> promotionObj = new  List <PromotionInvoice>();

            try{
                short promotionId = GetPromotionId(invoice.GroupCourseInstanceId);
                int   whichTerm   = WhichTerm(invoice.GroupCourseInstanceId, invoice.LearnerId);
                if (promotionId == 0)
                {
                    return(false);                  //no promotion
                }
                if (GetPromotionExp(promotionId, out promotionObj) == false)
                {
                    return(false);
                }
                parseExp(whichTerm, promotionObj, ref invoice);
            }
            catch (Exception e) {
                return(false);
            }
            return(true);
        }
Пример #9
0
 private short getInvoiceItem(InvoiceWaitingConfirm invoice)
 {
     if (invoice.Other13Fee != null && invoice.Other13Fee != 0)
     {
         return(5);
     }
     if (invoice.Other12Fee != null && invoice.Other12Fee != 0)
     {
         return(4);
     }
     if (invoice.Other11Fee != null && invoice.Other11Fee != 0)
     {
         return(3);
     }
     if (invoice.Other10Fee != null && invoice.Other10Fee != 0)
     {
         return(2);
     }
     if (invoice.Other9Fee != null && invoice.Other9Fee != 0)
     {
         return(1);
     }
     return(0);
 }
Пример #10
0
        public async Task <IActionResult> Post([FromBody] TrialLessonViewModel trialLessonViewModel)
        {
            var result         = new Result <Lesson>();
            var lesson         = new Lesson();
            var payment        = new Payment();
            var invoiceWaiting = new InvoiceWaitingConfirm();
            var invoice        = new Invoice();

            lesson.LearnerId             = trialLessonViewModel.LearnerId;
            lesson.RoomId                = trialLessonViewModel.RoomId;
            lesson.TeacherId             = trialLessonViewModel.TeacherId;
            lesson.OrgId                 = trialLessonViewModel.OrgId;
            lesson.IsCanceled            = 0;
            lesson.Reason                = null;
            lesson.CreatedAt             = toNZTimezone(DateTime.UtcNow);
            lesson.CourseInstanceId      = null;
            lesson.GroupCourseInstanceId = null;
            lesson.IsTrial               = 1;
            lesson.BeginTime             = trialLessonViewModel.BeginTime;
            lesson.EndTime               = trialLessonViewModel.EndTime;
            lesson.IsChanged             = 0;
            lesson.IsConfirm             = 0;
            lesson.TrialCourseId         = trialLessonViewModel.TrialCourseId;
            lesson.IsPaid                = trialLessonViewModel.IsPayNow?(short)1: (short)0;

            payment.PaymentMethod = trialLessonViewModel.PaymentMethod;
            payment.LearnerId     = trialLessonViewModel.LearnerId;
            payment.Amount        = trialLessonViewModel.Amount;
            payment.CreatedAt     = toNZTimezone(DateTime.UtcNow);
            payment.StaffId       = trialLessonViewModel.StaffId;
            payment.InvoiceId     = null;
            payment.BeforeBalance = null;
            payment.AfterBalance  = null;
            payment.PaymentType   = 3;
            payment.IsConfirmed   = 0;
            payment.Comment       = null;

            invoiceWaiting.LessonFee   = trialLessonViewModel.Amount;
            invoiceWaiting.LearnerId   = trialLessonViewModel.LearnerId;
            invoiceWaiting.LearnerName = await _ablemusicContext.Learner.
                                         Where(l => l.LearnerId == trialLessonViewModel.LearnerId).Select(l => l.FirstName).FirstOrDefaultAsync();

            invoiceWaiting.BeginDate = trialLessonViewModel.BeginTime.Value.Date;
            invoiceWaiting.EndDate   = trialLessonViewModel.BeginTime.Value.Date;
            invoiceWaiting.TotalFee  = trialLessonViewModel.Amount;
            invoiceWaiting.DueDate   = trialLessonViewModel.BeginTime.Value.Date;
            invoiceWaiting.PaidFee   = 0;
            invoiceWaiting.OwingFee  = trialLessonViewModel.Amount;
            invoiceWaiting.CreatedAt = toNZTimezone(DateTime.UtcNow);
            invoiceWaiting.IsPaid    = 0;
            invoiceWaiting.TermId    = await _ablemusicContext.Term.
                                       Where(t => t.BeginDate <= trialLessonViewModel.BeginTime.Value &&
                                             t.EndDate >= trialLessonViewModel.BeginTime.Value
                                             ).Select(l => l.TermId).FirstOrDefaultAsync();

            invoiceWaiting.LessonQuantity = 1;
            invoiceWaiting.CourseName     = "Trial Lesson";
            invoiceWaiting.IsConfirmed    = 1;
            invoiceWaiting.IsEmailSent    = 0;
            invoiceWaiting.IsActivate     = 1;

            List <Lesson>           conflictRooms          = new List <Lesson>();
            List <Lesson>           conflictTeacherLessons = new List <Lesson>();
            DateTime                beginTime = lesson.BeginTime.Value.AddMinutes(-60);
            DateTime                endTime   = lesson.EndTime.Value.AddMinutes(60);
            var                     lessonConflictCheckerService = new LessonConflictCheckerService(_ablemusicContext, lesson);
            Result <List <object> > lessonConflictCheckResult;

            try
            {
                lessonConflictCheckResult = await lessonConflictCheckerService.CheckBothRoomAndTeacher();
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.Message;
                return(BadRequest(result));
            }
            if (!lessonConflictCheckResult.IsSuccess)
            {
                return(BadRequest(lessonConflictCheckResult));
            }

            try
            {
                await _ablemusicContext.Lesson.AddAsync(lesson);

                if (trialLessonViewModel.IsPayNow)
                {
                    await _ablemusicContext.Payment.AddAsync(payment);
                }
                else
                {
                    await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoiceWaiting);

                    invoiceWaiting.InvoiceNum = invoiceWaiting.WaitingId.ToString();
                    _mapper.Map(invoiceWaiting, invoice);
                    invoice.IsActive = 1;
                    await _ablemusicContext.Invoice.AddAsync(invoice);
                }
                await _ablemusicContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.Message;
                return(BadRequest(result));
            }
            result.Data = lesson;
            return(Ok(result));
        }
        public async Task <IActionResult> RegistTrial([FromBody] TrialLessonAndLearnerModel trialLessonViewModel)
        {
            var result         = new Result <Lesson>();
            var lesson         = new Lesson();
            var payment        = new Payment();
            var learner        = new Learner();
            var invoiceWaiting = new InvoiceWaitingConfirm();
            var invoice        = new Invoice();

            using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
            {
                learner.FirstName  = trialLessonViewModel.FirstName;
                learner.LastName   = trialLessonViewModel.LastName;
                learner.ContactNum = trialLessonViewModel.ContactNum;
                learner.Email      = trialLessonViewModel.Email;
                learner.EnrollDate = toNZTimezone(DateTime.UtcNow);
                learner.OrgId      = trialLessonViewModel.OrgId;
                learner.CreatedAt  = toNZTimezone(DateTime.UtcNow);
                learner.IsActive   = 1;
                //learner.LearnerLevel = 0;
                learner.PaymentPeriod = 1;
                // learner.LevelType = 1;
                _ablemusicContext.Add(learner);
                await _ablemusicContext.SaveChangesAsync();

                // var fundItem = new Fund { Balance = 0, LearnerId = newLearner.LearnerId };
                _ablemusicContext.Add(new Fund {
                    Balance = 0, LearnerId = learner.LearnerId
                });
                await _ablemusicContext.SaveChangesAsync();

                _ablemusicContext.Add(new User
                {
                    UserName   = "******" + learner.LearnerId.ToString(),
                    Password   = "******",
                    CreatedAt  = toNZTimezone(DateTime.UtcNow),
                    RoleId     = 4,
                    IsActivate = 1
                });
                await _ablemusicContext.SaveChangesAsync();

                lesson.LearnerId             = learner.LearnerId;
                lesson.RoomId                = trialLessonViewModel.RoomId;
                lesson.TeacherId             = trialLessonViewModel.TeacherId;
                lesson.OrgId                 = trialLessonViewModel.OrgId;
                lesson.IsCanceled            = 0;
                lesson.Reason                = null;
                lesson.CreatedAt             = toNZTimezone(DateTime.UtcNow);
                lesson.CourseInstanceId      = null;
                lesson.GroupCourseInstanceId = null;
                lesson.IsTrial               = 1;
                lesson.BeginTime             = trialLessonViewModel.BeginTime;
                lesson.EndTime               = trialLessonViewModel.EndTime;
                lesson.IsChanged             = 2;
                lesson.IsConfirm             = 0;
                lesson.TrialCourseId         = trialLessonViewModel.TrialCourseId;
                lesson.IsPaid                = trialLessonViewModel.IsPayNow ? (short)1 : (short)0;

                payment.PaymentMethod = trialLessonViewModel.PaymentMethod;
                payment.LearnerId     = learner.LearnerId;
                payment.Amount        = trialLessonViewModel.Amount;
                payment.CreatedAt     = toNZTimezone(DateTime.UtcNow);
                payment.StaffId       = trialLessonViewModel.StaffId;
                payment.InvoiceId     = null;
                payment.BeforeBalance = null;
                payment.AfterBalance  = null;
                payment.PaymentType   = 3;
                payment.IsConfirmed   = 0;
                payment.Comment       = null;

                invoiceWaiting.LessonFee   = trialLessonViewModel.Amount;
                invoiceWaiting.LearnerId   = learner.LearnerId;
                invoiceWaiting.LearnerName = await _ablemusicContext.Learner.
                                             Where(l => l.LearnerId == learner.LearnerId).Select(l => l.FirstName).FirstOrDefaultAsync();

                invoiceWaiting.BeginDate = trialLessonViewModel.BeginTime.Value.Date;
                invoiceWaiting.EndDate   = trialLessonViewModel.BeginTime.Value.Date;
                invoiceWaiting.TotalFee  = trialLessonViewModel.Amount;
                invoiceWaiting.DueDate   = trialLessonViewModel.BeginTime.Value.Date.AddDays(7);
                invoiceWaiting.PaidFee   = 0;
                invoiceWaiting.OwingFee  = trialLessonViewModel.Amount;
                invoiceWaiting.CreatedAt = toNZTimezone(DateTime.UtcNow);
                invoiceWaiting.IsPaid    = 0;
                invoiceWaiting.TermId    = await _ablemusicContext.Term.
                                           Where(t => t.BeginDate <= trialLessonViewModel.BeginTime.Value &&
                                                 t.EndDate >= trialLessonViewModel.BeginTime.Value
                                                 ).Select(l => l.TermId).FirstOrDefaultAsync();

                invoiceWaiting.LessonQuantity = 1;
                invoiceWaiting.CourseName     = "Trial Lesson";
                invoiceWaiting.IsConfirmed    = 1;
                invoiceWaiting.IsEmailSent    = 0;
                invoiceWaiting.IsActivate     = 1;

                List <Lesson>           conflictRooms          = new List <Lesson>();
                List <Lesson>           conflictTeacherLessons = new List <Lesson>();
                DateTime                beginTime = lesson.BeginTime.Value.AddMinutes(-60);
                DateTime                endTime   = lesson.EndTime.Value.AddMinutes(60);
                var                     lessonConflictCheckerService = new LessonConflictCheckerService(_ablemusicContext, lesson);
                Result <List <object> > lessonConflictCheckResult;
                try
                {
                    lessonConflictCheckResult = await lessonConflictCheckerService.CheckBothRoomAndTeacher();
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    result.IsSuccess    = false;
                    result.ErrorMessage = ex.Message;
                    return(BadRequest(result));
                }
                if (!lessonConflictCheckResult.IsSuccess)
                {
                    return(BadRequest(lessonConflictCheckResult));
                }

                try
                {
                    if (trialLessonViewModel.IsPayNow)
                    {
                        await _ablemusicContext.Payment.AddAsync(payment);
                    }
                    else
                    {
                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoiceWaiting);

                        await _ablemusicContext.SaveChangesAsync();

                        invoiceWaiting.InvoiceNum = invoiceWaiting.WaitingId.ToString();
                        _mapper.Map(invoiceWaiting, invoice);
                        invoice.IsActive = 1;
                        await _ablemusicContext.Invoice.AddAsync(invoice);
                    }
                    lesson.InvoiceNum = invoiceWaiting.InvoiceNum;
                    await _ablemusicContext.Lesson.AddAsync(lesson);

                    await _ablemusicContext.SaveChangesAsync();

                    dbContextTransaction.Commit();
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    result.IsSuccess    = false;
                    result.ErrorMessage = ex.Message;
                    return(BadRequest(result));
                }
                result.Data = lesson;
                return(Ok(result));
            }
        }
        public async Task <Result <IActionResult> > GenerateGroupInvoice(int term_id, int instance_id = 0)
        {
            var concertFeeName = _ablemusicContext.Lookup.
                                 Where(x => x.LookupType == 15 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();;

            string concertFeeStr = _ablemusicContext.Lookup.
                                   Where(x => x.LookupType == 15 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
            int concertFee = Int32.Parse(concertFeeStr);
            //get note fee configuraton
            string noteFeeName = _ablemusicContext.Lookup.
                                 Where(x => x.LookupType == 16 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
            string noteFeeStr = _ablemusicContext.Lookup.
                                Where(x => x.LookupType == 16 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
            int noteFee = Int32.Parse(noteFeeStr);
            //get extra fee configuraton
            string extraFeeStr = _ablemusicContext.Lookup.
                                 Where(x => x.LookupType == 17 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
            int extraFee = Int32.Parse(extraFeeStr);

            var result = new Result <IActionResult>();
            var group_course_instances = await _ablemusicContext.GroupCourseInstance
                                         .Include(x => x.Course)
                                         .Include(x => x.LearnerGroupCourse)
                                         .Select(x => new
            {
                x.CourseId,
                x.GroupCourseInstanceId,
                x.BeginDate,
                x.EndDate,
                x.IsStarted,
                CourseName = x.Course.CourseName,
                Price      = x.Course.Price,
                Learners   = x.LearnerGroupCourse.Select(s => new { s.Learner.FirstName, s.LearnerId, s.CreatedAt, s.BeginDate, s.EndDate, s.InvoiceDate, s.LearnerGroupCourseId, s.IsActivate }).Where(s => s.IsActivate == 1).ToArray()
            })
                                         .ToListAsync();

            if (instance_id != 0)
            {
                group_course_instances = group_course_instances.Where(x => x.GroupCourseInstanceId == instance_id).ToList();
            }

            var term = await _ablemusicContext.Term.FirstOrDefaultAsync(x => x.TermId == term_id);

            //int i = 0;
            //int j = 0;
            foreach (var group_course_instance in group_course_instances)
            {
                foreach (var learner in group_course_instance.Learners)
                {
                    if (learner.InvoiceDate >= Convert.ToDateTime(term.EndDate))
                    {
                        continue;
                    }
                    DateTime begin_date;
                    InvoiceWaitingConfirm invoice = new InvoiceWaitingConfirm();

                    invoice.LearnerId             = learner.LearnerId;
                    invoice.LearnerName           = learner.FirstName;
                    invoice.GroupCourseInstanceId = group_course_instance.GroupCourseInstanceId;
                    invoice.CourseName            = group_course_instance.CourseName;
                    invoice.TermId            = (short)term.TermId;
                    invoice.IsPaid            = 0;
                    invoice.PaidFee           = 0;
                    invoice.CreatedAt         = _today;
                    invoice.IsConfirmed       = 0;
                    invoice.IsActivate        = 3;
                    invoice.IsEmailSent       = 0;
                    invoice.ConcertFeeName    = concertFeeName;
                    invoice.ConcertFee        = concertFee;
                    invoice.LessonNoteFeeName = noteFeeName;
                    invoice.NoteFee           = noteFee;

                    int isExist = IsLearnerHasPayExtreFee((int)invoice.TermId, (int)learner.LearnerId);
                    if (isExist == 1)
                    {
                        //invoice.ConcertFeeName = concertFeeName;
                        invoice.ConcertFee = 0;
                        //invoice.LessonNoteFeeName = noteFeeName;
                        invoice.NoteFee = 0;
                    }

                    var courseIns = await _ablemusicContext.LearnerGroupCourse.FirstOrDefaultAsync(x => x.LearnerGroupCourseId == learner.LearnerGroupCourseId);

                    int lesson_quantity = 0;

                    if (learner.InvoiceDate == null || (learner.InvoiceDate < term.EndDate && learner.BeginDate <= term.EndDate))
                    {
                        if (learner.BeginDate >= term.BeginDate)
                        {
                            begin_date = (DateTime)learner.BeginDate;
                        }
                        else
                        {
                            begin_date = (DateTime)term.BeginDate;
                        }
                        invoice.BeginDate = begin_date;
                        invoice.EndDate   = term.EndDate;

                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoice);

                        await _ablemusicContext.SaveChangesAsync();

                        //using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
                        //{
                        //    lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 0);
                        //    dbContextTransaction.Rollback();
                        //}

                        lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 0);

                        courseIns.InvoiceDate = invoice.EndDate;
                    }

                    if (invoice.BeginDate != null)
                    {
                        invoice.DueDate = Convert.ToDateTime(invoice.BeginDate).AddDays(-1);
                    }
                    invoice.LessonFee = group_course_instance.Price * lesson_quantity;

                    invoice.OwingFee       = invoice.LessonFee;
                    invoice.TotalFee       = invoice.LessonFee;
                    invoice.LessonQuantity = lesson_quantity;
                    if (invoice.LessonFee <= 0)
                    {
                        continue;
                    }

                    invoice.InvoiceNum = invoice.WaitingId.ToString();
                    _ablemusicContext.InvoiceWaitingConfirm.Update(invoice);
                    _ablemusicContext.Update(courseIns);

                    await _ablemusicContext.SaveChangesAsync();

                    //i++;
                    //j++;
                    //if (i == 5) break;
                }
                //if (j > 1) break;
            }
            //result.Data = i;

            return(result);
        }
        public async Task <Result <IActionResult> > Generateone2oneInvoice(int term_id, int instance_id = 0)
        {
            var result = new Result <IActionResult>();

            try
            {
                //get concert fee configuraton
                var concertFeeName = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 15 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();;

                string concertFeeStr = _ablemusicContext.Lookup.
                                       Where(x => x.LookupType == 15 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int concertFee = Int32.Parse(concertFeeStr);
                //get note fee configuraton
                string noteFeeName = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 16 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                string noteFeeStr = _ablemusicContext.Lookup.
                                    Where(x => x.LookupType == 16 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int noteFee = Int32.Parse(noteFeeStr);
                //get extra fee configuraton
                string extraFeeStr = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 17 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                int extraFee = Int32.Parse(extraFeeStr);

                var course_instances = await _ablemusicContext.One2oneCourseInstance
                                       .Include(x => x.Course)
                                       .Include(x => x.Learner).Where(x => x.Learner.IsActive == 1)
                                       .Select(x => new
                {
                    x.LearnerId,
                    x.CourseId,
                    x.CourseInstanceId,
                    x.BeginDate,
                    x.EndDate,
                    x.InvoiceDate,
                    Course = new
                    {
                        x.Course.CourseName,
                        x.Course.Price
                    },
                    Learner = new
                    {
                        x.Learner.FirstName,
                        x.Learner.PaymentPeriod
                    }
                })
                                       .ToListAsync();

                if (instance_id != 0)
                {
                    course_instances = course_instances.Where(x => x.CourseInstanceId == instance_id).ToList();
                }

                var term = await _ablemusicContext.Term.FirstOrDefaultAsync(x => x.TermId == term_id);

                var all_terms = await _ablemusicContext.Term.Select(x => new { x.TermId, x.BeginDate, x.EndDate }).ToListAsync();

                //int i = 0;
                foreach (var course_instance in course_instances)
                {
                    if (course_instance.InvoiceDate >= Convert.ToDateTime(term.EndDate))
                    {
                        continue;
                    }
                    InvoiceWaitingConfirm invoice = new InvoiceWaitingConfirm();

                    invoice.LearnerId         = course_instance.LearnerId;
                    invoice.LearnerName       = course_instance.Learner.FirstName;
                    invoice.CourseInstanceId  = course_instance.CourseInstanceId;
                    invoice.CourseName        = course_instance.Course.CourseName;
                    invoice.ConcertFeeName    = concertFeeName;
                    invoice.ConcertFee        = concertFee;
                    invoice.LessonNoteFeeName = noteFeeName;
                    invoice.NoteFee           = noteFee;
                    invoice.TermId            = (short)term_id;
                    invoice.IsPaid            = 0;
                    invoice.PaidFee           = 0;
                    invoice.CreatedAt         = _today;
                    invoice.IsConfirmed       = 0;
                    invoice.IsActivate        = 3;
                    invoice.IsEmailSent       = 0;

                    int isExist = IsLearnerHasPayExtreFee((int)invoice.TermId, (int)course_instance.LearnerId);
                    if (isExist == 1)
                    {
                        //invoice.ConcertFeeName = concertFeeName;
                        invoice.ConcertFee = 0;
                        //invoice.LessonNoteFeeName = noteFeeName;
                        invoice.NoteFee = 0;
                    }

                    var courseIns = await _ablemusicContext.One2oneCourseInstance.FirstOrDefaultAsync(x => x.CourseInstanceId == invoice.CourseInstanceId);

                    int lesson_quantity = 0;

                    if (course_instance.Learner.PaymentPeriod == 1 && (course_instance.InvoiceDate == null || course_instance.InvoiceDate < term.EndDate))
                    {
                        if (course_instance.BeginDate >= term.BeginDate)
                        {
                            invoice.BeginDate = course_instance.BeginDate;
                        }
                        else
                        {
                            invoice.BeginDate = term.BeginDate;
                        }

                        invoice.EndDate = term.EndDate;

                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoice);

                        await _ablemusicContext.SaveChangesAsync();

                        //using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
                        //{
                        //    lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                        //    dbContextTransaction.Rollback();

                        //}
                        lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);

                        courseIns.InvoiceDate = invoice.EndDate;
                    }
                    else if (course_instance.Learner.PaymentPeriod == 2)
                    {
                        if (course_instance.InvoiceDate == null)
                        {
                            if (course_instance.BeginDate >= term.BeginDate)
                            {
                                invoice.BeginDate = course_instance.BeginDate;
                            }
                            else
                            {
                                invoice.BeginDate = term.BeginDate;
                            }
                            int DOW = day_trans(Convert.ToDateTime(invoice.BeginDate).DayOfWeek.ToString());

                            invoice.BeginDate = Convert.ToDateTime(invoice.BeginDate).AddDays(8 - DOW);
                            invoice.EndDate   = Convert.ToDateTime(invoice.BeginDate).AddDays(6);

                            courseIns.InvoiceDate = invoice.EndDate;
                        }
                        else if (course_instance.EndDate == null || (course_instance.EndDate != null && course_instance.EndDate > course_instance.InvoiceDate))
                        {
                            invoice.BeginDate     = Convert.ToDateTime(courseIns.InvoiceDate).AddDays(1);
                            invoice.EndDate       = Convert.ToDateTime(invoice.BeginDate).AddDays(6);
                            courseIns.InvoiceDate = invoice.EndDate;
                        }
                        else
                        {
                            continue;
                        }
                        foreach (var all_term in all_terms)
                        {
                            if (invoice.EndDate >= all_term.BeginDate && invoice.EndDate <= all_term.EndDate)
                            {
                                invoice.TermId = all_term.TermId;
                            }
                        }

                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoice);

                        await _ablemusicContext.SaveChangesAsync();

                        //using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
                        //{
                        //    lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                        //    dbContextTransaction.Rollback();

                        //}
                        lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                    }
                    if (invoice.BeginDate != null)
                    {
                        invoice.DueDate = Convert.ToDateTime(invoice.BeginDate).AddDays(-1);
                    }
                    invoice.LessonFee = course_instance.Course.Price * lesson_quantity;
                    if (course_instance.Learner.PaymentPeriod == 2)
                    {
                        invoice.LessonFee = invoice.LessonFee + extraFee;
                    }
                    invoice.LessonFee      = course_instance.Course.Price * lesson_quantity;
                    invoice.OwingFee       = invoice.LessonFee + invoice.NoteFee + invoice.ConcertFee;
                    invoice.TotalFee       = invoice.OwingFee;
                    invoice.LessonQuantity = lesson_quantity;
                    if (invoice.LessonFee <= 0)
                    {
                        continue;
                    }
                    _ablemusicContext.InvoiceWaitingConfirm.Update(invoice);
                    invoice.InvoiceNum = invoice.WaitingId.ToString();
                    _ablemusicContext.Update(courseIns);

                    await _ablemusicContext.SaveChangesAsync();

                    //i++;
                    //if (i == 4) break;
                }
                //result.Data = i;
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.Message;
                return(result);
            }
            return(result);
        }
Пример #14
0
        public async Task <IActionResult> PutInvoiceWaitingConfirm([FromBody] InvoiceWaitingConfirmViewModel invoiceWaitingConfirmViewModel)
        {
            var result = new Result <string>();
            InvoiceWaitingConfirm invoiceWaitingConfirm       = new InvoiceWaitingConfirm();
            InvoiceWaitingConfirm invoiceWaitingConfirmUpdate = new InvoiceWaitingConfirm();
            List <Invoice>        activeInvoices = new List <Invoice>();
            Invoice existInvoice = new Invoice();
            Learner learner      = new Learner();

            _mapper.Map(invoiceWaitingConfirmViewModel, invoiceWaitingConfirm);
            try
            {
                invoiceWaitingConfirmUpdate = await _ablemusicContext.InvoiceWaitingConfirm.
                                              Where(i => (i.InvoiceNum == invoiceWaitingConfirm.InvoiceNum && i.IsActivate == 1)).FirstOrDefaultAsync();

                activeInvoices = await _ablemusicContext.Invoice.Where(i => (i.IsActive == 1 || i.IsActive == null) && i.InvoiceNum == invoiceWaitingConfirm.InvoiceNum).ToListAsync();
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.IsFound      = false;
                result.ErrorMessage = ex.Message;
                return(NotFound(result));
            }

            if (invoiceWaitingConfirmUpdate == null)
            {
                result.IsSuccess    = false;
                result.IsFound      = false;
                result.ErrorMessage = "invoice waiting id not found";
                return(NotFound(result));
            }
            if (invoiceWaitingConfirmUpdate.IsActivate == 0)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "The provided invoice id is not active";
                return(BadRequest(result));
            }
            if (activeInvoices.Count > 0 && activeInvoices.FirstOrDefault().PaidFee > 0)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "The provided invoice is already paid";
                return(BadRequest(result));
            }

            invoiceWaitingConfirmUpdate.IsActivate = 0;
            invoiceWaitingConfirm.IsConfirmed      = 1;
            invoiceWaitingConfirm.WaitingId        = 0;
            invoiceWaitingConfirm.IsPaid           = 0;
            invoiceWaitingConfirm.IsActivate       = 1;
            invoiceWaitingConfirm.IsEmailSent      = 0;
            invoiceWaitingConfirm.CreatedAt        = toNZTimezone(DateTime.UtcNow);
            //for patch
            invoiceWaitingConfirm.EndDate = invoiceWaitingConfirmUpdate.EndDate;
            invoiceWaitingConfirm.DueDate = invoiceWaitingConfirmUpdate.DueDate;
            //
            Invoice invoice = new Invoice
            {
                InvoiceNum            = invoiceWaitingConfirm.InvoiceNum,
                LessonFee             = invoiceWaitingConfirm.LessonFee,
                ConcertFee            = invoiceWaitingConfirm.ConcertFee,
                NoteFee               = invoiceWaitingConfirm.NoteFee,
                Other1Fee             = invoiceWaitingConfirm.Other1Fee,
                Other2Fee             = invoiceWaitingConfirm.Other2Fee,
                Other3Fee             = invoiceWaitingConfirm.Other3Fee,
                LearnerId             = invoiceWaitingConfirm.LearnerId,
                LearnerName           = invoiceWaitingConfirm.LearnerName,
                BeginDate             = invoiceWaitingConfirm.BeginDate,
                EndDate               = invoiceWaitingConfirm.EndDate,
                TotalFee              = invoiceWaitingConfirm.TotalFee,
                DueDate               = invoiceWaitingConfirm.DueDate,
                PaidFee               = invoiceWaitingConfirm.PaidFee,
                OwingFee              = invoiceWaitingConfirm.OwingFee,
                CreatedAt             = invoiceWaitingConfirm.CreatedAt,
                IsPaid                = invoiceWaitingConfirm.IsPaid,
                TermId                = invoiceWaitingConfirm.TermId,
                CourseInstanceId      = invoiceWaitingConfirm.CourseInstanceId,
                GroupCourseInstanceId = invoiceWaitingConfirm.GroupCourseInstanceId,
                LessonQuantity        = invoiceWaitingConfirm.LessonQuantity,
                CourseName            = invoiceWaitingConfirm.CourseName,
                ConcertFeeName        = invoiceWaitingConfirm.ConcertFeeName,
                LessonNoteFeeName     = invoiceWaitingConfirm.LessonNoteFeeName,
                Other1FeeName         = invoiceWaitingConfirm.Other1FeeName,
                Other2FeeName         = invoiceWaitingConfirm.Other2FeeName,
                Other3FeeName         = invoiceWaitingConfirm.Other3FeeName,
                Comment               = invoiceWaitingConfirm.Comment,
                IsActive              = 1
            };

            if (activeInvoices.Count > 0)
            {
                foreach (var activeInvoice in activeInvoices)
                {
                    activeInvoice.IsActive = 0;
                }
            }

            try
            {
                await _ablemusicContext.SaveChangesAsync();

                await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoiceWaitingConfirm);

                await _ablemusicContext.Invoice.AddAsync(invoice);

                await _ablemusicContext.SaveChangesAsync();

                learner = await _ablemusicContext.Learner.Where(l => l.LearnerId == invoice.LearnerId).FirstOrDefaultAsync();

                if (learner == null)
                {
                    result.IsSuccess    = false;
                    result.IsFound      = false;
                    result.ErrorMessage = "learner not found";
                    return(NotFound(result));
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.Message;
                return(BadRequest(result));
            }

            var invoicePDFGeneratorService = new InvoicePDFGeneratorService(invoice, _log);

            invoicePDFGeneratorService.SavePDF();

            //sending Email
            string mailTitle             = "Invoice";
            string mailContent           = MailContentGenerator(invoiceWaitingConfirmUpdate);
            Task   learnerMailSenderTask = MailSenderService.SendMailUpdateInvoiceWaitingTableAsync(learner.Email, mailTitle, mailContent, invoiceWaitingConfirmUpdate.WaitingId);

            return(Ok(result));
        }
Пример #15
0
        private void AddToInvoice(Payment payment, string InvoiceNum)
        {
            long ii      = 0;
            var  today   = DateTime.UtcNow.ToNZTimezone();
            var  termIds = _ablemusicContext.Term.
                           Where(t => t.EndDate > today.Date).Select(t => t.TermId).ToList();

            if (termIds.Count == 0)
            {
                throw new Exception("Sorry, Can not find a term");
            }

            var invoice = new InvoiceWaitingConfirm();

            if (InvoiceNum != null)
            {
                invoice = _ablemusicContext.InvoiceWaitingConfirm.
                          FirstOrDefault(i => i.InvoiceNum == InvoiceNum &&
                                         i.IsActivate == 1 && i.IsConfirmed == 0);
            }
            else
            {
                invoice = _ablemusicContext.InvoiceWaitingConfirm.Where(i => termIds.Contains(i.TermId.Value)).
                          FirstOrDefault(i => i.LearnerId == payment.LearnerId &&
                                         i.IsActivate == 1 && i.IsConfirmed == 0);
            }

            if (invoice == null)
            {
                throw new Exception("Sorry, Can not find a draft invoice");
            }

            foreach (var tran in payment.SoldTransaction)
            {
                ii = getInvoiceItem(invoice);
                ii++;
                invoice.TotalFee += tran.DiscountedAmount;
                invoice.OwingFee += tran.DiscountedAmount;
                switch (ii)
                {
                case 1:
                    invoice.Other9Fee     = tran.DiscountedAmount;
                    invoice.Other9FeeName = tran.Product.ProductName;
                    break;

                case 2:
                    invoice.Other10Fee     = tran.DiscountedAmount;
                    invoice.Other10FeeName = tran.Product.ProductName;
                    break;

                case 3:
                    invoice.Other11Fee     = tran.DiscountedAmount;
                    invoice.Other11FeeName = tran.Product.ProductName;
                    break;

                case 4:
                    invoice.Other12Fee     = tran.DiscountedAmount;
                    invoice.Other12FeeName = tran.Product.ProductName;
                    break;

                case 5:
                    invoice.Other13Fee     = tran.DiscountedAmount;
                    invoice.Other13FeeName = tran.Product.ProductName;
                    break;

                default:
                    throw new Exception("You Can Buy More Than 5 Books at a Time");
                }
                _ablemusicContext.InvoiceWaitingConfirm.Update(invoice);
            }
        }
Пример #16
0
        public async Task <Result <IActionResult> > Generateone2oneInvoice(int term_id, int instance_id = 0)
        {
            var result = new Result <IActionResult>();

            try
            {
                //get concert fee configuraton
                var concertFeeName = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 15 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();;

                string concertFeeStr = _ablemusicContext.Lookup.
                                       Where(x => x.LookupType == 15 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int concertFee = Int32.Parse(concertFeeStr);
                //get note fee configuraton
                string noteFeeName = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 16 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                string noteFeeStr = _ablemusicContext.Lookup.
                                    Where(x => x.LookupType == 16 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int noteFee = Int32.Parse(noteFeeStr);
                //Aural Fee
                string auralFeeName = _ablemusicContext.Lookup.
                                      Where(x => x.LookupType == 19 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                string auralFeeStr = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 19 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int auralFee = Int32.Parse(auralFeeStr);
                //Theory Fee
                string theoryFeeName = _ablemusicContext.Lookup.
                                       Where(x => x.LookupType == 20 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                string theoryFeeStr = _ablemusicContext.Lookup.
                                      Where(x => x.LookupType == 20 && x.PropValue == 2).Select(x => x.PropName).FirstOrDefault();
                int theoryFee = Int32.Parse(theoryFeeStr);
                //get extra fee configuraton
                string extraFeeStr = _ablemusicContext.Lookup.
                                     Where(x => x.LookupType == 17 && x.PropValue == 1).Select(x => x.PropName).FirstOrDefault();
                int extraFee = Int32.Parse(extraFeeStr);

                var course_instances = await _ablemusicContext.One2oneCourseInstance
                                       .Include(x => x.Course)
                                       .Include(x => x.Learner).Where(x => x.Learner.IsActive == 1)
                                       .Select(x => new
                {
                    x.LearnerId,
                    x.CourseId,
                    x.CourseInstanceId,
                    x.BeginDate,
                    x.EndDate,
                    x.InvoiceDate,
                    Course = new
                    {
                        x.Course.CourseName,
                        x.Course.Price
                    },
                    Learner = new
                    {
                        x.Learner.FirstName,
                        x.Learner.PaymentPeriod
                    }
                })
                                       .ToListAsync();

                if (instance_id != 0)
                {
                    course_instances = course_instances.Where(x => x.CourseInstanceId == instance_id).ToList();
                }

                var term = await _ablemusicContext.Term.FirstOrDefaultAsync(x => x.TermId == term_id);

                var all_terms = await _ablemusicContext.Term.Select(x => new { x.TermId, x.BeginDate, x.EndDate }).ToListAsync();

                //int i = 0;
                foreach (var course_instance in course_instances)
                {
                    if (course_instance.InvoiceDate >= Convert.ToDateTime(term.EndDate))
                    {
                        continue;
                    }
                    if (course_instance.EndDate <= course_instance.InvoiceDate)
                    {
                        continue;                                                          //fix bug duplicated lessons
                    }
                    InvoiceWaitingConfirm invoice = new InvoiceWaitingConfirm();

                    invoice.LearnerId         = course_instance.LearnerId;
                    invoice.LearnerName       = course_instance.Learner.FirstName;
                    invoice.CourseInstanceId  = course_instance.CourseInstanceId;
                    invoice.CourseName        = course_instance.Course.CourseName;
                    invoice.ConcertFeeName    = concertFeeName;
                    invoice.ConcertFee        = concertFee;
                    invoice.LessonNoteFeeName = noteFeeName;
                    invoice.NoteFee           = noteFee;
                    invoice.Other2FeeName     = auralFeeName;
                    invoice.Other2Fee         = auralFee;
                    invoice.Other3FeeName     = theoryFeeName;
                    invoice.Other3Fee         = theoryFee;
                    invoice.TermId            = (short)term_id;
                    invoice.IsPaid            = 0;
                    invoice.PaidFee           = 0;
                    invoice.CreatedAt         = _today;
                    invoice.IsConfirmed       = 0;
                    invoice.IsActivate        = 1;
                    invoice.IsEmailSent       = 0;

                    int isExist = IsLearnerHasPayExtreFee(invoice.TermId, course_instance.LearnerId);
                    if (isExist == 1)
                    {
                        //invoice.ConcertFeeName = concertFeeName;
                        invoice.ConcertFee = 0;
                        //invoice.LessonNoteFeeName = noteFeeName;
                        invoice.NoteFee = 0;
                    }

                    var courseIns = await _ablemusicContext.One2oneCourseInstance.FirstOrDefaultAsync(x => x.CourseInstanceId == invoice.CourseInstanceId);

                    int lesson_quantity = 0;

                    if (course_instance.Learner.PaymentPeriod == 1 && (course_instance.InvoiceDate == null || course_instance.InvoiceDate < term.EndDate))
                    {
                        // if (course_instance.BeginDate >= term.BeginDate)
                        // {
                        //     invoice.BeginDate = course_instance.BeginDate;
                        // }
                        // else
                        // {
                        //     invoice.BeginDate = term.BeginDate;
                        // }
                        //get min begin date between booked course and term;
                        invoice.BeginDate = new DateTime(Math.Max(course_instance.BeginDate.Value.Ticks, term.BeginDate.Value.Ticks));

                        //if booked course have end date, get max end date between booked course and term;
                        if (course_instance.EndDate == null)
                        {
                            invoice.EndDate = term.EndDate;
                        }
                        else
                        {
                            invoice.EndDate = new DateTime(Math.Min(course_instance.EndDate.Value.Ticks, term.EndDate.Value.Ticks));
                        }

                        // save invoice for unified generating lessons read invocie.
                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoice);

                        await _ablemusicContext.SaveChangesAsync();

                        //using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
                        //{
                        //    lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                        //    dbContextTransaction.Rollback();

                        //}
                        lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);

                        courseIns.InvoiceDate = invoice.EndDate;
                    }
                    else if (course_instance.Learner.PaymentPeriod == 2)//for week billing cycle student
                    {
                        if (course_instance.InvoiceDate == null)
                        {
                            if (course_instance.BeginDate >= term.BeginDate)
                            {
                                invoice.BeginDate = course_instance.BeginDate;
                            }
                            else
                            {
                                invoice.BeginDate = term.BeginDate;
                            }
                            int DOW = day_trans(Convert.ToDateTime(invoice.BeginDate).DayOfWeek.ToString());

                            invoice.BeginDate = Convert.ToDateTime(invoice.BeginDate).AddDays(8 - DOW);
                            invoice.EndDate   = Convert.ToDateTime(invoice.BeginDate).AddDays(6);
                            if (course_instance.EndDate != null)
                            {
                                invoice.EndDate = new DateTime(Math.Min(invoice.EndDate.Value.Ticks, course_instance.EndDate.Value.Ticks));
                            }
                        }
                        else if (course_instance.EndDate == null || (course_instance.EndDate != null && course_instance.EndDate > course_instance.InvoiceDate))
                        {
                            invoice.BeginDate     = Convert.ToDateTime(courseIns.InvoiceDate).AddDays(1);
                            invoice.EndDate       = Convert.ToDateTime(invoice.BeginDate).AddDays(6);
                            courseIns.InvoiceDate = invoice.EndDate;
                        }
                        else
                        {
                            continue;
                        }
                        foreach (var all_term in all_terms)
                        {
                            if (invoice.EndDate >= all_term.BeginDate && invoice.EndDate <= all_term.EndDate)
                            {
                                invoice.TermId = all_term.TermId;
                            }
                        }

                        await _ablemusicContext.InvoiceWaitingConfirm.AddAsync(invoice);

                        await _ablemusicContext.SaveChangesAsync();

                        //using (var dbContextTransaction = _ablemusicContext.Database.BeginTransaction())
                        //{
                        //    lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                        //    dbContextTransaction.Rollback();

                        //}
                        lesson_quantity = await SaveLesson(invoice.WaitingId, 1, 1);
                    }
                    //if (invoice.BeginDate != null) invoice.DueDate = Convert.ToDateTime(invoice.BeginDate).AddDays(-1);
                    if (invoice.BeginDate == term.BeginDate)
                    {
                        invoice.DueDate = Convert.ToDateTime(invoice.BeginDate).AddDays(-21);
                    }
                    else
                    {
                        invoice.DueDate = Convert.ToDateTime(invoice.BeginDate).AddDays(7);
                    }
                    invoice.LessonFee = course_instance.Course.Price * lesson_quantity;
                    if (course_instance.Learner.PaymentPeriod == 2)
                    {
                        invoice.LessonFee = invoice.LessonFee + extraFee;
                    }
                    invoice.LessonFee = course_instance.Course.Price * lesson_quantity;
                    invoice.OwingFee  = invoice.LessonFee + invoice.NoteFee + invoice.ConcertFee
                                        + invoice.Other2Fee + invoice.Other3Fee; //Aural and Theory
                    invoice.TotalFee       = invoice.OwingFee;
                    invoice.LessonQuantity = lesson_quantity;
                    if (invoice.LessonFee <= 0)
                    {
                        continue;
                    }
                    UpdateInvoiceRegistFee(ref invoice);
                    _ablemusicContext.InvoiceWaitingConfirm.Update(invoice);
                    invoice.InvoiceNum = invoice.WaitingId.ToString();
                    _ablemusicContext.InvoiceWaitingConfirm.Update(invoice);
                    _ablemusicContext.Update(courseIns);

                    if (invoice.TotalFee == 0)
                    {
                        _ablemusicContext.InvoiceWaitingConfirm.Remove(invoice);
                    }
                    await _ablemusicContext.SaveChangesAsync();
                }
                //result.Data = i;
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.Message;
                return(result);
            }
            return(result);
        }