<commit_before>package gdrj

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
)

type LedgerSummary struct {
	orm.ModelBase                          `bson:"-" json:"-"`
	ID                                     string `bson:"_id"`
	PC                                     *ProfitCenter
	CC                                     *CostCenter
	PLModel                                *PLModel
	CompanyCode                            string
	LedgerAccount                          string
	Customer                               *Customer
	Product                                *Product
	Date                                   *Date
	PLGroup1, PLGroup2, PLGroup3, PLGroup4 string
	Value1, Value2, Value3                 float64
	//EasyForSelect
	PCID, CCID, OutletID, SKUID, PLCode, PLOrder string
	Month                                        time.Month
	Year                                         int
	Source                                       string
}

// month,year
func (s *LedgerSummary) RecordID() interface{} {
	return s.ID
	//return toolkit.Sprintf("%d_%d_%s_%s", s.Date.Year, s.Date.Month, s.CompanyCode, s.LedgerAccount)
}

func (s *LedgerSummary) PrepareID() interface{} {
	return toolkit.Sprintf("%d_%d_%s_%s_%s_%s_%s_%s_%s",
		s.Date.Year, s.Date.Month,
		s.CompanyCode, s.LedgerAccount,
		s.PLCode, s.OutletID, s.SKUID, s.PCID, s.CCID)
}

func (s *LedgerSummary) TableName() string {
	return "ledgersummariestemp" //"ledgersummaries"
}

func (s *LedgerSummary) PreSave() error {
	s.ID = s.PrepareID().(string)
	return nil
}

func GetUniqueBreakDown(breakdown string) []string {
	return nil
}

func LedgerSummaryGetDetailPivot(payload *DetailParam) ([]*LedgerSummary, error) {
	filters := []*dbox.Filter{
		dbox.Eq("plmodel.plheader1", payload.PLHeader1),
	}

	if payload.PLHeader2 != "" {
		filters = append(filters, dbox.Eq("plmodel.plheader2", payload.PLHeader2))
	}

	if payload.PLHeader3 != "" {
		filters = append(filters, dbox.Eq("plmodel.plheader3", payload.PLHeader3))
	}

	for _, each := range filters {
		fmt.Println("++++++", *each)
	}

	filter := dbox.And(payload.ParseFilter(), dbox.And(filters...))

	cursor, err := Find(new(LedgerSummary), filter, nil)
	if err != nil {
		return nil, err
	}

	result := []*LedgerSummary{}
	err = cursor.Fetch(&result, 0, false)
	if err != nil {
		return nil, err
	}
	cursor.Close()

	return result, nil
}

func GetLedgerSummaryByDetail(LedgerAccount, PCID, CCID, OutletID, SKUID string, Year int, Month time.Month) (ls *LedgerSummary) {
	ls = new(LedgerSummary)

	filter := dbox.And(dbox.Eq("month", Month),
		dbox.Eq("year", Year),
		dbox.Eq("ledgeraccount", LedgerAccount),
		dbox.Eq("pcid", PCID),
		dbox.Eq("ccid", CCID),
		dbox.Eq("outletid", OutletID),
		dbox.Eq("skuid", SKUID))

	cr, err := Find(new(LedgerSummary), filter, nil)
	if err != nil {
		return
	}

	_ = cr.Fetch(&ls, 1, false)
	cr.Close()

	return
}

func GetSalesHeaderList() (toolkit.Ms, error) {
	conn := DB().Connection
	q := conn.NewQuery().From(new(LedgerSummary).TableName())
	q = q.Group("plmodel.plheader1")
	c, e := q.Cursor(nil)
	if e != nil {
		return nil, errors.New("GetSalesHeaderList: Preparing cursor error " + e.Error())
	}
	defer c.Close()

	result := toolkit.Ms{}
	e = c.Fetch(&result, 0, false)
	if e != nil {
		return nil, errors.New("GetSalesHeaderList: Fetch cursor error " + e.Error())
	}

	return result, nil

}

func GetDecreasedQty() (toolkit.Ms, error) {
	result := toolkit.M{}
	results := toolkit.Ms{}
	results = append(results, result)
	ls := new(LedgerSummary)
	lsList := []*LedgerSummary{}
	quartal := toolkit.M{}
	// quartalList := toolkit.Ms{}

	cls, err := Find(new(LedgerSummary), nil, nil)
	if err != nil {
		return nil, errors.New("GetSalesHeaderList: Preparing cursor error " + err.Error())
	}

	defer cls.Close()

	for err = cls.Fetch(ls, 1, false); err == nil; {
		ls = new(LedgerSummary)
		lsList = append(lsList, ls)
		quartal.Set("product", ls.SKUID)
		quartal.Set("qty", ls.Value3)
		quartal.Set("year", ls.Year)
		switch {
		case ls.Month >= 1 && ls.Month <= 3:
			quartal.Set("quartal", "q1")
		case ls.Month >= 4 && ls.Month <= 6:
			quartal.Set("quartal", "q2")
		case ls.Month >= 7 && ls.Month <= 9:
			quartal.Set("quartal", "q3")
		case ls.Month >= 10 && ls.Month <= 12:
			quartal.Set("quartal", "q4")
		}
		err = cls.Fetch(ls, 1, false)
	}

	return results, nil
}

func GetIncreasedSales() (toolkit.Ms, error) {
	result := toolkit.M{}
	results := toolkit.Ms{}
	results = append(results, result)

	return results, nil
}

func CalculateLedgerSummaryAnalysisIdea(payload *PivotParam) ([]*toolkit.M, error) {
	var filter *dbox.Filter = payload.ParseFilter()

	conn := DB().Connection
	q := conn.NewQuery().From(new(LedgerSummary).TableName())
	q = q.Where(filter)
	q = q.Group("plmodel._id", "plmodel.orderindex", "plmodel.plheader1", "plmodel.plheader2", "plmodel.plheader3")
	q = q.Aggr(dbox.AggrSum, "$value1", "value1")

	c, e := q.Cursor(nil)
	if e != nil {
		return nil, errors.New("SummarizedLedgerSum: Preparing cursor error " + e.Error())<commit_msg>get decreased qty & increased sales<commit_after>package gdrj

import (
	"errors"
	"fmt"
	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
	"sort"
	"strings"
	"time"
)

type LedgerSummary struct {
	orm.ModelBase                          `bson:"-" json:"-"`
	ID                                     string `bson:"_id"`
	PC                                     *ProfitCenter
	CC                                     *CostCenter
	PLModel                                *PLModel
	CompanyCode                            string
	LedgerAccount                          string
	Customer                               *Customer
	Product                                *Product
	Date                                   *Date
	PLGroup1, PLGroup2, PLGroup3, PLGroup4 string
	Value1, Value2, Value3                 float64
	//EasyForSelect
	PCID, CCID, OutletID, SKUID, PLCode, PLOrder string
	Month                                        time.Month
	Year                                         int
	Source                                       string
}

// month,year
func (s *LedgerSummary) RecordID() interface{} {
	return s.ID
	//return toolkit.Sprintf("%d_%d_%s_%s", s.Date.Year, s.Date.Month, s.CompanyCode, s.LedgerAccount)
}

func (s *LedgerSummary) PrepareID() interface{} {
	return toolkit.Sprintf("%d_%d_%s_%s_%s_%s_%s_%s_%s",
		s.Date.Year, s.Date.Month,
		s.CompanyCode, s.LedgerAccount,
		s.PLCode, s.OutletID, s.SKUID, s.PCID, s.CCID)
}

func (s *LedgerSummary) TableName() string {
	return "ledgersummariestemp" //"ledgersummaries"
}

func (s *LedgerSummary) PreSave() error {
	s.ID = s.PrepareID().(string)
	return nil
}

func GetUniqueBreakDown(breakdown string) []string {
	return nil
}

func LedgerSummaryGetDetailPivot(payload *DetailParam) ([]*LedgerSummary, error) {
	filters := []*dbox.Filter{
		dbox.Eq("plmodel.plheader1", payload.PLHeader1),
	}

	if payload.PLHeader2 != "" {
		filters = append(filters, dbox.Eq("plmodel.plheader2", payload.PLHeader2))
	}

	if payload.PLHeader3 != "" {
		filters = append(filters, dbox.Eq("plmodel.plheader3", payload.PLHeader3))
	}

	for _, each := range filters {
		fmt.Println("++++++", *each)
	}

	filter := dbox.And(payload.ParseFilter(), dbox.And(filters...))

	cursor, err := Find(new(LedgerSummary), filter, nil)
	if err != nil {
		return nil, err
	}

	result := []*LedgerSummary{}
	err = cursor.Fetch(&result, 0, false)
	if err != nil {
		return nil, err
	}
	cursor.Close()

	return result, nil
}

func GetLedgerSummaryByDetail(LedgerAccount, PCID, CCID, OutletID, SKUID string, Year int, Month time.Month) (ls *LedgerSummary) {
	ls = new(LedgerSummary)

	filter := dbox.And(dbox.Eq("month", Month),
		dbox.Eq("year", Year),
		dbox.Eq("ledgeraccount", LedgerAccount),
		dbox.Eq("pcid", PCID),
		dbox.Eq("ccid", CCID),
		dbox.Eq("outletid", OutletID),
		dbox.Eq("skuid", SKUID))

	cr, err := Find(new(LedgerSummary), filter, nil)
	if err != nil {
		return
	}

	_ = cr.Fetch(&ls, 1, false)
	cr.Close()

	return
}

func GetSalesHeaderList() (toolkit.Ms, error) {
	conn := DB().Connection
	q := conn.NewQuery().From(new(LedgerSummary).TableName())
	q = q.Group("plmodel.plheader1")
	c, e := q.Cursor(nil)
	if e != nil {
		return nil, errors.New("GetSalesHeaderList: Preparing cursor error " + e.Error())
	}
	defer c.Close()

	result := toolkit.Ms{}
	e = c.Fetch(&result, 0, false)
	if e != nil {
		return nil, errors.New("GetSalesHeaderList: Fetch cursor error " + e.Error())
	}

	return result, nil

}

func GetDecreasedQty() (toolkit.Ms, error) {
	ls := new(LedgerSummary)
	lsList := []*LedgerSummary{}

	cls, err := Find(new(LedgerSummary), nil, nil)
	if err != nil {
		return nil, errors.New("GetDecreasedQty: Preparing cursor error " + err.Error())
	}

	defer cls.Close()

	for err = cls.Fetch(ls, 1, false); err == nil; {
		lsList = append(lsList, ls)
		ls = new(LedgerSummary)
		err = cls.Fetch(ls, 1, false)
	}

	product := toolkit.M{}
	for _, ledSum := range lsList {
		if ledSum.SKUID != "" {
			id := ledSum.SKUID + "_"
			switch {
			case ledSum.Month >= 1 && ledSum.Month <= 3:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q1"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value3)
				} else {
					product.Set(id, ledSum.Value3)
				}
			case ledSum.Month >= 4 && ledSum.Month <= 6:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q2"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value3)
				} else {
					product.Set(id, ledSum.Value3)
				}
			case ledSum.Month >= 7 && ledSum.Month <= 9:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q3"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value3)
				} else {
					product.Set(id, ledSum.Value3)
				}
			case ledSum.Month >= 10 && ledSum.Month <= 12:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q4"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value3)
				} else {
					product.Set(id, ledSum.Value3)
				}
			}
		}
	}

	var keys []string
	for k := range product {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	results := toolkit.Ms{}
	result := toolkit.M{}
	prevSKUID := ""
	var prevVal float64
	var isLess bool
	var listProd = []string{}
	var listVal = []float64{}
	for i, key := range keys {
		i++
		split := strings.Split(key, "_")
		listVal = append(listVal, product.GetFloat64(key))
		if prevSKUID == split[0] {
			if isLess == true {
				if prevVal < product.GetFloat64(key) {
					isLess = false
				} else {
					if i%8 == 0 {
						listProd = append(listProd, prevSKUID)
						result.Set(split[0], listVal)
						results = append(results, result)
					} else {
						prevVal = product.GetFloat64(key)
					}
				}
			}
		} else {
			listVal = []float64{}
			listVal = append(listVal, product.GetFloat64(key))
			prevVal = product.GetFloat64(key)
			prevSKUID = split[0]
			isLess = true
		}
	}
	return results, nil
}

func GetIncreasedSales() (toolkit.Ms, error) {
	ls := new(LedgerSummary)
	lsList := []*LedgerSummary{}

	cls, err := Find(new(LedgerSummary), nil, nil)
	if err != nil {
		return nil, errors.New("GetDecreasedQty: Preparing cursor error " + err.Error())
	}

	defer cls.Close()

	for err = cls.Fetch(ls, 1, false); err == nil; {
		lsList = append(lsList, ls)
		ls = new(LedgerSummary)
		err = cls.Fetch(ls, 1, false)
	}

	product := toolkit.M{}
	for _, ledSum := range lsList {
		if ledSum.SKUID != "" {
			id := ledSum.SKUID + "_"
			switch {
			case ledSum.Month >= 1 && ledSum.Month <= 3:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q1"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value1)
				} else {
					product.Set(id, ledSum.Value1)
				}
			case ledSum.Month >= 4 && ledSum.Month <= 6:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q2"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value1)
				} else {
					product.Set(id, ledSum.Value1)
				}
			case ledSum.Month >= 7 && ledSum.Month <= 9:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q3"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value1)
				} else {
					product.Set(id, ledSum.Value1)
				}
			case ledSum.Month >= 10 && ledSum.Month <= 12:
				id += toolkit.ToString(ledSum.Year) + "_" + "Q4"
				if product.Has(id) {
					product.Set(id, product.GetFloat64(id)+ledSum.Value1)
				} else {
					product.Set(id, ledSum.Value1)
				}
			}
		}
	}

	var keys []string
	for k := range product {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	results := toolkit.Ms{}
	result := toolkit.M{}
	prevSKUID := ""
	var prevVal float64
	var isGreater bool
	var listProd = []string{}
	var listVal = []float64{}
	for i, key := range keys {
		i++
		split := strings.Split(key, "_")
		listVal = append(listVal, product.GetFloat64(key))
		if prevSKUID == split[0] {
			if isGreater == true {
				if prevVal > product.GetFloat64(key) {
					isGreater = false
				} else {
					if i%8 == 0 {
						listProd = append(listProd, prevSKUID)
						result.Set(split[0], listVal)
						results = append(results, result)
					} else {
						prevVal = product.GetFloat64(key)
					}
				}
			}
		} else {
			listVal = []float64{}
			listVal = append(listVal, product.GetFloat64(key))
			prevVal = product.GetFloat64(key)
			prevSKUID = split[0]
			isGreater = true
		}
	}
	return results, nil
}

func CalculateLedgerSummaryAnalysisIdea(payload *PivotParam) ([]*toolkit.M, error) {
	var filter *dbox.Filter = payload.ParseFilter()

	conn := DB().Connection
	q := conn.NewQuery().From(new(LedgerSummary).TableName())
	q = q.Where(filter)
	q = q.Group("plmodel._id", "plmodel.orderindex", "plmodel.plheader1", "plmodel.plheader2", "plmodel.plheader3")
	q = q.Aggr(dbox.AggrSum, "$value1", "value1")

	c, e := q.Cursor(nil)
	if e != nil {
		return nil, errors.New("SummarizedLedgerSum: Preparing cursor error " + e.Error())
{'fraction_non_alphanumeric': 0.15472021725148288, 'fraction_numerical': 0.012649181733724004, 'mean_word_length': 2.8266338528848785, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5073081', 'n_tokens_mistral': 5692, 'n_tokens_neox': 5112, 'n_words': 1080}