예제 #1
0
func (c *Controller) AutoPayments() (string, error) {

	txType := "AutoPayments"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	var autoPayments []*autoPayment

	rows, err := c.Query(c.FormatQuery("SELECT id, amount, commission, currency_id, last_payment_time, period, sender, recipient FROM auto_payments WHERE sender = ? AND del_block_id = 0"), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var amount, commission float64
		var id, currency_id, last_payment_time, period, sender, recipient int64
		err = rows.Scan(&id, &amount, &commission, &currency_id, &last_payment_time, &period, &sender, &recipient)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		auto_ := &autoPayment{Id: id, Amount: amount, Commission: commission, Currency_id: currency_id, Last_payment_time: last_payment_time, Period: period, Sender: sender, Recipient: recipient}
		autoPayments = append(autoPayments, auto_)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"AutoPayments", "DelAutoPayment", "NewAutoPayment"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("auto_payments", "AutoPayments", &AutoPaymentsPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		CurrencyList:    c.CurrencyListCf,
		AutoPayments:    autoPayments,
		LastTxFormatted: lastTxFormatted})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #2
0
func (c *Controller) ArbitrationBuyer() (string, error) {

	log.Debug("ArbitrationBuyer")

	txType := "money_back_request"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myOrders, err := c.GetAll(`
			SELECT *
			FROM orders
			WHERE buyer = ?
			ORDER BY time DESC
			LIMIT 20
			`, 20, c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeSellerHoldBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("arbitration_buyer", "arbitrationBuyer", &arbitrationBuyerPage{
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MyOrders:        myOrders})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #3
0
func (c *Controller) PromisedAmountList() (string, error) {

	txType := "PromisedAmount"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewPromisedAmount", "ChangePromisedAmount", "DelPromisedAmount", "ForRepaidFix", "ActualizationPromisedAmounts", "Mining"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	limitsText := strings.Replace(c.Lang["change_commission_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_promised_amount"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_promised_amount_period"]], -1)

	actualizationPromisedAmounts, promisedAmountListAccepted, _, err := c.GetPromisedAmounts(c.SessUserId, c.Variables.Int64["cash_request_time"])
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	TemplateStr, err := makeTemplate("promised_amount_list", "promisedAmountList", &promisedAmountListPage{
		Alert:                        c.Alert,
		Lang:                         c.Lang,
		CountSignArr:                 c.CountSignArr,
		ShowSignData:                 c.ShowSignData,
		UserId:                       c.SessUserId,
		TimeNow:                      timeNow,
		TxType:                       txType,
		TxTypeId:                     txTypeId,
		SignData:                     "",
		LastTxFormatted:              lastTxFormatted,
		CurrencyList:                 c.CurrencyList,
		PromisedAmountListAccepted:   promisedAmountListAccepted,
		ActualizationPromisedAmounts: actualizationPromisedAmounts,
		LimitsText:                   limitsText})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #4
0
func (c *Controller) ChangeAvatar() (string, error) {

	txType := "UserAvatar"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"UserAvatar"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	data, err := c.OneRow("SELECT name, avatar FROM users WHERE user_id =  ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	avatar := data["avatar"]
	name := data["name"]

	TemplateStr, err := makeTemplate("change_avatar", "changeAvatar", &ChangeAvatarPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		Avatar:          avatar,
		Name:            name})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #5
0
func (c *Controller) HolidaysList() (string, error) {

	var err error

	var myHolidaysPending []map[string]string
	if c.SessRestricted == 0 {
		// те, что еще не попали в Dc-сеть
		myHolidaysPending, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_holidays ORDER BY id DESC`, -1)
	}

	myHolidaysAccepted, err := c.GetAll(`SELECT * FROM holidays WHERE user_id = ?`, -1, c.SessUserId)

	limitsText := strings.Replace(c.Lang["limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_holidays"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_holidays_period"]], -1)

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewHolidays"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("holidays_list", "holidaysList", &holidaysListPage{
		Alert:              c.Alert,
		Lang:               c.Lang,
		CountSignArr:       c.CountSignArr,
		ShowSignData:       c.ShowSignData,
		SignData:           "",
		LastTxFormatted:    lastTxFormatted,
		LimitsText:         limitsText,
		MyHolidaysPending:  myHolidaysPending,
		MyHolidaysAccepted: myHolidaysAccepted})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #6
0
func (c *Controller) ChangeArbitratorConditions() (string, error) {

	txType := "ChangeArbitratorConditions"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myCommission := make(map[int64][]float64)
	if c.SessRestricted == 0 {
		rows, err := c.Query(c.FormatQuery("SELECT currency_id, pct, min, max FROM " + c.MyPrefix + "my_commission"))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var pct, min, max float64
			var currency_id int64
			err = rows.Scan(&currency_id, &pct, &min, &max)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myCommission[currency_id] = []float64{pct, min, max}
		}
	}

	currencyList := c.CurrencyList
	commission := make(map[int64][]float64)
	for currency_id, _ := range currencyList {
		if len(myCommission[currency_id]) > 0 {
			commission[currency_id] = myCommission[currency_id]
		} else {
			commission[currency_id] = []float64{0.1, 0.01, 0}
		}
	}

	// для CF-проектов
	currencyList[1000] = "Crowdfunding"
	if len(myCommission[1000]) > 0 {
		commission[1000] = myCommission[1000]
	} else {
		commission[1000] = []float64{0.1, 0.01, 0}
	}
	arbitratorConditionsJson, err := c.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id  =  ?", c.SessUserId).Bytes()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	arbitratorConditionsMap_ := make(map[string][5]string)
	if len(arbitratorConditionsJson) > 0 {
		err = json.Unmarshal(arbitratorConditionsJson, &arbitratorConditionsMap_)
		// арбитр к этому моменту мог передумать и убрать свои условия, уйдя из арбитров для новых сделок поставив [0] что вызовет тут ошибку
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}
	arbitratorConditionsMap := make(map[int64][5]string)
	for k, v := range arbitratorConditionsMap_ {
		arbitratorConditionsMap[utils.StrToInt64(k)] = v
	}
	if len(arbitratorConditionsMap) == 0 {
		arbitratorConditionsMap[72] = [5]string{"0.01", "0", "0.01", "0", "0.1"}
		arbitratorConditionsMap[23] = [5]string{"0.01", "0", "0.01", "0", "0.1"}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("change_arbitrator_conditions", "changeArbitratorConditions", &changeArbitratorConditionsPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		CurrencyList:    c.CurrencyList,
		PendingTx:       pendingTx,
		LastTxFormatted: lastTxFormatted,
		Conditions:      arbitratorConditionsMap,
		Commission:      commission})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #7
0
func (c *Controller) CashRequestIn() (string, error) {

	txType := "CashRequestIn"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	cashRequestsStatus := map[string]string{"my_pending": c.Lang["local_pending"], "pending": c.Lang["pending"], "approved": c.Lang["approved"], "rejected": c.Lang["rejected"]}

	// Узнаем свой user_id
	userId, err := c.GetMyUserId(c.MyPrefix)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// актуальный запрос к нам на получение налички. Может быть только 1.
	actualData, err := c.OneRow(`
		SELECT `+c.MyPrefix+`my_cash_requests.cash_request_id,
					 `+c.MyPrefix+`my_cash_requests.id,
					 `+c.MyPrefix+`my_cash_requests.comment_status,
					 `+c.MyPrefix+`my_cash_requests.comment,
					 cash_requests.amount,
					 cash_requests.currency_id,
					 cash_requests.from_user_id,
					 hex(cash_requests.hash_code) as hash_code
		FROM `+c.MyPrefix+`my_cash_requests
		LEFT JOIN cash_requests ON cash_requests.id = `+c.MyPrefix+`my_cash_requests.cash_request_id
		WHERE cash_requests.to_user_id = ? AND
					 cash_requests.status = 'pending' AND
					 cash_requests.time > ? AND
					 cash_requests.del_block_id = 0 AND
					 cash_requests.for_repaid_del_block_id = 0
		ORDER BY cash_request_id DESC
		LIMIT 1`, userId, utils.Time()-c.Variables.Int64["cash_request_time"]).String()
	fmt.Println(`
		SELECT ` + c.MyPrefix + `my_cash_requests.cash_request_id,
					 ` + c.MyPrefix + `my_cash_requests.id,
					 ` + c.MyPrefix + `my_cash_requests.comment_status,
					 ` + c.MyPrefix + `my_cash_requests.comment,
					 cash_requests.amount,
					 cash_requests.currency_id,
					 cash_requests.from_user_id,
					 hex(cash_requests.hash_code) as hash_code
		FROM ` + c.MyPrefix + `my_cash_requests
		LEFT JOIN cash_requests ON cash_requests.id = ` + c.MyPrefix + `my_cash_requests.cash_request_id
		WHERE cash_requests.to_user_id = ` + utils.Int64ToStr(userId) + ` AND
					 cash_requests.status = 'pending' AND
					 cash_requests.time > ` + utils.Int64ToStr(utils.Time()-c.Variables.Int64["cash_request_time"]) + ` AND
					 cash_requests.del_block_id = 0 AND
					 cash_requests.for_repaid_del_block_id = 0
		ORDER BY cash_request_id DESC
		LIMIT 1`)
	if len(actualData) > 0 {
		actualData["hash_code"] = strings.ToLower(actualData["hash_code"])
	}
	// список ранее отправленных ответов на запросы.
	myCashRequests, err := c.GetAll("SELECT * FROM "+c.MyPrefix+"my_cash_requests WHERE to_user_id = ?", -1, userId)

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"CashRequestIn"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("cash_request_in", "cashRequestIn", &CashRequestInPage{
		Alert:              c.Alert,
		Lang:               c.Lang,
		CountSignArr:       c.CountSignArr,
		ShowSignData:       c.ShowSignData,
		UserId:             userId,
		TimeNow:            timeNow,
		TxType:             txType,
		TxTypeId:           txTypeId,
		SignData:           "",
		CurrencyList:       c.CurrencyList,
		CashRequestsStatus: cashRequestsStatus,
		MyCashRequests:     myCashRequests,
		LastTxFormatted:    lastTxFormatted,
		ActualData:         actualData})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #8
0
func (c *Controller) ArbitrationSeller() (string, error) {

	log.Debug("ArbitrationSeller")

	txType := "ChangeSellerHoldBack"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	holdBack, err := c.OneRow("SELECT arbitration_days_refund, seller_hold_back_pct FROM users WHERE user_id  =  ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	myOrders, err := c.GetAll("SELECT id, time, amount, seller, status, comment_status, comment	FROM orders	WHERE seller = ? ORDER BY time DESC LIMIT 20", 20, c.SessUserId)
	for k, data := range myOrders {
		if data["status"] == "refund" {
			if c.SessRestricted == 0 {
				data_, err := c.OneRow("SELECT comment, comment_status FROM "+c.MyPrefix+"my_comments WHERE id  =  ? AND type  =  'seller'", data["id"]).String()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				data["status"] = data_["comment"]
				data["comment_status"] = data_["comment_status"]
			}
		}
		myOrders[k] = data
	}

	var shopData map[string]string
	if c.SessRestricted == 0 {
		shopData, err = c.OneRow("SELECT shop_secret_key, shop_callback_url FROM " + c.MyPrefix + "my_table").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeSellerHoldBack", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("arbitration_seller", "arbitrationSeller", &arbitrationSellerPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MinerId:         c.MinerId,
		PendingTx:       pendingTx,
		MyOrders:        myOrders,
		SessRestricted:  c.SessRestricted,
		ShopData:        shopData,
		HoldBack:        holdBack})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #9
0
파일: new_user.go 프로젝트: dzyk/dcoin-go
func (c *Controller) NewUser() (string, error) {

	txType := "NewUser"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	param := utils.ParamType{X: 176, Y: 100, Width: 100, Bg_path: "static/img/k_bg.png"}

	refPhotos := make(map[int64][]string)
	myRefsKeys := make(map[int64]map[string]string)
	if c.SessRestricted == 0 {
		join := c.MyPrefix + `my_new_users.user_id`
		if c.ConfigIni["db_type"] == "sqlite" || c.ConfigIni["db_type"] == "postgresql" {
			join = `"` + c.MyPrefix + `my_new_users".user_id`
		}
		rows, err := c.Query(c.FormatQuery(`
				SELECT users.user_id,	private_key,  log_id
				FROM ` + c.MyPrefix + `my_new_users
				LEFT JOIN users ON users.user_id = ` + join + `
				WHERE status = 'approved'
				`))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var user_id, log_id int64
			var private_key string
			err = rows.Scan(&user_id, &private_key, &log_id)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			// проверим, не сменил ли уже юзер свой ключ
			StrUserId := utils.Int64ToStr(user_id)
			if log_id != 0 {
				myRefsKeys[user_id] = map[string]string{"user_id": StrUserId}
			} else {
				myRefsKeys[user_id] = map[string]string{"user_id": StrUserId, "private_key": private_key}
				md5 := string(utils.Md5(private_key))
				kPath := *utils.Dir + "/public/" + md5[0:16]
				kPathPng := kPath + ".png"
				kPathTxt := kPath + ".txt"
				if _, err := os.Stat(kPathPng); os.IsNotExist(err) {
					privKey := strings.Replace(private_key, "-----BEGIN RSA PRIVATE KEY-----", "", -1)
					privKey = strings.Replace(privKey, "-----END RSA PRIVATE KEY-----", "", -1)
					_, err = utils.KeyToImg(privKey, kPathPng, user_id, c.TimeFormat, param)
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					err := ioutil.WriteFile(kPathTxt, []byte(privKey), 0644)
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					/*$gd = key_to_img($private_key, $param, $row['user_id']);
					imagepng($gd, $k_path_png);
					file_put_contents($k_path_txt, trim($private_key));*/
				}
			}
		}
	}

	refs := make(map[int64]map[int64]float64)
	// инфа по рефам юзера
	rows, err := c.Query(c.FormatQuery(`
			SELECT referral, sum(amount) as amount, currency_id
			FROM referral_stats
			WHERE user_id = ?
			GROUP BY currency_id,  referral
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var referral, currency_id int64
		var amount float64
		err = rows.Scan(&referral, &amount, &currency_id)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		refs[referral] = map[int64]float64{currency_id: amount}
	}

	myRefsAmounts := make(map[int64]myRefsType)
	for refUserId, refData := range refs {
		data, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", refUserId).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// получим ID майнеров, у которых лежат фото нужного нам юзера
		if len(data) == 0 {
			continue
		}
		minersIds := utils.GetMinersKeepers(data["photo_block_id"], data["photo_max_miner_id"], data["miners_keepers"], true)
		if len(minersIds) > 0 {
			hosts, err := c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myRefsAmounts[refUserId] = myRefsType{Amounts: refData, Hosts: hosts}
			refPhotos[refUserId] = hosts
		}
	}
	myRefs := make(map[int64]myRefsType)
	for refUserId, refData := range myRefsAmounts {
		myRefs[refUserId] = refData
	}
	for refUserId, refData := range myRefsKeys {
		md5 := string(utils.Md5(refData["private_key"]))
		myRefs[refUserId] = myRefsType{Key: refData["private_key"], KeyUrl: c.NodeConfig["pool_url"] + "public/" + md5[0:16]}
	}

	/*
	 * Общая стата по рефам
	 */
	globalRefs := make(map[int64]globalRefsType)
	// берем лидеров по USD
	rows, err = c.Query(c.FormatQuery(`
			SELECT user_id, sum(amount) as amount
			FROM referral_stats
			WHERE currency_id = 72
			GROUP BY user_id
			ORDER BY amount DESC
			`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var user_id int64
		var amount float64
		err = rows.Scan(&user_id, &amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// вся прибыль с рефов у данного юзера
		refAmounts, err := c.GetAll(`
				SELECT ROUND(sum(amount)) as amount,  currency_id
				FROM referral_stats
				WHERE user_id = ?
				GROUP BY currency_id
				`, -1, user_id)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		data, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", user_id).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// получим ID майнеров, у которых лежат фото нужного нам юзера
		minersIds := utils.GetMinersKeepers(data["photo_block_id"], data["photo_max_miner_id"], data["miners_keepers"], true)
		hosts, err := c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		globalRefs[user_id] = globalRefsType{Amounts: refAmounts, Hosts: hosts}
		refPhotos[user_id] = hosts
	}

	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewUser"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
	}

	TemplateStr, err := makeTemplate("new_user", "newUser", &newUserPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		MyRefs:          myRefs,
		GlobalRefs:      globalRefs,
		CurrencyList:    c.CurrencyList,
		RefPhotos:       refPhotos,
		PoolUrl:         c.NodeConfig["pool_url"]})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #10
0
func (c *Controller) ArbitrationArbitrator() (string, error) {

	log.Debug("ArbitrationArbitrator")

	txType := "MoneyBackRequest"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myOrders, err := c.GetAll(`
			SELECT *
			FROM orders
			WHERE (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 status = 'refund'
			ORDER BY time DESC
			LIMIT 20
	`, 20, c.SessUserId, c.SessUserId, c.SessUserId, c.SessUserId, c.SessUserId)
	for k, data := range myOrders {
		if c.SessRestricted == 0 {
			data_, err := c.OneRow(`
						SELECT comment,
									 comment_status
						FROM `+c.MyPrefix+`my_comments
						WHERE id = ? AND
									 type = 'arbitrator'
						LIMIT 1
				`, data["id"]).String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			data["comment"] = data_["comment"]
			data["comment_status"] = data_["comment_status"]
		} else {
			data["comment"] = ""
			data["comment_status"] = "decrypted"
		}
		myOrders[k] = data
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("arbitration_arbitrator", "arbitrationArbitrator", &arbitrationArbitratorPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MinerId:         c.MinerId,
		MyOrders:        myOrders})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #11
0
func (c *Controller) ChangePrimaryKey() (string, error) {

	var err error

	txType := "ChangePrimaryKey"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	var myKeys []map[string]string
	if c.SessRestricted == 0 {
		myKeys, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_keys ORDER BY id DESC`, -1)
	}

	statusArray := map[string]string{"my_pending": c.Lang["local_pending"], "approved": c.Lang["status_approved"]}

	// узнаем, когда последний раз была смена ключа, чтобы не показывать юзеру страницу смены
	lastChangeKeyTime, err := c.Single("SELECT time FROM log_time_primary_key WHERE user_id  =  ? ORDER BY time DESC", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	limitsText := strings.Replace(c.Lang["change_primary_key_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_primary_key"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_primary_key_period"]], -1)

	var lastTxQueueTx, lastTxTx bool
	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangePrimaryKey"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
		if len(lastTx[0]["queue_tx"]) > 0 {
			lastTxQueueTx = true
		}
		if len(lastTx[0]["tx"]) > 0 {
			lastTxTx = true
		}
	}

	TemplateStr, err := makeTemplate("change_primary_key", "changePrimaryKey", &changePrimaryKeyPage{
		Alert:             c.Alert,
		Lang:              c.Lang,
		ShowSignData:      c.ShowSignData,
		SignData:          "",
		UserId:            c.SessUserId,
		CountSignArr:      c.CountSignArr,
		LimitsText:        limitsText,
		LastTxQueueTx:     lastTxQueueTx,
		LastTxTx:          lastTxTx,
		LastTxFormatted:   lastTxFormatted,
		LastChangeKeyTime: lastChangeKeyTime,
		LastTx:            lastTx,
		MyKeys:            myKeys,
		StatusArray:       statusArray,
		TimeNow:           timeNow,
		TxType:            txType,
		IOS:               utils.IOS(),
		Android:           utils.Android(),
		Mobile:            utils.Mobile(),
		TxTypeId:          txTypeId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #12
0
파일: voting.go 프로젝트: dzyk/dcoin-go
func (c *Controller) Voting() (string, error) {

	txType := "VotesComplex"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	waitVoting := make(map[int64]string)
	promisedAmountCurrencyList := make(map[int64]map[string]string)

	// голосовать майнер может только после того, как пройдет  miner_newbie_time сек
	regTime, err := c.Single("SELECT reg_time FROM miners_data WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	minerNewbie := ""
	if regTime > utils.Time()-c.Variables.Int64["miner_newbie_time"] && c.SessUserId != 1 {
		minerNewbie = strings.Replace(c.Lang["hold_time_wait2"], "[sec]", utils.TimeLeft(c.Variables.Int64["miner_newbie_time"]-(utils.Time()-regTime), c.Lang), -1)
	} else {
		// валюты
		rows, err := c.Query(c.FormatQuery(`
				SELECT currency_id,
							  name,
							  full_name,
							  start_time
				FROM promised_amount
					LEFT JOIN currency ON currency.id = promised_amount.currency_id
				WHERE user_id = ? AND
							 status IN ('mining', 'repaid') AND
							 start_time > 0 AND
							 del_block_id = 0
				GROUP BY currency_id
				`), c.SessUserId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var currency_id, start_time int64
			var name, full_name string
			err = rows.Scan(&currency_id, &name, &full_name, &start_time)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			// после добавления обещанной суммы должно пройти не менее min_hold_time_promise_amount сек, чтобы за неё можно было голосовать
			if start_time > utils.Time()-c.Variables.Int64["min_hold_time_promise_amount"] {
				waitVoting[currency_id] = strings.Replace(c.Lang["hold_time_wait"], "[sec]", utils.TimeLeft(c.Variables.Int64["min_hold_time_promise_amount"]-(utils.Time()-start_time), c.Lang), -1)
				continue
			}
			// если по данной валюте еще не набралось >1000 майнеров, то за неё голосовать нельзя.
			countMiners, err := c.Single(`
					SELECT count(user_id)
					FROM promised_amount
					WHERE start_time < ? AND
								 del_block_id = 0 AND
								 status IN ('mining', 'repaid') AND
								 currency_id = ? AND
								 del_block_id = 0
					GROUP BY  user_id
					`, utils.Time()-c.Variables.Int64["min_hold_time_promise_amount"], currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if countMiners < c.Variables.Int64["min_miners_of_voting"] {
				waitVoting[currency_id] = strings.Replace(c.Lang["min_miners_count"], "[miners_count]", utils.Int64ToStr(c.Variables.Int64["min_miners_of_voting"]), -1)
				waitVoting[currency_id] = strings.Replace(waitVoting[currency_id], "[remaining]", utils.Int64ToStr(c.Variables.Int64["min_miners_of_voting"]-countMiners), -1)
				continue
			}
			// голосовать можно не чаще 1 раза в 2 недели
			voteTime, err := c.Single("SELECT time FROM log_time_votes_complex WHERE user_id  =  ? AND time > ?", c.SessUserId, utils.Time()-c.Variables.Int64["limit_votes_complex_period"]).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if voteTime > 0 {
				waitVoting[currency_id] = strings.Replace(c.Lang["wait_voting"], "[sec]", utils.TimeLeft(c.Variables.Int64["limit_votes_complex_period"]-(utils.Time()-voteTime), c.Lang), -1)
				continue
			}

			// получим наши предыдущие голоса
			votesUserPct, err := c.Single("SELECT pct FROM votes_user_pct WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMinerPct, err := c.Single("SELECT pct FROM votes_miner_pct WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMaxOtherCurrencies, err := c.Single("SELECT count FROM votes_max_other_currencies WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMaxPromisedAmount, err := c.Single("SELECT amount FROM votes_max_promised_amount WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			promisedAmountCurrencyList[currency_id] = make(map[string]string)
			promisedAmountCurrencyList[currency_id]["votes_user_pct"] = utils.Int64ToStr(votesUserPct)
			promisedAmountCurrencyList[currency_id]["votes_miner_pct"] = utils.Int64ToStr(votesMinerPct)
			promisedAmountCurrencyList[currency_id]["votes_max_other_currencies"] = utils.Int64ToStr(votesMaxOtherCurrencies)
			promisedAmountCurrencyList[currency_id]["votes_max_promised_amount"] = utils.Int64ToStr(votesMaxPromisedAmount)
			promisedAmountCurrencyList[currency_id]["name"] = name
		}
	}

	referral, err := c.OneRow("SELECT first, second, third FROM votes_referral WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(referral) == 0 {
		referral["first"] = int64(utils.RandInt(0, 30))
		referral["second"] = int64(utils.RandInt(0, 30))
		referral["third"] = int64(utils.RandInt(0, 30))
	}

	maxCurrencyId, err := c.Single("SELECT max(id) FROM currency").Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	allMaxPromisedAmount := []int64{1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000, 20000000, 50000000, 100000000, 200000000, 500000000, 1000000000}

	allPct := utils.GetPctArray()
	pctArray := utils.GetPctArray()
	jsPct := "{"
	for year, sec := range pctArray {
		jsPct += fmt.Sprintf(`%v: '%v',`, year, sec)
	}
	jsPct = jsPct[:len(jsPct)-1] + "}"

	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"VotesComplex"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
	}

	refs := []string{"first", "second", "third"}
	refsNums := []int{0, 5, 10, 15, 20, 25, 30}

	TemplateStr, err := makeTemplate("voting", "voting", &VotingPage{
		Alert:                      c.Alert,
		Lang:                       c.Lang,
		CountSignArr:               c.CountSignArr,
		ShowSignData:               c.ShowSignData,
		UserId:                     c.SessUserId,
		TimeNow:                    timeNow,
		TxType:                     txType,
		TxTypeId:                   txTypeId,
		SignData:                   "",
		PromisedAmountCurrencyList: promisedAmountCurrencyList,
		MaxOtherCurrenciesCount:    []int{0, 1, 2, 3, 4},
		RefsNums:                   refsNums,
		Referral:                   referral,
		MinerNewbie:                minerNewbie,
		MaxCurrencyId:              maxCurrencyId,
		AllMaxPromisedAmount:       allMaxPromisedAmount,
		AllPct:                     allPct,
		LastTxFormatted:            lastTxFormatted,
		WaitVoting:                 waitVoting,
		CurrencyList:               c.CurrencyList,
		JsPct:                      jsPct,
		Refs:                       refs})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #13
0
func (c *Controller) MiningMenu() (string, error) {

	var err error
	log.Debug("first_select: %v", c.Parameters["first_select"])
	if c.Parameters["first_select"] == "1" {
		c.ExecSql(`UPDATE ` + c.MyPrefix + `my_table SET first_select=1`)
	}
	if len(c.Parameters["skip_promised_amount"]) > 0 {
		err = c.ExecSql("UPDATE " + c.MyPrefix + "my_table SET hide_first_promised_amount = 1")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}
	if len(c.Parameters["skip_commission"]) > 0 {
		err = c.ExecSql("UPDATE " + c.MyPrefix + "my_table SET hide_first_commission = 1")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	var result string
	checkCommission := func() error {
		// установлена ли комиссия
		commission, err := c.Single("SELECT commission FROM commission WHERE user_id  =  ?", c.SessUserId).String()
		if err != nil {
			return utils.ErrInfo(err)
		}
		if len(commission) == 0 {
			// возможно юзер уже отправил запрос на добавление комиссии
			last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeCommission"}), 1, c.TimeFormat)
			if err != nil {
				return utils.ErrInfo(err)
			}
			if len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0) {
				// авансом выдаем полное майнерское меню
				result = "full_mining_menu"
			} else {
				// возможно юзер нажал кнопку "пропустить"
				hideFirstCommission, err := c.Single("SELECT hide_first_commission FROM " + c.MyPrefix + "my_table").Int64()
				if err != nil {
					return utils.ErrInfo(err)
				}
				if hideFirstCommission == 0 {
					result = "need_commission"
				} else {
					result = "full_mining_menu"
				}
			}
		} else {
			result = "full_mining_menu"
		}
		return nil
	}

	hostTpl := ""
	// чтобы при добавлении общенных сумм, смены комиссий редиректило сюда
	navigate := "miningMenu"
	if c.SessRestricted != 0 {
		result = "need_email"
	} else {
		myMinerId, err := c.Single("SELECT miner_id FROM miners_data WHERE user_id  =  ?", c.SessUserId).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if myMinerId == 0 {
			// проверим, послали ли мы запрос в DC-сеть
			data, err := c.OneRow("SELECT node_voting_send_request, http_host as host FROM " + c.MyPrefix + "my_table").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			node_voting_send_request := utils.StrToInt64(data["node_voting_send_request"])
			host := data["host"]
			// если прошло менее 1 часа
			if time.Now().Unix()-node_voting_send_request < 3600 {
				result = "pending"
			} else if node_voting_send_request > 0 {
				// голосование нодов
				nodeVotesEnd, err := c.Single("SELECT votes_end FROM votes_miners WHERE user_id  =  ? AND type  =  'node_voting' ORDER BY id DESC", c.SessUserId).String()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				if nodeVotesEnd == "1" { // голосование нодов завершено
					userVotesEnd, err := c.Single("SELECT votes_end FROM votes_miners WHERE user_id  =  ? AND type  =  'user_voting' ORDER BY id DESC", c.SessUserId).String()
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					if userVotesEnd == "1" { // юзерское голосование закончено
						result = "bad"
					} else if userVotesEnd == "0" { // идет юзерское голосование
						result = "users_pending"
					} else {
						result = "bad_photos_hash"
						hostTpl = host
					}
				} else if nodeVotesEnd == "0" && time.Now().Unix()-node_voting_send_request < 86400 { // голосование нодов началось, ждем.
					result = "nodes_pending"
				} else if nodeVotesEnd == "0" && time.Now().Unix()-node_voting_send_request >= 86400 { // голосование нодов удет более суток и еще не завершилось
					result = "resend"
				} else { // запрос в DC-сеть еще не дошел и голосования не начались
					// если прошло менее 1 часа
					if time.Now().Unix()-node_voting_send_request < 3600 {
						result = "pending"
					} else { // где-то проблема и запрос не ушел.
						result = "resend"
					}
				}
			} else { // запрос на получение статуса "майнер" мы еще не слали
				result = "null"
			}
		} else {

			// установлены ли уведомления
			smtpUserName, err := c.Single("SELECT smtp_username FROM " + c.MyPrefix + "my_table").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if len(smtpUserName) == 0 {
				result = "need_notifications"
			} else {
				// добавлена ли обещанная сумма
				promisedAmount, err := c.Single("SELECT id FROM promised_amount WHERE user_id  =  ?", c.SessUserId).Int64()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				if promisedAmount == 0 {
					// возможно юзер уже отправил запрос на добавление обещенной суммы
					last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewPromisedAmount"}), 1, c.TimeFormat)
					if len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0) {
						// установлена ли комиссия
						err = checkCommission()
						if err != nil {
							return "", utils.ErrInfo(err)
						}
					} else {
						// возможно юзер нажал кнопку "пропустить"
						hideFirstPromisedAmount, err := c.Single("SELECT hide_first_promised_amount FROM " + c.MyPrefix + "my_table").Int64()
						if err != nil {
							return "", utils.ErrInfo(err)
						}
						if hideFirstPromisedAmount == 0 {
							result = "need_promised_amount"
						} else {
							err = checkCommission()
							if err != nil {
								return "", utils.ErrInfo(err)
							}
						}
					}
				} else {
					// установлена ли комиссия
					err = checkCommission()
					if err != nil {
						return "", utils.ErrInfo(err)
					}
				}
			}
		}
	}

	var minerVotesAttempt int64
	var myComments []map[string]string
	c.Navigate = navigate
	lastTxFormatted := ""
	tplName := ""
	tplTitle := ""
	log.Debug(">result:", result)
	var nodePrivateKey string
	if result == "null" {
		tplName = "upgrade_0"
		tplTitle = "upgrade0"
		return c.Upgrade0()
	} else if result == "need_email" {
		tplName = "sign_up_in_the_pool"
		tplTitle = "signUpInThePool"
		//  сгенерим ключ для нода
		nodePrivateKey, _ = utils.GenKeys()
	} else if result == "need_notifications" {
		tplName = "notifications"
		tplTitle = "notifications"
		return c.Notifications()
	} else if result == "need_promised_amount" {
		tplName = "promised_amount_add"
		tplTitle = "upgrade"
		return c.NewPromisedAmount()
	} else if result == "need_commission" {
		tplName = "change_commission"
		tplTitle = "changeCommission"
		return c.ChangeCommission()
	} else if result == "full_mining_menu" {
		tplName = "mining_menu"
		tplTitle = "miningMenu"
		last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewUser", "NewMiner", "NewPromisedAmount", "ChangePromisedAmount", "VotesMiner", "ChangeGeolocation", "VotesPromisedAmount", "DelPromisedAmount", "CashRequestOut", "CashRequestIn", "VotesComplex", "ForRepaidFix", "NewHolidays", "ActualizationPromisedAmounts", "Mining", "NewMinerUpdate", "ChangeHost", "ChangeCommission"}), 3, c.TimeFormat)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(last_tx) > 0 {
			lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
		}
	} else {
		// сколько у нас осталось попыток стать майнером.
		countAttempt, err := c.CountMinerAttempt(c.SessUserId, "user_voting")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		minerVotesAttempt = c.Variables.Int64["miner_votes_attempt"] - countAttempt

		// комментарии проголосовавших
		myComments, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_comments WHERE comment != 'null' AND type NOT IN ('arbitrator','seller')`, -1)
		tplName = "upgrade"
		tplTitle = "upgrade"
	}

	log.Debug("tplName, tplTitle %v, %v", tplName, tplTitle)
	TemplateStr, err := makeTemplate(tplName, tplTitle, &miningMenuPage{
		Alert:             c.Alert,
		Lang:              c.Lang,
		CountSignArr:      c.CountSignArr,
		ShowSignData:      c.ShowSignData,
		UserId:            c.SessUserId,
		SignData:          "",
		CurrencyList:      c.CurrencyList,
		LastTxFormatted:   lastTxFormatted,
		MyComments:        myComments,
		Result:            result,
		NodePrivateKey:    nodePrivateKey,
		MinerVotesAttempt: minerVotesAttempt,
		Mobile:            utils.Mobile(),
		Host:              hostTpl})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #14
0
func (c *Controller) ChangeCommission() (string, error) {

	txType := "ChangeCommission"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	navigate := "changeCommission"
	if len(c.Navigate) > 0 {
		navigate = c.Navigate
	}

	minCommission := map[string]string{"WOC": "0.01", "AED": "0.04", "AOA": "0.96", "ARS": "0.06", "AUD": "0.01", "AZN": "0.01", "BDT": "0.78", "BGN": "0.01", "BOB": "0.07", "BRL": "0.02", "BYR": "89.25", "CAD": "0.01", "CHF": "0.01", "CLP": "5.13", "CNY": "0.06", "COP": "19.11", "CRC": "4.98", "CZK": "0.19", "DKK": "0.06", "DOP": "0.42", "DZD": "0.81", "EGP": "0.07", "EUR": "0.01", "GBP": "0.01", "GEL": "0.02", "GHS": "0.02", "GTQ": "0.08", "HKD": "0.08", "HRK": "0.06", "HUF": "2.25", "IDR": "103.85", "ILS": "0.04", "INR": "0.62", "IQD": "11.64", "IRR": "999.99", "JOD": "0.01", "JPY": "0.98", "KES": "0.87", "KRW": "11.14", "KWD": "0.01", "KZT": "1.53", "LBP": "15.11", "LKR": "1.32", "MAD": "0.08", "MXN": "0.13", "MYR": "0.03", "NGN": "1.61", "NOK": "0.06", "NPR": "0.98", "NZD": "0.01", "PEN": "0.03", "PHP": "0.44", "PKR": "1.03", "PLN": "0.03", "QAR": "0.04", "RON": "0.03", "RSD": "0.85", "RUB": "0.33", "SAR": "0.04", "SDG": "0.04", "SEK": "0.07", "SGD": "0.01", "SVC": "0.09", "SYP": "1.08", "THB": "0.31", "TND": "0.02", "TRY": "0.02", "TWD": "0.30", "TZS": "16.19", "UAH": "0.08", "UGX": "25.79", "USD": "0.01", "UZS": "21.15", "VEF": "0.06", "VND": "210.95", "YER": "2.15", "ZAR": "0.10", "BTC": "0.01", "LTC": "0.01"}

	currencyMin := make(map[int64]string)
	for id, name := range c.CurrencyList {
		currencyMin[id] = minCommission[name]
	}

	myCommission := make(map[int64][]float64)
	if c.SessRestricted == 0 {
		rows, err := c.Query(c.FormatQuery("SELECT currency_id, pct, min, max FROM " + c.MyPrefix + "my_commission"))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var pct, min, max float64
			var currency_id int64
			err = rows.Scan(&currency_id, &pct, &min, &max)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myCommission[currency_id] = []float64{pct, min, max}
		}
	}

	currencyList := c.CurrencyList
	commission := make(map[int64][]float64)
	for currency_id, _ := range currencyList {
		if len(myCommission[currency_id]) > 0 {
			commission[currency_id] = myCommission[currency_id]
		} else {
			commission[currency_id] = []float64{0.1, utils.StrToFloat64(currencyMin[currency_id]), 0}
		}
	}

	// для CF-проектов
	currencyList[1000] = "Crowdfunding"
	if len(myCommission[1000]) > 0 {
		commission[1000] = myCommission[1000]
	} else {
		commission[1000] = []float64{0.1, 0.01, 0}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	//limitsText := strings.Replace(c.Lang["change_commission_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_commission"]), -1)
	//limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_commission_period"]], -1)

	log.Debug("commission:", commission)

	TemplateStr, err := makeTemplate("change_commission", "changeCommission", &changeCommissionPage{
		Alert:            c.Alert,
		Lang:             c.Lang,
		CountSignArr:     c.CountSignArr,
		ShowSignData:     c.ShowSignData,
		UserId:           c.SessUserId,
		TimeNow:          timeNow,
		TxType:           txType,
		TxTypeId:         txTypeId,
		SignData:         "",
		LastTxFormatted:  lastTxFormatted,
		CurrencyList:     c.CurrencyList,
		ConfigCommission: c.ConfigCommission,
		Navigate:         navigate,
		Commission:       commission})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #15
0
func (c *Controller) WalletsList() (string, error) {

	var err error

	// валюты
	currencyList := c.CurrencyListCf

	confirmedBlockId := c.ConfirmedBlockId

	var wallets []utils.DCAmounts
	var myDcTransactions []map[string]string
	if c.SessUserId > 0 {
		wallets, err = c.GetBalances(c.SessUserId)
		if c.SessRestricted == 0 {
			myDcTransactions, err = c.GetAll("SELECT * FROM "+c.MyPrefix+"my_dc_transactions ORDER BY id DESC LIMIT 100", 100)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			for id, data := range myDcTransactions {
				t := time.Unix(utils.StrToInt64(data["time"]), 0)
				timeFormatted := t.Format(c.TimeFormat)
				log.Debug("timeFormatted", utils.StrToInt64(data["time"]), timeFormatted, c.TimeFormat)
				myDcTransactions[id]["timeFormatted"] = timeFormatted
				myDcTransactions[id]["numBlocks"] = "0"
				blockId := utils.StrToInt64(data["block_id"])
				if blockId > 0 {
					myDcTransactions[id]["numBlocks"] = utils.Int64ToStr(confirmedBlockId - blockId)
				}
			}
		}
	}
	userType := "SendDc"
	projectType := "CfSendDc"
	userTypeId := utils.TypeInt(userType)
	projectTypeId := utils.TypeInt(projectType)
	timeNow := time.Now().Unix()
	currentBlockId, err := c.GetBlockId()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	names := make(map[string]string)
	names["cash_request"] = c.Lang["cash"]
	names["from_mining_id"] = c.Lang["from_mining"]
	names["from_repaid"] = c.Lang["from_repaid_mining"]
	names["from_user"] = c.Lang["from_user"]
	names["node_commission"] = c.Lang["node_commission"]
	names["system_commission"] = c.Lang["system_commission"]
	names["referral"] = c.Lang["referral"]
	names["cf_project"] = "Crowd funding"
	names["cf_project_refund"] = "Crowd funding refund"

	minerId, err := c.GetMinerId(c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	c.r.ParseForm()
	// если юзер кликнул по кнопку "профинансировать" со страницы проекта
	//parameters := c.r.FormValue("parameters")
	cfProjectId := int64(utils.StrToFloat64(c.Parameters["projectId"]))

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"SendDc"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}
	arbitrationTrustList_, err := c.GetMap(`
			SELECT arbitrator_user_id,
					 	conditions
			FROM arbitration_trust_list
			LEFT JOIN arbitrator_conditions ON arbitrator_conditions.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ?
	`, "arbitrator_user_id", "conditions", c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	arbitrationTrustList := make(map[int64]map[int64][]string)
	var jsonMap map[string][]string
	for arbitrator_user_id, conditions := range arbitrationTrustList_ {
		err = json.Unmarshal([]byte(conditions), &jsonMap)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		uidInt := utils.StrToInt64(arbitrator_user_id)
		arbitrationTrustList[uidInt] = make(map[int64][]string)
		for currenycId, data := range jsonMap {
			arbitrationTrustList[uidInt][utils.StrToInt64(currenycId)] = data
		}
	}
	log.Debug("arbitrationTrustList", arbitrationTrustList)

	TemplateStr, err := makeTemplate("wallets_list", "walletsList", &walletsListPage{
		CountSignArr:         c.CountSignArr,
		CfProjectId:          cfProjectId,
		Names:                names,
		UserIdStr:            utils.Int64ToStr(c.SessUserId),
		Alert:                c.Alert,
		Community:            c.Community,
		ConfigCommission:     c.ConfigCommission,
		ProjectType:          projectType,
		UserType:             userType,
		UserId:               c.SessUserId,
		Lang:                 c.Lang,
		CurrencyList:         currencyList,
		Wallets:              wallets,
		MyDcTransactions:     myDcTransactions,
		UserTypeId:           userTypeId,
		ProjectTypeId:        projectTypeId,
		Time:                 timeNow,
		CurrentBlockId:       currentBlockId,
		ConfirmedBlockId:     confirmedBlockId,
		MinerId:              minerId,
		Config:               c.NodeConfig,
		LastTxFormatted:      lastTxFormatted,
		ArbitrationTrustList: arbitrationTrustList,
		ShowSignData:         c.ShowSignData,
		SignData:             ""})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #16
0
func (c *Controller) CurrencyExchange() (string, error) {

	txType := "NewForexOrder"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	addSql := ""
	if len(c.Parameters["all_currencies"]) == 0 {
		// по умолчанию выдаем только те валюты, которые есть хоть у кого-то на кошельках
		actualCurrencies, err := c.GetList("SELECT currency_id FROM wallets GROUP BY currency_id").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(actualCurrencies) > 0 {
			addSql = " WHERE id IN (" + strings.Join(actualCurrencies, ",") + ")"
		}
	}
	currencyListName := make(map[int64]string)
	currency, err := c.GetMap("SELECT id, name FROM currency "+addSql+" ORDER BY name", "id", "name")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for k, v := range currency {
		currencyListName[utils.StrToInt64(k)] = v
	}

	var sellCurrencyId, buyCurrencyId int64
	if len(c.Parameters["buy_currency_id"]) > 0 {
		buyCurrencyId = utils.StrToInt64(c.Parameters["buy_currency_id"])
		c.sess.Set("buy_currency_id", buyCurrencyId)
	}
	if len(c.Parameters["sell_currency_id"]) > 0 {
		sellCurrencyId = utils.StrToInt64(c.Parameters["sell_currency_id"])
		c.sess.Set("sell_currency_id", sellCurrencyId)
	}
	if buyCurrencyId == 0 {
		buyCurrencyId = GetSessInt64("buy_currency_id", c.sess)
	}
	if sellCurrencyId == 0 {
		sellCurrencyId = GetSessInt64("sell_currency_id", c.sess)
	}
	if buyCurrencyId == 0 {
		buyCurrencyId = 1
	}
	if sellCurrencyId == 0 {
		sellCurrencyId = 72
	}

	buyCurrencyName := currencyListName[buyCurrencyId]
	sellCurrencyName := currencyListName[sellCurrencyId]

	// валюты
	currencyListFullName, err := c.GetCurrencyListFullName()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	buyOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE  buy_currency_id =  ? AND
						 sell_currency_id = ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, buyCurrencyId, sellCurrencyId)

	sellOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE  buy_currency_id =  ? AND
						 sell_currency_id = ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, sellCurrencyId, buyCurrencyId)

	myOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE user_id =  ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, c.SessUserId)

	rows, err := c.Query(c.FormatQuery(`
			SELECT amount, currency_id, last_update
			FROM wallets
			WHERE user_id = ? AND
						currency_id IN (?, ?)
			`), c.SessUserId, sellCurrencyId, buyCurrencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	walletsAmounts := make(map[int64]float64)
	for rows.Next() {
		var amount float64
		var currency_id, last_update int64
		err = rows.Scan(&amount, &currency_id, &last_update)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		profit, err := c.CalcProfitGen(currency_id, amount, c.SessUserId, last_update, timeNow, "wallets")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		amount += profit
		amount = utils.Round(amount, 2)
		forex_orders_amount, err := c.Single("SELECT sum(amount) FROM forex_orders WHERE user_id = ? AND sell_currency_id = ? AND del_block_id = 0", c.SessUserId, currency_id).Float64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		amount -= forex_orders_amount
		walletsAmounts[currency_id] = amount
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewForexOrder", "DelForexOrder"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("currency_exchange", "currencyExchange", &currencyExchangePage{
		LastTxFormatted:      lastTxFormatted,
		Lang:                 c.Lang,
		CountSignArr:         c.CountSignArr,
		ShowSignData:         c.ShowSignData,
		WalletsAmounts:       walletsAmounts,
		CurrencyListName:     currencyListName,
		BuyCurrencyId:        buyCurrencyId,
		SellCurrencyId:       sellCurrencyId,
		BuyCurrencyName:      buyCurrencyName,
		SellCurrencyName:     sellCurrencyName,
		CurrencyListFullName: currencyListFullName,
		ConfigCommission:     c.ConfigCommission,
		TimeNow:              timeNow,
		SellOrders:           sellOrders,
		BuyOrders:            buyOrders,
		MyOrders:             myOrders,
		UserId:               c.SessUserId,
		TxType:               txType,
		TxTypeId:             txTypeId,
		SignData:             ""})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
예제 #17
0
func (c *Controller) Arbitration() (string, error) {

	txType := "ChangeArbitratorList"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	var q string
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ? AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id, url
			ORDER BY count(arbitration_trust_list.user_id)  DESC`
	} else {
		q = `SELECT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ? AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id
			ORDER BY count(arbitration_trust_list.user_id)  DESC`
	}
	myTrustList, err := c.GetAll(q, 100, c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	var arbitrators []*arbitrationType
	// top 10 арбитров
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN miners_data ON miners_data.user_id = arbitration_trust_list.user_id
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE miners_data.status='miner' AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id, url
			ORDER BY count(arbitration_trust_list.user_id)  DESC
			LIMIT 10`
	} else {
		q = `SELECT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN miners_data ON miners_data.user_id = arbitration_trust_list.user_id
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE miners_data.status='miner' AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id
			ORDER BY count(arbitration_trust_list.user_id)  DESC
			LIMIT 10`
	}
	rows, err := c.Query(c.FormatQuery(q))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		//var pct, amount float64
		var arbitrator_user_id, count int64
		var url string
		err = rows.Scan(&arbitrator_user_id, &url, &count)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// кол-во манибеков и сумма за последний месяц
		refund_data, err := c.OneRow(`
			SELECT count(id) as count, sum(refund) as sum
			FROM orders
			LEFT JOIN miners_data ON miners_data.user_id = orders.buyer
			WHERE (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 orders.status = 'refund' AND
						 arbitrator_refund_time > ? AND
						 arbitrator_refund_time < ? AND
						 miners_data.status = 'miner'
			GROUP BY user_id
		`, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, timeNow-3600*24*30, timeNow).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// кол-во неудовлетвореных манибеков за последний месяц
		count_rejected_refunds, err := c.Single(`
			SELECT count(id)
			FROM orders
			LEFT JOIN miners_data ON miners_data.user_id = orders.buyer
			WHERE  (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 orders.status = 'refund' AND
						 end_time > ? AND
						 end_time < ? AND
						 voluntary_refund = 0 AND
						 refund = 0 AND
						 miners_data.status = 'miner'
			GROUP BY user_id
		`, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, timeNow-3600*24*30, timeNow).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		log.Debug("utils.StrToInt64(refund_data[count])", utils.StrToInt64(refund_data["count"]))
		log.Debug("utils.StrToInt64(refund_data[sum])", utils.StrToInt64(refund_data["sum"]))

		arbitrators = append(arbitrators, &arbitrationType{Arbitrator_user_id: arbitrator_user_id, Url: url, Count: count, Refund_data_count: utils.StrToInt64(refund_data["count"]), Refund_data_sum: utils.StrToFloat64(refund_data["sum"]), Count_rejected_refunds: count_rejected_refunds})

	}

	// арбитр ли наш юзер
	arbitrator, err := c.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// продавец ли
	arbitrationDaysRefund, err := c.Single("SELECT arbitration_days_refund FROM users WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	arbitrationTrustList, err := c.Single("SELECT arbitrator_user_id FROM arbitration_trust_list WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorList", "ChangeArbitratorConditions", "ChangeSellerHoldBack", "ChangeSellerHoldBack", "MoneyBackRequest", "MoneyBack", "ChangeMoneyBackTime"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("arbitration", "arbitration", &arbitrationPage{
		Alert:                 c.Alert,
		Lang:                  c.Lang,
		CountSignArr:          c.CountSignArr,
		ShowSignData:          c.ShowSignData,
		UserId:                c.SessUserId,
		TimeNow:               timeNow,
		TxType:                txType,
		TxTypeId:              txTypeId,
		SignData:              "",
		Arbitrators:           arbitrators,
		MyTrustList:           myTrustList,
		PendingTx:             pendingTx,
		Arbitrator:            arbitrator,
		ArbitrationDaysRefund: arbitrationDaysRefund,
		LastTxFormatted:       lastTxFormatted,
		ArbitrationTrustList:  arbitrationTrustList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}