Example #1
0
func (c *Controller) EWithdraw() (string, error) {

	if c.SessUserId == 0 {
		return "", errors.New(c.Lang["sign_up_please"])
	}

	c.r.ParseForm()
	currencyId := utils.StrToInt64(c.r.FormValue("currency_id"))
	if !utils.CheckInputData(c.r.FormValue("amount"), "amount") {
		return "", fmt.Errorf("incorrect amount")
	}
	method := c.r.FormValue("method")
	if !utils.CheckInputData(method, "method") {
		return "", fmt.Errorf("incorrect method")
	}
	account := c.r.FormValue("account")
	if !utils.CheckInputData(account, "account") {
		return "", fmt.Errorf("incorrect account")
	}
	amount := utils.StrToFloat64(c.r.FormValue("amount"))

	curTime := utils.Time()

	// нужно проверить, есть ли нужная сумма на счету юзера
	userAmount := utils.EUserAmountAndProfit(c.SessUserId, currencyId)
	if userAmount < amount {
		return "", fmt.Errorf("%s (%f<%f)", c.Lang["not_enough_money"], userAmount, amount)
	}
	if method != "Dcoin" && currencyId < 1000 {
		return "", fmt.Errorf("incorrect method")
	}

	err := userLock(c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	err = c.ExecSql(`UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = ? AND currency_id = ?`, userAmount-amount, curTime, c.SessUserId, currencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	var commission float64
	if method == "Dcoin" {
		commission = utils.StrToFloat64(c.EConfig["dc_commission"])
	} else if method == "Perfect-money" {
		commission = utils.StrToFloat64(c.EConfig["pm_commission"])
	}
	wdAmount := utils.ClearNull(utils.Float64ToStr(amount*(1-commission/100)), 2)

	err = c.ExecSql(`INSERT INTO e_withdraw (open_time, user_id, currency_id, account, amount, wd_amount, method) VALUES (?, ?, ?, ?, ?, ?, ?)`, curTime, c.SessUserId, currencyId, account, amount, wdAmount, method)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	userUnlock(c.SessUserId)

	return utils.JsonAnswer(c.Lang["request_is_created"], "success").String(), nil
}
Example #2
0
func (c *Controller) ESaveOrder() (string, error) {

	if c.SessUserId == 0 {
		return "", errors.New(c.Lang["sign_up_please"])
	}
	c.r.ParseForm()
	sellCurrencyId := utils.StrToInt64(c.r.FormValue("sell_currency_id"))
	buyCurrencyId := utils.StrToInt64(c.r.FormValue("buy_currency_id"))
	amount := utils.StrToFloat64(c.r.FormValue("amount"))
	sellRate := utils.StrToFloat64(c.r.FormValue("sell_rate"))
	orderType := c.r.FormValue("type")
	// можно ли торговать такими валютами
	checkCurrency, err := c.Single("SELECT count(id) FROM e_currency WHERE id IN (?, ?)", sellCurrencyId, buyCurrencyId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if checkCurrency != 2 {
		return "", errors.New("Currency error")
	}
	if orderType != "sell" && orderType != "buy" {
		return "", errors.New("Type error")
	}
	if amount == 0 {
		return "", errors.New(c.Lang["amount_error"])
	}
	if amount < 0.001 && sellCurrencyId < 1000 {
		return "", errors.New(strings.Replace(c.Lang["save_order_min_amount"], "[amount]", "0.001", -1))
	}
	if sellRate < 0.0001 {
		return "", errors.New(strings.Replace(c.Lang["save_order_min_price"], "[price]", "0.0001", -1))
	}
	reductionLock, err := utils.EGetReductionLock()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if reductionLock > 0 {
		return "", errors.New(strings.Replace(c.Lang["creating_orders_unavailable"], "[minutes]", "30", -1))
	}

	// нужно проверить, есть ли нужная сумма на счету юзера
	userAmountAndProfit := utils.EUserAmountAndProfit(c.SessUserId, sellCurrencyId)
	if userAmountAndProfit < amount {
		return "", errors.New(c.Lang["not_enough_money"] + " (" + utils.Float64ToStr(userAmountAndProfit) + "<" + utils.Float64ToStr(amount) + ")" + strings.Replace(c.Lang["add_funds_link"], "[currency]", "USD", -1))
	}

	err = NewForexOrder(c.SessUserId, amount, sellRate, sellCurrencyId, buyCurrencyId, orderType, utils.StrToMoney(c.EConfig["commission"]))
	if err != nil {
		return "", utils.ErrInfo(err)
	} else {
		return utils.JsonAnswer(c.Lang["order_created"], "success").String(), nil
	}

	return ``, nil
}
Example #3
0
func (p *Parser) NewPromisedAmount() error {
	addSqlNames := ""
	addSqlValues := ""
	if p.BlockData.BlockId > 27134 {
		paymentSystemsIds := strings.Split(string(p.TxMaps.String["payment_systems_ids"]), ",")
		for i, v := range paymentSystemsIds {
			addSqlNames += fmt.Sprintf("ps%d,", (i + 1))
			addSqlValues += fmt.Sprintf("%s,", v)
		}
	}

	//добавляем promised_amount в БД
	err := p.ExecSql(`
				INSERT INTO promised_amount (
						user_id,
						amount,
						currency_id,
						` + addSqlNames + `
						video_type,
						video_url_id,
						votes_start_time
					)
					VALUES (
						` + utils.Int64ToStr(p.TxMaps.Int64["user_id"]) + `,
						` + utils.Float64ToStr(p.TxMaps.Money["amount"]) + `,
						` + utils.Int64ToStr(p.TxMaps.Int64["currency_id"]) + `,
						` + addSqlValues + `
						'` + p.TxMaps.String["video_type"] + `',
						'` + p.TxMaps.String["video_url_id"] + `',
						` + utils.Int64ToStr(p.BlockData.Time) + `
					)`)
	if err != nil {
		return p.ErrInfo(err)
	}

	// проверим, не наш ли это user_id
	myUserId, myBlockId, myPrefix, _, err := p.GetMyUserId(p.TxMaps.Int64["user_id"])
	if err != nil {
		return err
	}
	if p.TxUserID == myUserId && myBlockId <= p.BlockData.BlockId {
		// Удалим, т.к. попало в блок
		err = p.ExecSql("DELETE FROM "+myPrefix+"my_promised_amount WHERE amount = ? AND currency_id = ?", p.TxMaps.Money["amount"], p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
	}

	return nil
}
Example #4
0
func (c *Controller) getMyWallets() ([]map[string]string, error) {
	var myWallets []map[string]string
	eCurrency, err := c.GetAll(`SELECT name as currency_name, id FROM e_currency ORDER BY sort_id ASC`, -1)
	if err != nil {
		return myWallets, utils.ErrInfo(err)
	}
	for _, data := range eCurrency {
		wallet, err := c.OneRow("SELECT * FROM e_wallets WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, data["id"]).String()
		if err != nil {
			return myWallets, utils.ErrInfo(err)
		}
		if len(wallet) > 0 {
			amount := utils.StrToFloat64(wallet["amount"])
			profit, err := utils.DB.CalcProfitGen(utils.StrToInt64(wallet["currency_id"]), amount, 0, utils.StrToInt64(wallet["last_update"]), utils.Time(), "wallet")
			if err != nil {
				return myWallets, utils.ErrInfo(err)
			}
			myWallets = append(myWallets, map[string]string{"amount": utils.ClearNull(utils.Float64ToStr(amount+profit), 2), "currency_name": data["currency_name"], "last_update": wallet["last_update"]})
		}
	}

	return myWallets, nil
}
Example #5
0
func (c *Controller) EMain() (string, error) {

	var err error

	dcCurrencyId := utils.StrToInt64(c.Parameters["dc_currency_id"])
	currencyId := utils.StrToInt64(c.Parameters["currency_id"])
	if dcCurrencyId == 0 {
		dcCurrencyId = 72
	}
	if currencyId == 0 {
		currencyId = 1001
	}

	// все валюты, с которыми работаем
	currencyList, err := utils.EGetCurrencyList()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	log.Debug("%v", currencyList)

	// работаем только с теми валютами, которые есть у нас в списке
	if len(currencyList[dcCurrencyId]) == 0 || len(currencyList[currencyId]) == 0 {
		return "", utils.ErrInfo("incorrect currency")
	}

	// пары валют для меню
	currencyListPair, err := eGetCurrencyPair()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	dcCurrency := currencyList[dcCurrencyId]
	currency := currencyList[currencyId]

	// история сделок
	var tradeHistory []map[string]string

	rows, err := c.Query(c.FormatQuery(`
			SELECT sell_currency_id, sell_rate, amount, time
			FROM e_trade
			WHERE ((sell_currency_id = ? AND buy_currency_id = ?) OR (sell_currency_id = ? AND buy_currency_id = ?)) AND main = 1
			ORDER BY time DESC
			LIMIT 40
			`), dcCurrencyId, currencyId, currencyId, dcCurrencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var sellCurrencyId, eTime int64
		var sellRate, amount float64
		err = rows.Scan(&sellCurrencyId, &sellRate, &amount, &eTime)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		var eType string
		var eAmount float64
		var eTotal float64
		if sellCurrencyId == dcCurrencyId {
			eType = "sell"
			sellRate = 1 / sellRate
			eAmount = amount
			eTotal = amount * sellRate
		} else {
			eType = "buy"
			eAmount = amount * (1 / sellRate)
			eTotal = amount
		}
		t := time.Unix(eTime, 0)
		tradeHistory = append(tradeHistory, map[string]string{"Time": t.Format(c.TimeFormat), "Type": eType, "SellRate": utils.ClearNull(utils.Float64ToStr(sellRate), 4), "Amount": utils.ClearNull(utils.Float64ToStr(eAmount), 4), "Total": utils.ClearNull(utils.Float64ToStr(eTotal), 4)})
	}

	// активные ордеры на продажу
	var orders eOrders
	rows, err = c.Query(c.FormatQuery(`
			SELECT sell_rate, amount
			FROM e_orders
			WHERE (sell_currency_id = ? AND buy_currency_id = ?) AND
						empty_time = 0 AND
						del_time = 0 AND
						amount > 0
			ORDER BY sell_rate DESC
			LIMIT 100
			`), dcCurrencyId, currencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	// мин. цена покупки
	var buyMin float64
	for rows.Next() {
		var sellRate, amount float64
		err = rows.Scan(&sellRate, &amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if orders.Sell == nil {
			orders.Sell = make(map[float64]float64)
		}
		sellRate = utils.ClearNullFloat64(1/sellRate, 6)
		orders.Sell[sellRate] = utils.ClearNullFloat64(orders.Sell[sellRate]+amount, 6)
		if buyMin == 0 {
			buyMin = sellRate
		} else if sellRate < buyMin {
			buyMin = sellRate
		}
	}

	keys := []float64{}
	for k := range orders.Sell {
		keys = append(keys, k)
	}
	sort.Float64s(keys)
	var eOrdersSell []map[string]float64
	for _, k := range keys {
		eOrdersSell = append(eOrdersSell, map[string]float64{"sell_rate": k, "amount": orders.Sell[k]})
	}

	// активные ордеры на покупку
	rows, err = c.Query(c.FormatQuery(`
			SELECT sell_rate, amount
			FROM e_orders
			WHERE (sell_currency_id = ? AND buy_currency_id = ?) AND
					empty_time = 0 AND
					del_time = 0 AND
					amount > 0
			ORDER BY sell_rate ASC
			LIMIT 100
			`), currencyId, dcCurrencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	// мин. цена продажи
	var sellMax float64
	for rows.Next() {
		var sellRate, amount float64
		err = rows.Scan(&sellRate, &amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if orders.Buy == nil {
			orders.Buy = make(map[float64]float64)
		}
		sellRate = utils.ClearNullFloat64(sellRate, 6)
		orders.Buy[sellRate] = utils.ClearNullFloat64(orders.Buy[sellRate]+amount*(1/sellRate), 6)
		if sellMax == 0 {
			sellMax = sellRate
		} else if sellRate < sellMax {
			sellMax = sellRate
		}
	}
	var keysR sort.Float64Slice
	for k := range orders.Buy {
		keysR = append(keysR, k)
	}
	sort.Sort(sort.Reverse(keysR))
	var eOrdersBuy []map[string]float64
	for _, k := range keysR {
		eOrdersBuy = append(eOrdersBuy, map[string]float64{"sell_rate": k, "amount": orders.Buy[k]})
	}

	// комиссия
	commission := c.EConfig["commission"]
	commissionText := strings.Replace(c.Lang["commission_text"], "[commission]", commission, -1)

	// кол-во юзеров
	members, err := c.Single(`SELECT count(*) FROM e_users`).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	TemplateStr, err := makeTemplate("e_main", "eMain", &eMainPage{
		Lang:             c.Lang,
		Commission:       commission,
		Members:          members,
		SellMax:          sellMax,
		BuyMin:           buyMin,
		EOrdersSell:      eOrdersSell,
		EOrdersBuy:       eOrdersBuy,
		DcCurrency:       dcCurrency,
		Currency:         currency,
		DcCurrencyId:     dcCurrencyId,
		UserId:           c.SessUserId,
		TradeHistory:     tradeHistory,
		CurrencyId:       currencyId,
		CommissionText:   commissionText,
		CurrencyListPair: currencyListPair,
		CurrencyList:     currencyList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #6
0
func (c *Controller) EMyFinance() (string, error) {

	var err error

	if c.SessUserId == 0 {
		return `<script language="javascript"> window.location.href = "` + c.EURL + `"</script>If you are not redirected automatically, follow the <a href="` + c.EURL + `">` + c.EURL + `</a>`, nil
	}

	confirmations := c.EConfig["confirmations"]

	currencyList, err := utils.EGetCurrencyList()

	// счет, куда юзеры должны слать DC
	mainDcAccount := c.EConfig["main_dc_account"]

	currency := make(map[string]map[string]string)

	// валюты, по которым идут торги на бирже
	//var myWallets []map[string]string
	eCurrency, err := c.GetAll(`SELECT name, id FROM e_currency ORDER BY sort_id ASC`, -1)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for _, data := range eCurrency {
		wallet, err := c.OneRow("SELECT * FROM e_wallets WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, data["id"]).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(wallet) > 0 {
			amount := utils.StrToFloat64(wallet["amount"])
			profit, err := utils.DB.CalcProfitGen(utils.StrToInt64(wallet["currency_id"]), amount, 0, utils.StrToInt64(wallet["last_update"]), utils.Time(), "wallet")
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			wallet["amount"] = utils.Float64ToStr(amount + profit)
		} else {
			wallet["amount"] = "0"
		}

		currency[data["id"]] = make(map[string]string)
		currency[data["id"]]["amount"] = wallet["amount"]
		currency[data["id"]]["name"] = data["name"]
		if utils.StrToInt64(data["id"]) < 1000 { //DC
			currency[data["id"]]["input"] = strings.Replace(c.Lang["dc_deposit_text"], "[dc_currency]", data["name"], -1)
			currency[data["id"]]["input"] = strings.Replace(currency[data["id"]]["input"], "[account]", mainDcAccount, -1)
			currency[data["id"]]["input"] = strings.Replace(currency[data["id"]]["input"], "[user_id]", utils.Int64ToStr(c.SessUserId), -1)
			currency[data["id"]]["input"] = strings.Replace(currency[data["id"]]["input"], "[confirmations]", confirmations, -1)
		}

		currency[data["id"]]["output"] = `<div class="pull-left"><h4>` + c.Lang["withdraw0"] + ` ` + data["name"] + `</h4>
			<table class="table_out">
			<tbody>
			<tr>
			<td>` + c.Lang["your_dcoin_account"] + `:</td>
			<td class="form-inline"><input id="account-` + data["id"] + `" class="form-control col-xs-3" type="text"></td>
			</tr>
			<tr>
			<td>` + c.Lang["amount_to_withdrawal"] + `:</td>
			<td class="form-inline" style="line-height: 35px"><input id="amount-` + data["id"] + `" class="form-control col-xs-3" maxlength="15" type="text"  onkeyup="calc_withdraw_amount(` + data["id"] + `, '0.1')" onchange="calc_withdraw_amount(` + data["id"] + `, '0.1')" style="margin-right:5px"> ` + data["name"] + `</td>
			</tr>
			<tr>
			<td>` + c.Lang["you_will_receive"] + `:</td>
			<td class="form-inline" style="line-height: 35px"><input  disabled="" id="withdraw_amount-` + data["id"] + `" class="form-control col-xs-3" maxlength="15" type="text" style="margin-right:5px"> ` + data["name"] + `</td>
			</tr>
			</tbody></table><div id="alerts-` + data["id"] + `"></div><button class="btn btn-outline btn-primary" onclick="withdraw(` + data["id"] + `, 'Dcoin')">` + c.Lang["withdrawal"] + `</button>
			</div><div class="pull-left" style="margin-left:30px; margin-top:43px; border-left: 4px solid #ccc; padding:7px 7px; width:400px">`
		dcWithdrawText := strings.Replace(c.Lang["dc_withdraw_text"], "[min_amount]", "5", -1)
		dcWithdrawText = strings.Replace(dcWithdrawText, "[currency]", data["name"], -1)
		currency[data["id"]]["output"] += dcWithdrawText + `</div>`
	}

	if currency["1001"] == nil {
		currency["1001"] = make(map[string]string)
	}

	currency["1001"]["name"] = "USD"
	currency["1001"]["input"] = `<div class="pull-left"><h4>` + c.Lang["deposit0"] + ` USD</h4>
		<select id="ps_select" class="form-control">
		  <option value="pm">Perfect Money</option>
		  <option value="ik">Mobile, Yandex</option>
		  <option value="payeer">BTC</option>
		</select>
			<div style="display:block" id="pm_form">
				<form action="https://perfectmoney.is/api/step1.asp" method="POST">
					<input type="hidden" name="PAYEE_ACCOUNT" value="` + c.EConfig["pm_id"] + `">
					<input type="hidden" name="PAYEE_NAME" value="Dcoin">
					<input type="hidden" name="PAYMENT_ID" value="` + utils.Int64ToStr(c.SessUserId) + `">
					<input type="hidden" name="PAYMENT_UNITS" value="USD">
					<input type="hidden" name="STATUS_URL" value="` + c.EURL + `ajax?controllerName=EGatePm">
					<input type="hidden" name="PAYMENT_URL" value="` + c.EURL + `ajax?controllerName=ESuccess">
					<input type="hidden" name="PAYMENT_URL_METHOD" value="LINK">
					<input type="hidden" name="NOPAYMENT_URL" value="` + c.EURL + `ajax?controllerName=EFailure">
					<input type="hidden" name="NOPAYMENT_URL_METHOD" value="LINK">
					<input type="hidden" name="SUGGESTED_MEMO" value="Dcoins">
					<input type="hidden" name="BAGGAGE_FIELDS" value="">
					<table class="table_out">
					<tbody>
						<tr>
						<td>` + c.Lang["amount_to_pay"] + `</td>
						<td class="form-inline" style="line-height: 35px;"><input name="PAYMENT_AMOUNT" class="form-control" type="text" style="margin-right:5px; width:120px"><input type="submit" value="` + c.Lang["deposit"] + `" class="btn btn-outline btn-success" name="PAYMENT_METHOD"></td>
						</tr>
						<tr>
					 </tbody>
					 </table>
				</form>
			</div>
			<div style="display:none" id="ik_form">
				<form id="payment" name="payment" method="post" action="https://sci.interkassa.com/" enctype="utf-8">
				    <input type="hidden" name="ik_co_id" value="` + c.EConfig["ik_id"] + `" />
					<input type="hidden" name="ik_pm_no" value="ik_pm_no" />
					<input type="hidden" name="ik_cur" value="USD" />
					<input type="hidden" name="ik_ia_u" value="` + c.EURL + `ajax?controllerName=EGateIk" />
					<input type="hidden" name="ik_suc_u" value=""` + c.EURL + `ajax?controllerName=ESuccess" />
					<input type="hidden" name="ik_fal_u" value="` + c.EURL + `ajax?controllerName=EFailure" />
					<input type="hidden" name="ik_desc" value="` + utils.Int64ToStr(c.SessUserId) + `" />
				<table class="table_out">
				<tbody>
					<tr>
					<td>` + c.Lang["amount_to_pay"] + `</td>
					<td class="form-inline" style="line-height: 35px;"><input name="ik_am" class="form-control" type="text" style="margin-right:5px; width:120px"><input type="submit" value="` + c.Lang["deposit"] + `" class="btn btn-outline btn-success"></td>
					</tr>
					<tr>
				 </tbody>
				 </table>
				</form>
			</div>
			<script>
			$('#payeer_sign').bind('click', function () {
				$.post( 'ajax?controllerName=EPayeerSign', {
					m_orderid: $('input[name=m_orderid]').val(),
					m_desc: $('input[name=m_desc]').val(),
					m_amount: $('input[name=m_amount]').val()
				},
				function (data) {
					console.log("data", data)
					$('input[name=m_sign]').val(data);
					$("#payeer_form_data").submit();
				});
			});
			</script>
			<div style="display:none" id="payeer_form">
				<form id="payeer_form_data" name="payment" method="post" action="https://payeer.com/merchant/" enctype="utf-8">
				   	<input type="hidden" id="m_shop" name="m_shop" value="` + c.EConfig["payeer_id"] + `">
					<input type="hidden" id="m_orderid" name="m_orderid" value="1234">
					<input type="hidden" id="m_curr" name="m_curr" value="USD">
					<input type="hidden" id="m_desc" name="m_desc" value="` + base64.StdEncoding.EncodeToString(utils.Int64ToByte(c.SessUserId)) + `">
					<input type="hidden" id="m_sign" name="m_sign" value="">
				<table class="table_out">
				<tbody>
					<tr>
					<td>` + c.Lang["amount_to_pay"] + `</td>
					<td class="form-inline" style="line-height: 35px;"><input id="m_amount" name="m_amount" class="form-control" type="text" style="margin-right:5px; width:120px"><input id="payeer_sign" type="button" value="` + c.Lang["deposit"] + `" class="btn btn-outline btn-success"></td>
					</tr>
					<tr>
				 </tbody>
				 </table>
				</form>
			</div>

			</div>`

	currency["1001"]["output"] = `<div class="pull-left"><h4>` + c.Lang["withdraw0"] + ` USD</h4>
		<table class="table_out">
			<tbody>
			<tr>
			<td>` + c.Lang["withdrawal_on_the_purse"] + `:</td>
			<td class="form-inline"><div class="form-group"><select class="form-control" style="width:300px"><option>Perfect Money [1.5%] [min 10 USD]</option></select></div></td>
			</tr>
			<tr>
			<td>` + c.Lang["purse"] + `:</td>
			<td class="form-inline" style="line-height: 35px;"><input id="account-1001" class="form-control" type="text" style="margin-right:5px; width:300px"></td>
			</tr>
			<tr>
			<td>` + c.Lang["amount_to_withdrawal"] + `:</td>
			<td class="form-inline" style="line-height: 35px;"><input id="amount-1001" class="form-control" type="text"  onkeyup="calc_withdraw_amount(1001, '1.5')" onchange="calc_withdraw_amount(1001, '1.5')" style="margin-right:5px; width:300px"></td>
			</tr>
			<tr>
			<td>` + c.Lang["you_will_receive"] + `:</td>
			<td class="form-inline" style="line-height: 35px"><input  disabled="" id="withdraw_amount-1001" class="form-control" type="text" style="margin-right:5px; width:300px"> </td>
			</tr>
			</tbody></table><div id="alerts-1001"></div><button class="btn btn-outline btn-primary" onclick="withdraw(1001, 'Perfect-money')">` + c.Lang["withdrawal"] + `</button>
			</div><div class="pull-left" style="margin-left:30px; margin-top:43px; border-left: 4px solid #ccc; padding:7px 7px; width:350px">` + c.Lang["withdrawal_within_hours"] + `</div>`

	types := map[string]string{"withdraw": c.Lang["withdraw0"], "adding_funds": c.Lang["deposit0"]}

	// история вывода средств
	myFinanceHistory_ := make(map[int64][]*EmyFinanceType)
	rows, err := c.Query(c.FormatQuery(`
			SELECT id, amount, wd_amount, close_time, currency_id, method, open_time
			FROM e_withdraw
			WHERE user_id = ?
			ORDER BY open_time DESC
			LIMIT 40
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		Finance := new(EmyFinanceType)
		err = rows.Scan(&Finance.Id, &Finance.Amount, &Finance.WdAmount, &Finance.CloseTime, &Finance.CurrencyId, &Finance.Method, &Finance.OpenTime)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		Finance.Ftype = types["withdraw"]
		Finance.Amount = Finance.WdAmount
		Finance.AddTime = Finance.OpenTime
		if Finance.CloseTime == 0 {
			Finance.Status = c.Lang["in_process"]
		} else {
			t := time.Unix(Finance.CloseTime, 0)
			timeFormated := t.Format(c.TimeFormat)
			Finance.Status = `<span class="text-success"><strong>` + c.Lang["ready"] + `</strong></span> (` + timeFormated + `)`
		}
		Finance.Method = Finance.Method + ` (` + currencyList[Finance.CurrencyId] + `)`
		myFinanceHistory_[Finance.OpenTime] = append(myFinanceHistory_[Finance.OpenTime], Finance)
	}

	// история ввода средств
	rows, err = c.Query(c.FormatQuery(`
			SELECT id, amount, time, currency_id
			FROM e_adding_funds
			WHERE user_id = ?
			ORDER BY time DESC
			LIMIT 40
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		Finance := new(EmyFinanceType)
		err = rows.Scan(&Finance.Id, &Finance.Amount, &Finance.AddTime, &Finance.CurrencyId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		Finance.Ftype = types["adding_funds"]
		Finance.Status = `<span class="text-success"><strong>` + c.Lang["ready"] + `</strong></span>`
		Finance.Method = `Dcoin (` + currencyList[Finance.CurrencyId] + `)`
		myFinanceHistory_[Finance.AddTime] = append(myFinanceHistory_[Finance.AddTime], Finance)
	}

	// история ввода средств IK
	rows, err = c.Query(c.FormatQuery(`
			SELECT id, amount, time, currency_id
			FROM e_adding_funds_ik
			WHERE user_id = ?
			ORDER BY time DESC
			LIMIT 40
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		Finance := new(EmyFinanceType)
		err = rows.Scan(&Finance.Id, &Finance.Amount, &Finance.AddTime, &Finance.CurrencyId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		Finance.Ftype = types["adding_funds"]
		Finance.Status = `<span class="text-success"><strong>` + c.Lang["ready"] + `</strong></span>`
		Finance.Method = `Interkassa (` + currencyList[Finance.CurrencyId] + `)`
		myFinanceHistory_[Finance.AddTime] = append(myFinanceHistory_[Finance.AddTime], Finance)
	}

	// история ввода средств PM
	rows, err = c.Query(c.FormatQuery(`
			SELECT id, amount, time, currency_id
			FROM e_adding_funds_pm
			WHERE user_id = ?
			ORDER BY time DESC
			LIMIT 40
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		Finance := new(EmyFinanceType)
		err = rows.Scan(&Finance.Id, &Finance.Amount, &Finance.AddTime, &Finance.CurrencyId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		Finance.Ftype = types["adding_funds"]
		Finance.Status = `<span class="text-success"><strong>` + c.Lang["ready"] + `</strong></span>`
		Finance.Method = `PerfectMoney (` + currencyList[Finance.CurrencyId] + `)`
		myFinanceHistory_[Finance.AddTime] = append(myFinanceHistory_[Finance.AddTime], Finance)
	}

	//map[int64][]*EmyFinanceType
	var keys []int
	for k := range myFinanceHistory_ {
		keys = append(keys, int(k))
	}
	sort.Ints(keys)

	var my_finance_history []*EmyFinanceType
	for _, k := range keys {
		for _, data := range myFinanceHistory_[int64(k)] {
			my_finance_history = append(my_finance_history, data)
		}
	}
	///home/z/go-projects/src/github.com/c-darwin/dcoin-go/packages/controllers/e_my_finance.go:275: cannot use myFinanceHistory_[k] (type []*EmyFinanceType) as type *EmyFinanceType in append

	collapse := c.Parameters["collapse"]

	TemplateStr, err := makeTemplate("e_my_finance", "eMyFinance", &eMyFinancePage{
		Lang:             c.Lang,
		UserId:           c.SessUserId,
		MyFinanceHistory: my_finance_history,
		Collapse:         collapse,
		Currency:         currency,
		CurrencyList:     currencyList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #7
0
func (c *Controller) CfPagePreview() (string, error) {

	var err error

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

	cfUrl, err := c.GetCfUrl()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	showHeaders := false
	if len(c.r.FormValue("blurb_img")) > 0 {
		showHeaders = true
	}

	page := c.Parameters["page"]
	if len(page) > 0 {
		if ok, _ := regexp.MatchString(`^(?i)[a-z]{0,10}$`, page); !ok {
			return "", errors.New("incorrect page")
		}
	}
	cfCurrencyName := c.Parameters["onlyCfCurrencyName"]
	if len(page) == 0 {
		page = "home"
	}

	langId := int64(utils.StrToFloat64(c.Parameters["lang_id"]))
	projectId := int64(utils.StrToFloat64(c.Parameters["onlyProjectId"]))
	log.Debug("projectId:", projectId)
	var blurbImg, headImg, descriptionImg, picture, videoType, videoUrlId, newsImg string
	imgBlank := cfUrl + "static/img/blank.png"

	var links [][]string
	if projectId > 0 || len(cfCurrencyName) > 0 {
		if projectId == 0 {
			projectId, err = c.Single("SELECT id FROM cf_projects WHERE project_currency_name = ?", cfCurrencyName).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}
		data := make(map[string]string)
		if langId > 0 {
			data, err = c.OneRow("SELECT * FROM cf_projects_data WHERE project_id = ? AND lang_id = ?", projectId, langId).String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		} else { // Если язык не указан, то просто берем первое добавленное описание
			data, err = c.OneRow("SELECT * FROM cf_projects_data WHERE project_id = ? ORDER BY id ASC", projectId).String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			langId = utils.StrToInt64(data["lang_id"])
		}
		blurbImg = data["blurb_img"]
		headImg = data["head_img"]
		descriptionImg = data["description_img"]
		picture = data["picture"]
		videoType = data["video_type"]
		videoUrlId = data["video_url_id"]
		newsImg = data["news_img"]
		if len(data["links"]) > 0 && data["links"] != "0" {
			var links_ [][]interface{}
			err = json.Unmarshal([]byte(data["links"]), &links_)
			if err != nil {
				log.Debug("data links:", data["links"])
				return "", utils.ErrInfo(err)
			}
			for _, v := range links_ {
				var l []string
				for _, v2 := range v {
					str := utils.InterfaceToStr(v2)
					if len(str) == 0 {
						return "", utils.ErrInfo(errors.New("Incorrect links"))
					}
					l = append(l, str)
				}
				links = append(links, l)
			}
		}
	} else {
		log.Debug("FormValue", c.r.Form)

		blurbImg = c.r.FormValue("blurb_img")
		headImg = c.r.FormValue("head_img")
		descriptionImg = c.r.FormValue("description_img")
		picture = c.r.FormValue("blurb_img")
		videoType = c.r.FormValue("video_type")
		videoUrlId = c.r.FormValue("video_url_id")
		newsImg = c.r.FormValue("news_img")

		if !utils.CheckInputData(c.r.FormValue("project_id"), "int") {
			return "", errors.New("Incorrect project_id")
		}
		if !utils.CheckInputData(blurbImg, "img_url") {
			blurbImg = imgBlank
		}
		if !utils.CheckInputData(headImg, "img_url") {
			headImg = imgBlank
		}
		if !utils.CheckInputData(descriptionImg, "img_url") {
			descriptionImg = imgBlank
		}
		if !utils.CheckInputData(picture, "img_url") {
			picture = imgBlank
		}
		if !utils.CheckInputData(newsImg, "img_url") {
			newsImg = imgBlank
		}
		if !utils.CheckInputData(videoType, "video_type") {
			videoType = ""
		}
		if !utils.CheckInputData(videoUrlId, "video_url_id") {
			videoUrlId = ""
		}

		if len(c.Parameters["links"]) > 0 {
			var links_ [][]interface{}
			err = json.Unmarshal([]byte(c.Parameters["links"]), &links_)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			for _, v := range links_ {
				var l []string
				for _, v2 := range v {
					str := utils.InterfaceToStr(v2)
					if len(str) == 0 {
						return "", utils.ErrInfo(errors.New("Incorrect links"))
					}
					l = append(l, str)
				}
				links = append(links, l)
			}
		}
	}

	project, err := c.OneRow("SELECT * FROM cf_projects WHERE id = ?", projectId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// сколько дней осталось
	days := utils.Round((utils.StrToFloat64(project["end_time"])-float64(utils.Time()))/86400, 0)
	if days <= 0 {
		days = 0
	}
	project["days"] = utils.Float64ToStr(days)
	if project["close_block_id"] != "0" || project["del_block_id"] != "0" {
		project["ended"] = "1"
	} else {
		project["ended"] = "0"
	}

	// дата старта
	t := time.Unix(utils.StrToInt64(project["start_time"]), 0)
	project["start_date"] = t.Format(c.TimeFormat)

	// в какой валюте идет сбор
	project["currency"] = c.CurrencyList[utils.StrToInt64(project["currency_id"])]

	// на каких языках есть описание
	// для home/news можно скрыть язык
	addSql := ""
	if page == "home" || page == "news" {
		addSql = " AND hide = 0 "
	}
	projectLang, err := c.GetMap(`SELECT id, lang_id FROM cf_projects_data WHERE project_id = ? `+addSql, "id", "lang_id", projectId)

	// сколько собрано средств
	projectFunding, err := c.Single("SELECT sum(amount) FROM cf_funding WHERE project_id  =  ? AND del_block_id  =  0", projectId).Float64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// сколько всего фундеров
	projectCountFunders, err := c.Single("SELECT count(id) FROM cf_funding WHERE project_id  =  ? AND del_block_id  =  0 GROUP BY user_id", projectId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// список фундеров
	var q string
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT cf_funding.user_id, sum(amount) as amount, time,  name, avatar
			FROM cf_funding
			LEFT JOIN users ON users.user_id = cf_funding.user_id
			WHERE project_id = ? AND
						del_block_id = 0
			GROUP BY cf_funding.user_id, time, name, avatar
			ORDER BY time DESC
			LIMIT 100`
	} else {
		q = `SELECT cf_funding.user_id, sum(amount) as amount, time,  name, avatar
			FROM cf_funding
			LEFT JOIN users ON users.user_id = cf_funding.user_id
			WHERE project_id = ? AND
						del_block_id = 0
			GROUP BY cf_funding.user_id
			ORDER BY time DESC
			LIMIT 100`
	}
	projectFunders, err := c.GetAll(q, 100, projectId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for k, v := range projectFunders {
		t := time.Unix(utils.StrToInt64(v["time"]), 0)
		projectFunders[k]["time"] = t.Format(c.TimeFormat)
		if len(v["avatar"]) == 0 {
			projectFunders[k]["avatar"] = cfUrl + "static/img/noavatar.png"
		}
		if len(v["name"]) == 0 {
			projectFunders[k]["name"] = "Noname"
		}
	}

	// список комментов
	var projectComments []map[string]string
	if langId > 0 {
		projectComments, err = c.GetAll(`
				SELECT users.user_id, comment, time, name, avatar
				FROM cf_comments
				LEFT JOIN users ON users.user_id = cf_comments.user_id
				WHERE project_id = ? AND
							 lang_id = ?
				ORDER BY time DESC
				LIMIT 100
				`, 100, projectId, langId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		for k, v := range projectComments {
			t := time.Unix(utils.StrToInt64(v["time"]), 0)
			projectComments[k]["time"] = t.Format(c.TimeFormat)
			if len(v["avatar"]) == 0 {
				projectComments[k]["avatar"] = cfUrl + "static/img/noavatar.png"
			}
			if len(v["name"]) == 0 {
				projectComments[k]["name"] = "Noname"
			}
		}
	}
	// сколько всего комментов на каждом языке
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT lang_id, count(id) as count FROM cf_comments WHERE project_id = ? GROUP BY lang_id`
	} else {
		q = `SELECT lang_id, count(id) as count FROM cf_comments WHERE project_id = ?`
	}
	langComments, err := c.GetMap(q, "lang_id", "count", projectId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	var projectCountComments int64
	for _, v := range langComments {
		projectCountComments += utils.StrToInt64(v)
	}

	cfLng, err := c.GetAllCfLng()

	// инфа об авторе проекта
	authorInfo, err := c.GetCfAuthorInfo(project["user_id"], cfUrl)

	// возможно наш юзер фундер
	project["funder"] = ""
	if c.SessUserId > 0 {
		project["funder"], err = c.Single("SELECT id FROM cf_funding WHERE project_id  =  ? AND user_id  =  ? AND del_block_id  =  0", projectId, c.SessUserId).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	pagesArray := []string{"home", "news", "funders", "comments"}
	configCfPs := make(map[string][]string)
	if len(c.NodeConfig["cf_ps"]) > 0 {
		//{"1":["Credit card"],"2":["ik","MTS, Megafon, W1, Paxum"],"3":["pm","Perfect Money"]}
		err = json.Unmarshal([]byte(c.NodeConfig["cf_ps"]), &configCfPs)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	// узнаем, какие платежные системы доступны данному проекту
	projectPs, err := c.OneRow("SELECT * FROM cf_projects_ps WHERE project_id  =  ?", projectId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// узнаем, не в блек-листе ли проект
	black, err := c.Single("SELECT project_id FROM cf_blacklist WHERE project_id  =  ?", projectId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if black > 0 {
		return "", errors.New("Black project")
	}

	TemplateStr, err := makeTemplate("cf_page_preview", "cfPagePreview", &CfPagePreviewPage{
		Alert:                c.Alert,
		Lang:                 c.Lang,
		CountSignArr:         c.CountSignArr,
		ShowSignData:         c.ShowSignData,
		UserId:               c.SessUserId,
		TimeNow:              timeNow,
		TxType:               txType,
		TxTypeId:             txTypeId,
		SignData:             "",
		CfLng:                cfLng,
		CurrencyList:         c.CurrencyList,
		CfUrl:                cfUrl,
		ShowHeaders:          showHeaders,
		Page:                 page,
		CfCurrencyName:       cfCurrencyName,
		LangId:               langId,
		ProjectId:            projectId,
		BlurbImg:             blurbImg,
		HeadImg:              headImg,
		DescriptionImg:       descriptionImg,
		Picture:              picture,
		VideoType:            videoType,
		VideoUrlId:           videoUrlId,
		NewsImg:              newsImg,
		Links:                links,
		ImgBlank:             imgBlank,
		Project:              project,
		ProjectLang:          projectLang,
		ProjectFunding:       projectFunding,
		ProjectCountFunders:  projectCountFunders,
		ProjectFunders:       projectFunders,
		ProjectComments:      projectComments,
		LangComments:         langComments,
		ProjectCountComments: projectCountComments,
		AuthorInfo:           authorInfo,
		PagesArray:           pagesArray,
		ConfigCfPs:           configCfPs,
		ProjectPs:            projectPs,
		Black:                black})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #8
0
func (c *Controller) Statistic() (string, error) {

	var err error

	sumWallets := make(map[int64]float64)
	// получаем кол-во DC на кошельках
	rows, err := c.Query(`
			SELECT currency_id,
					     sum(amount) as sum_amount
			FROM wallets
			GROUP BY currency_id
			`)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var currency_id int64
		var sum_amount float64
		err = rows.Scan(&currency_id, &sum_amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		sumWallets[currency_id] = sum_amount
	}
	// получаем кол-во TDC на обещанных суммах
	rows, err = c.Query(`
			SELECT currency_id,
			  		     sum(tdc_amount) as sum_amount
			FROM promised_amount
			GROUP BY currency_id
			`)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var currency_id int64
		var sum_amount float64
		err = rows.Scan(&currency_id, &sum_amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if sumWallets[currency_id] > 0 {
			sumWallets[currency_id] += sum_amount
		} else {
			sumWallets[currency_id] = sum_amount
		}
	}

	// получаем суммы обещанных сумм
	sumPromisedAmount, err := c.GetMap(`
			SELECT currency_id,
						sum(amount) as sum_amount
			FROM promised_amount
			WHERE status = 'mining' AND
					     del_block_id = 0 AND
						(cash_request_out_time = 0 OR cash_request_out_time > ?)
			GROUP BY currency_id`, "currency_id", "sum_amount", utils.Time()-c.Variables.Int64["cash_request_time"])

	// получаем кол-во майнеров по валютам
	promisedAmountMiners, err := c.GetMap(`
			SELECT currency_id, count(user_id) as count
			FROM (
					SELECT currency_id, user_id
					FROM promised_amount
					WHERE  del_block_id = 0 AND
								 del_mining_block_id = 0 AND
								 status IN ('mining', 'repaid')
					GROUP BY  user_id, currency_id
					) as t1
			GROUP BY  currency_id`, "currency_id", "count")

	// получаем кол-во анонимных юзеров по валютам
	walletsUsers, err := c.GetMap(`
			SELECT currency_id, count(user_id) as count
			FROM wallets
			WHERE amount > 0
			GROUP BY  currency_id`, "currency_id", "count")

	refPhotos := make(map[int64][]string)
	// таблица обмена на наличные
	cashRequests, err := c.GetAll(`
			SELECT *
			FROM cash_requests
			ORDER BY id DESC
			LIMIT 5`, 5)
	for i := 0; i < len(cashRequests); i++ {
		if cashRequests[i]["del_block_id"] != "0" {
			cashRequests[i]["status"] = "reduction closed"
		} else if utils.Time()-utils.StrToInt64(cashRequests[i]["time"]) > c.Variables.Int64["cash_request_time"] && cashRequests[i]["status"] != "approved" {
			cashRequests[i]["status"] = "rejected"
		}
		t := time.Unix(utils.StrToInt64(cashRequests[i]["time"]), 0)
		cashRequests[i]["time"] = t.Format(c.TimeFormat)

		// ### from_user_id для фоток
		data, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", cashRequests[i]["from_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)
		}
		refPhotos[utils.StrToInt64(cashRequests[i]["from_user_id"])] = hosts

		// ### to_user_id для фоток
		data, err = c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", cashRequests[i]["to_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)
		}
		refPhotos[utils.StrToInt64(cashRequests[i]["to_user_id"])] = hosts
	}

	var userInfoWallets []utils.DCAmounts
	var promisedAmountListAccepted []utils.PromisedAmounts
	var credits map[string]string
	// поиск инфы о юзере
	userInfoId := int64(utils.StrToFloat64(c.Parameters["user_info_id"]))
	if userInfoId > 0 {
		userInfoWallets, err = c.GetBalances(userInfoId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// обещанные суммы юзера
		_, promisedAmountListAccepted, _, err = c.GetPromisedAmounts(userInfoId, c.Variables.Int64["cash_request_time"])
		// кредиты
		credits, err = c.GetMap(`
				SELECT sum(amount) as amount,
							 currency_id
				FROM credits
				WHERE from_user_id = ? AND
							 del_block_id = 0
				GROUP BY currency_id`, "amount", "currency_id", userInfoId)
	}

	/*
	 * Кол-во юзеров, сменивших ключ
	 * */
	countUsers, err := c.Single("SELECT count(user_id) FROM users WHERE log_id > 0").Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	/*
	 * %/год
	 * */
	currencyPct := make(map[int64]map[string]string)
	for currencyId, name := range c.CurrencyList {
		pct, err := c.OneRow("SELECT * FROM pct WHERE currency_id  =  ? ORDER BY block_id DESC", currencyId).Float64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		currencyPct[currencyId] = make(map[string]string)
		currencyPct[currencyId]["name"] = name
		currencyPct[currencyId]["miner"] = utils.Float64ToStr(utils.Round((math.Pow(1+pct["miner"], 120)-1)*100, 6))
		currencyPct[currencyId]["user"] = utils.Float64ToStr(utils.Round((math.Pow(1+pct["user"], 120)-1)*100, 6))
	}

	/*
	 * Произошедшие сокращения
	 * */
	reduction, err := c.GetAll(`
			SELECT *
			FROM reduction
			ORDER BY time DESC
			LIMIT 20`, 20)
	for i := 0; i < len(reduction); i++ {
		if reduction[i]["type"] != "auto" {
			reduction[i]["type"] = "voting"
		}

		t := time.Unix(utils.StrToInt64(reduction[i]["time"]), 0)
		reduction[i]["time"] = t.Format(c.TimeFormat)
	}

	TemplateStr, err := makeTemplate("statistic", "statistic", &StatisticPage{
		Lang:                       c.Lang,
		CurrencyList:               c.CurrencyListCf,
		UserInfoId:                 userInfoId,
		SumWallets:                 sumWallets,
		SumPromisedAmount:          sumPromisedAmount,
		PromisedAmountMiners:       promisedAmountMiners,
		WalletsUsers:               walletsUsers,
		CashRequests:               cashRequests,
		UserInfoWallets:            userInfoWallets,
		Credits:                    credits,
		PromisedAmountListAccepted: promisedAmountListAccepted,
		CountUsers:                 countUsers,
		CurrencyPct:                currencyPct,
		Reduction:                  reduction,
		RefPhotos:                  refPhotos,
		UserId:                     c.SessUserId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #9
0
func (p *Parser) ChangeCreditPart() error {
	return p.selectiveLoggingAndUpd([]string{"credit_part"}, []interface{}{utils.Float64ToStr(p.TxMaps.Float64["pct"])}, "users", []string{"user_id"}, []string{utils.Int64ToStr(p.TxUserID)})
}
Example #10
0
func (c *Controller) StatisticVoting() (string, error) {

	var err error

	js := ""
	var divs []string

	/*
	 * Голосование за размер обещанной суммы
	 */
	rows, err := c.Query(c.FormatQuery(`SELECT currency_id, amount, count(user_id) as votes FROM votes_max_promised_amount GROUP BY currency_id, amount`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	maxPromisedAmountVotes := make(map[int64][]map[int64]int64)
	for rows.Next() {
		var currency_id, votes, amount int64
		err = rows.Scan(&currency_id, &amount, &votes)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		maxPromisedAmountVotes[currency_id] = append(maxPromisedAmountVotes[currency_id], map[int64]int64{amount: votes})
	}

	for currencyId, arr := range maxPromisedAmountVotes {
		js += fmt.Sprintf("var max_promised_amounts_%d = [", currencyId)
		for _, data := range arr {
			for k, v := range data {
				js += fmt.Sprintf("[%v, %v],", k, v)
			}
		}
		js = js[:len(js)-1] + "];\n"
		divs = append(divs, fmt.Sprintf("max_promised_amounts_%d", currencyId))
	}

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

	newMaxPromisedAmounts := make(map[int64]int64)
	//array []map[int64]int64, min, max, step int64
	for currencyId, data := range maxPromisedAmountVotes {
		newMaxPromisedAmounts[currencyId] = utils.GetMaxVote(data, 0, totalCountCurrencies, 10)
	}

	/*
	 * Голосование за кол-во валют в обещанных суммах
	 */
	rows, err = c.Query(c.FormatQuery(`SELECT currency_id, count, count(user_id) as votes FROM votes_max_other_currencies GROUP BY  currency_id, count`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	maxOtherCurrenciesVotes := make(map[int64][]map[int64]int64)
	for rows.Next() {
		var currency_id, count, votes int64
		err = rows.Scan(&currency_id, &count, &votes)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		maxOtherCurrenciesVotes[currency_id] = append(maxOtherCurrenciesVotes[currency_id], map[int64]int64{count: votes})
	}

	log.Debug("maxOtherCurrenciesVotes", maxOtherCurrenciesVotes)
	newMaxOtherCurrencies := make(map[int64]int64)
	for currencyId, arr := range maxOtherCurrenciesVotes {
		newMaxOtherCurrencies[currencyId] = utils.GetMaxVote(arr, 0, totalCountCurrencies, 10)
		js += fmt.Sprintf("var max_other_currencies_votes_%d = [", currencyId)
		for _, data := range arr {
			log.Debug("data", data)
			for k, v := range data {
				js += fmt.Sprintf("[%v, %v],", k, v)
			}
		}
		js = js[:len(js)-1] + "];\n"
		log.Debug("js", js)
		divs = append(divs, fmt.Sprintf("max_other_currencies_votes_%d", currencyId))
	}

	/*
	 * Голосование за ручное сокращение объема монет
	 * */
	// получаем кол-во обещанных сумм у разных юзеров по каждой валюте. start_time есть только у тех, у кого статус mining/repaid
	promisedAmount_, err := c.GetAll(`
			SELECT currency_id, count(user_id) as count
					FROM (
							SELECT currency_id, user_id
							FROM promised_amount
							WHERE start_time < ? AND
										 del_block_id = 0 AND
										 del_mining_block_id = 0 AND
										 status IN ('mining', 'repaid')
							GROUP BY  user_id, currency_id
							) as t1
					GROUP BY  currency_id
	`, -1, utils.Time()-c.Variables.Int64["min_hold_time_promise_amount"])
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	promisedAmount := make(map[string]string)
	for _, data := range promisedAmount_ {
		promisedAmount[data["currency_id"]] = data["count"]
	}

	// берем все голоса юзеров по данной валюте
	votesReduction := make(map[string]map[string]string)
	votesReduction_, err := c.GetAll(`
			SELECT currency_id,
					  	pct,
					     count(currency_id) as votes
			FROM votes_reduction
			WHERE time > ? AND
						 pct > 0
			GROUP BY currency_id, pct
	`, -1, utils.Time()-c.Variables.Int64["reduction_period"])
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for _, data := range votesReduction_ {
		votesReduction[data["currency_id"]] = make(map[string]string)
		votesReduction[data["currency_id"]][data["pct"]] = data["votes"]
	}

	/*
	 * Голосование за реф. бонусы
	 * */
	refLevels := []string{"first", "second", "third"}
	newReferralPct := make(map[string]int64)
	votesReferral := make(map[string][]map[int64]int64)
	for i := 0; i < len(refLevels); i++ {
		level := refLevels[i]
		// берем все голоса
		votesReferral_, err := c.GetAll(`
				SELECT `+level+`,
							  count(user_id) as votes
				FROM votes_referral
				GROUP BY  `+level+`
		`, -1)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		for _, data := range votesReferral_ {
			votesReferral[level] = append(votesReferral[level], map[int64]int64{utils.StrToInt64(data[level]): utils.StrToInt64(data["votes"])})
		}

		newReferralPct[level] = utils.GetMaxVote(votesReferral[level], 0, 30, 10)
	}

	for level, arr := range votesReferral {
		js += "var votes_referral_" + level + " = ["
		for _, data := range arr {
			for k, v := range data {
				js += fmt.Sprintf("[%v, %v],", k, v)
			}
		}
		js = js[:len(js)-1] + "];\n"
		divs = append(divs, "votes_referral_"+level)
	}

	/*
	 * Голосоваие за майнеркие и юзерские %
	 * */
	// берем все голоса miner_pct
	pctVotes := make(map[int64]map[string]map[string]int64)
	rows, err = c.Query("SELECT currency_id, pct, count(user_id) as votes FROM votes_miner_pct GROUP BY currency_id, pct ORDER BY currency_id, pct ASC")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var currency_id, votes int64
		var pct string
		err = rows.Scan(&currency_id, &pct, &votes)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		log.Debug("newpctcurrency_id", currency_id, "pct", pct, "votes", votes)
		if len(pctVotes[currency_id]) == 0 {
			pctVotes[currency_id] = make(map[string]map[string]int64)
		}
		if len(pctVotes[currency_id]["miner_pct"]) == 0 {
			pctVotes[currency_id]["miner_pct"] = make(map[string]int64)
		}
		pctVotes[currency_id]["miner_pct"][pct] = votes
	}

	// берем все голоса user_pct
	rows, err = c.Query("SELECT currency_id, pct, count(user_id) as votes FROM votes_user_pct GROUP BY currency_id, pct ORDER BY currency_id, pct ASC")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var currency_id, votes int64
		var pct string
		err = rows.Scan(&currency_id, &pct, &votes)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		log.Debug("currency_id", currency_id, "pct", pct, "votes", votes)
		if len(pctVotes[currency_id]) == 0 {
			pctVotes[currency_id] = make(map[string]map[string]int64)
		}
		if len(pctVotes[currency_id]["user_pct"]) == 0 {
			pctVotes[currency_id]["user_pct"] = make(map[string]int64)
		}
		pctVotes[currency_id]["user_pct"][pct] = votes
	}

	log.Debug("pctVotes", pctVotes)

	for currencyId, data := range pctVotes {
		currencyIdStr := utils.Int64ToStr(currencyId)
		divs = append(divs, "miner_pct_"+currencyIdStr)
		divs = append(divs, "user_pct_"+currencyIdStr)

		js += "var miner_pct_" + currencyIdStr + " = ["
		for k, v := range data["miner_pct"] {
			pctY := utils.Round((math.Pow(1+utils.StrToFloat64(k), 3600*24*365)-1)*100, 2)
			js += fmt.Sprintf("[%v, %v],", pctY, v)
		}
		js = js[:len(js)-1] + "];\n"

		js += "var user_pct_" + currencyIdStr + " = ["
		for k, v := range data["user_pct"] {
			pctY := utils.Round((math.Pow(1+utils.StrToFloat64(k), 3600*24*365)-1)*100, 2)
			js += fmt.Sprintf("[%v, %v],", pctY, v)
		}
		js = js[:len(js)-1] + "];\n"
	}

	newPct := make(map[string]map[string]string)
	newPctTpl := make(map[string]map[string]float64)
	var userMaxKey int64
	PctArray := utils.GetPctArray()

	log.Debug("pctVotes", pctVotes)
	for currencyId, data := range pctVotes {

		currencyIdStr := utils.Int64ToStr(currencyId)
		// определяем % для майнеров
		pctArr := utils.MakePctArray(data["miner_pct"])
		log.Debug("currencyIdStr:", currencyIdStr)
		log.Debug("miner_pct:", data["miner_pct"])
		log.Debug("pctArr:", pctArr)
		key := utils.GetMaxVote(pctArr, 0, 390, 100)
		log.Debug("key:", key)
		if len(newPct[currencyIdStr]) == 0 {
			newPct[currencyIdStr] = make(map[string]string)
		}
		newPct[currencyIdStr]["miner_pct"] = utils.GetPctValue(key)
		if len(newPctTpl[currencyIdStr]) == 0 {
			newPctTpl[currencyIdStr] = make(map[string]float64)
		}
		newPctTpl[currencyIdStr]["miner_pct"] = utils.Round((math.Pow(1+utils.StrToFloat64(utils.GetPctValue(key)), 3600*24*365)-1)*100, 2)

		// определяем % для юзеров
		pctArr = utils.MakePctArray(data["user_pct"])
		pctY := utils.ArraySearch(newPct[currencyIdStr]["miner_pct"], PctArray)
		maxUserPctY := utils.Round(utils.StrToFloat64(pctY)/2, 2)
		userMaxKey = utils.FindUserPct(int(maxUserPctY))
		// отрезаем лишнее, т.к. поиск идет ровно до макимального возможного, т.е. до miner_pct/2
		pctArr = utils.DelUserPct(pctArr, userMaxKey)

		key = utils.GetMaxVote(pctArr, 0, userMaxKey, 100)
		newPct[currencyIdStr]["user_pct"] = utils.GetPctValue(key)
		newPctTpl[currencyIdStr]["user_pct"] = utils.Round((math.Pow(1+utils.StrToFloat64(utils.GetPctValue(key)), 3600*24*365)-1)*100, 2)
	}

	log.Debug("newPct", newPct)
	log.Debug("newPctTpl", newPctTpl)

	/*
	 * %/год
	 * */
	currencyPct := make(map[int64]map[string]string)
	for currencyId, name := range c.CurrencyList {
		pct, err := c.OneRow("SELECT * FROM pct WHERE currency_id  =  ? ORDER BY block_id DESC", currencyId).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		currencyPct[currencyId] = make(map[string]string)
		currencyPct[currencyId]["name"] = name
		currencyPct[currencyId]["miner"] = utils.Float64ToStr(utils.Round((math.Pow(1+utils.StrToFloat64(pct["miner"]), 120)-1)*100, 6))
		currencyPct[currencyId]["user"] = utils.Float64ToStr(utils.Round((math.Pow(1+utils.StrToFloat64(pct["user"]), 120)-1)*100, 6))
	}

	TemplateStr, err := makeTemplate("statistic_voting", "statisticVoting", &StatisticVotingPage{
		Lang:                    c.Lang,
		CurrencyList:            c.CurrencyListCf,
		Js:                      template.JS(js),
		Divs:                    divs,
		CurrencyPct:             currencyPct,
		NewPctTpl:               newPctTpl,
		PctVotes:                pctVotes,
		VotesReferral:           votesReferral,
		VotesReduction:          votesReduction,
		PromisedAmount:          promisedAmount,
		NewMaxOtherCurrencies:   newMaxOtherCurrencies,
		MaxOtherCurrenciesVotes: maxOtherCurrenciesVotes,
		MaxPromisedAmountVotes:  maxPromisedAmountVotes,
		NewMaxPromisedAmounts:   newMaxPromisedAmounts,
		NewReferralPct:          newReferralPct,
		UserId:                  c.SessUserId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #11
0
func (p *Parser) NewReduction() error {
	d := (100 - utils.StrToFloat64(p.TxMaps.String["pct"])) / 100
	if utils.StrToFloat64(p.TxMaps.String["pct"]) > 0 {

		// т.к. невозможо 2 отката подряд из-за промежутка в 2 дня между reduction,
		// то можем использовать только бекап на 1 уровень назад вместо _log
		// но для теста полного роллбека до 1-го блока нужно бекапить данные
		data, err := p.DCDB.GetMap("SELECT user_id, amount FROM wallets WHERE currency_id = ?", "user_id", "amount", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
		jsonDataWallets, err := json.Marshal(data)
		if err != nil {
			return p.ErrInfo(err)
		}

		err = p.ExecSql("UPDATE wallets SET amount_backup = amount, amount = round(amount*"+utils.Float64ToStr(d)+"+"+utils.Float64ToStr(consts.ROUND_FIX)+", 2) WHERE currency_id = ?", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}

		// если бы не урезали amount, то пришлось бы делать пересчет tdc по всем, у кого есть данная валюта
		// после 87826 блока убрано amount_backup = amount, amount = amount*({$d}) т.к. теряется смысл в reduction c type=promised_amount
		data, err = p.DCDB.GetMap("SELECT user_id, tdc_amount FROM promised_amount WHERE currency_id = ?", "user_id", "tdc_amount", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
		jsonDataPromisedAmountTdc, err := json.Marshal(data)
		if err != nil {
			return p.ErrInfo(err)
		}
		err = p.ExecSql("UPDATE promised_amount SET tdc_amount_backup = tdc_amount, tdc_amount = round(tdc_amount*"+utils.Float64ToStr(d)+"+"+utils.Float64ToStr(consts.ROUND_FIX)+", 2) WHERE currency_id = ?", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}

		// все свежие cash_request_out_time отменяем
		data, err = p.DCDB.GetMap("SELECT user_id, cash_request_out_time FROM promised_amount WHERE currency_id = ?", "user_id", "cash_request_out_time", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
		jsonDataPromisedAmountTime, err := json.Marshal(data)
		if err != nil {
			return p.ErrInfo(err)
		}
		err = p.ExecSql("UPDATE promised_amount SET cash_request_out_time_backup = cash_request_out_time, cash_request_out_time = 0 WHERE currency_id = ? AND cash_request_out_time > ?", p.TxMaps.Int64["currency_id"], (p.BlockData.Time - p.Variables.Int64["cash_request_time"]))
		if err != nil {
			return p.ErrInfo(err)
		}

		// все текущие cash_requests, т.е. по которым не прошло 2 суток
		err = p.ExecSql("UPDATE cash_requests SET del_block_id = ? WHERE currency_id = ? AND status = 'pending' AND time > ?", p.BlockData.BlockId, p.TxMaps.Int64["currency_id"], (p.BlockData.Time - p.Variables.Int64["cash_request_time"]))
		if err != nil {
			return p.ErrInfo(err)
		}

		// форeкс-ордеры
		data, err = p.DCDB.GetMap("SELECT user_id, amount FROM forex_orders WHERE sell_currency_id = ?", "user_id", "amount", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
		jsonDataPromisedAmountForex, err := json.Marshal(data)
		if err != nil {
			return p.ErrInfo(err)
		}
		err = p.ExecSql("UPDATE forex_orders SET amount_backup = amount, amount = round(amount*"+utils.Float64ToStr(d)+"+"+utils.Float64ToStr(consts.ROUND_FIX)+", 2) WHERE sell_currency_id = ?", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}

		// крауд-фандинг
		data, err = p.DCDB.GetMap("SELECT user_id, amount FROM cf_funding WHERE currency_id = ?", "user_id", "amount", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}
		jsonDataPromisedAmountCF, err := json.Marshal(data)
		if err != nil {
			return p.ErrInfo(err)
		}
		err = p.ExecSql("UPDATE cf_funding SET amount_backup = amount, amount = round(amount*"+utils.Float64ToStr(d)+"+"+utils.Float64ToStr(consts.ROUND_FIX)+", 2) WHERE currency_id = ?", p.TxMaps.Int64["currency_id"])
		if err != nil {
			return p.ErrInfo(err)
		}

		log.Error(`INSERT INTO reduction_backup (block_id, currency_id, cf_funding, forex_orders, promised_amount_cash_request_out_time, promised_amount_tdc_amount, wallets) VALUES (%v, %v, %v, %v, %v, %v, %v) `, p.BlockData.BlockId, p.TxMaps.Int64["currency_id"], jsonDataPromisedAmountCF, jsonDataPromisedAmountForex, jsonDataPromisedAmountTime, jsonDataPromisedAmountTdc, jsonDataWallets)
		err = p.ExecSql(`INSERT INTO reduction_backup (block_id, currency_id, cf_funding, forex_orders, promised_amount_cash_request_out_time, promised_amount_tdc_amount, wallets) VALUES (?, ?, ?, ?, ?, ?, ?)`, p.BlockData.BlockId, p.TxMaps.Int64["currency_id"], jsonDataPromisedAmountCF, jsonDataPromisedAmountForex, jsonDataPromisedAmountTime, jsonDataPromisedAmountTdc, jsonDataWallets)
		if err != nil {
			return p.ErrInfo(err)
		}
	}
	rType := ""
	if p.TxMaps.String["reduction_type"] == "manual" {
		rType = "manual"
	} else {
		rType = "auto"
	}
	err := p.ExecSql("INSERT INTO reduction ( time, currency_id, type, pct, block_id ) VALUES ( ?, ?, ?, ?, ? )", p.BlockData.Time, p.TxMaps.Int64["currency_id"], rType, p.TxMaps.String["pct"], p.BlockData.BlockId)
	if err != nil {
		return p.ErrInfo(err)
	}
	return nil
}
Example #12
0
func NewForexOrder(userId int64, amount, sellRate float64, sellCurrencyId, buyCurrencyId int64, orderType string, eCommission float64) error {
	log.Debug("userId: %v / amount: %v / sellRate: %v / sellCurrencyId: %v / buyCurrencyId: %v / orderType: %v ", userId, amount, sellRate, sellCurrencyId, buyCurrencyId, orderType)
	curTime := utils.Time()
	err := userLock(userId)
	if err != nil {
		return utils.ErrInfo(err)
	}
	commission := utils.StrToFloat64(utils.ClearNull(utils.Float64ToStr(amount*(eCommission/100)), 6))
	newAmount := utils.StrToFloat64(utils.ClearNull(utils.Float64ToStr(amount-commission), 6))
	if newAmount < commission {
		commission = 0
		newAmount = amount
	}
	log.Debug("newAmount: %v / commission: %v ", newAmount, commission)
	if commission > 0 {
		userAmount := utils.EUserAmountAndProfit(1, sellCurrencyId)
		newAmount_ := userAmount + commission
		// наисляем комиссию системе
		err = utils.UpdEWallet(1, sellCurrencyId, utils.Time(), newAmount_, true)
		if err != nil {
			return utils.ErrInfo(err)
		}
		// и сразу вычитаем комиссию с кошелька юзера
		userAmount = utils.EUserAmountAndProfit(userId, sellCurrencyId)
		err = utils.DB.ExecSql("UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = ? AND currency_id = ?", userAmount-commission, utils.Time(), userId, sellCurrencyId)
		if err != nil {
			return utils.ErrInfo(err)
		}
	}
	// обратный курс. нужен для поиска по ордерам
	reverseRate := utils.StrToFloat64(utils.ClearNull(utils.Float64ToStr(1/sellRate), 6))
	log.Debug("sellRate %v", sellRate)
	log.Debug("reverseRate %v", reverseRate)

	var totalBuyAmount, totalSellAmount float64
	if orderType == "buy" {
		totalBuyAmount = newAmount * reverseRate
	} else {
		totalSellAmount = newAmount
	}

	var debit float64
	var prevUserId int64
	// берем из БД только те ордеры, которые удовлетворяют нашим требованиям
	rows, err := utils.DB.Query(utils.DB.FormatQuery(`
				SELECT id, user_id, amount, sell_rate, buy_currency_id, sell_currency_id
				FROM e_orders
				WHERE buy_currency_id = ? AND
							 sell_rate >= ? AND
							 sell_currency_id = ?  AND
							 del_time = 0 AND
							 empty_time = 0
				ORDER BY sell_rate DESC
				`), sellCurrencyId, reverseRate, buyCurrencyId)
	if err != nil {
		return utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var rowId, rowUserId, rowBuyCurrencyId, rowSellCurrencyId int64
		var rowAmount, rowSellRate float64
		err = rows.Scan(&rowId, &rowUserId, &rowAmount, &rowSellRate, &rowBuyCurrencyId, &rowSellCurrencyId)
		if err != nil {
			return utils.ErrInfo(err)
		}
		log.Debug("rowId: %v / rowUserId: %v / rowAmount: %v / rowSellRate: %v / rowBuyCurrencyId: %v / rowSellCurrencyId: %v", rowId, rowUserId, rowAmount, rowSellRate, rowBuyCurrencyId, rowSellCurrencyId)

		// чтобы ордеры одного и тоже юзера не вызывали стопор, пропускаем все его оредера
		if rowUserId == prevUserId {
			continue
		}
		// блокируем юзера, чей ордер взяли, кроме самого себя
		if rowUserId != userId {
			lockErr := userLock(rowUserId)
			if lockErr != nil {
				log.Error("%v", utils.ErrInfo(err))
				prevUserId = rowUserId
				continue
			}
		}
		if orderType == "buy" {
			// удовлетворит ли данный ордер наш запрос целиком
			if rowAmount >= totalBuyAmount {
				debit = totalBuyAmount
				log.Debug("order ENDED")
			} else {
				debit = rowAmount
			}
		} else {
			// удовлетворит ли данный ордер наш запрос целиком
			if rowAmount/rowSellRate >= totalSellAmount {
				debit = totalSellAmount * rowSellRate
			} else {
				debit = rowAmount
			}
		}
		log.Debug("totalBuyAmount: %v / debit: %v", totalBuyAmount, debit)
		if rowAmount-debit < 0.01 { // ордер опустошили
			err = utils.DB.ExecSql("UPDATE e_orders SET amount = 0, empty_time = ? WHERE id = ?", curTime, rowId)
			if err != nil {
				return utils.ErrInfo(err)
			}
		} else {
			// вычитаем забранную сумму из ордера
			err = utils.DB.ExecSql("UPDATE e_orders SET amount = amount - ? WHERE id = ?", debit, rowId)
			if err != nil {
				return utils.ErrInfo(err)
			}
		}
		mySellRate := utils.ClearNull(utils.Float64ToStr(1/rowSellRate), 6)
		myAmount := debit * utils.StrToFloat64(mySellRate)
		eTradeSellCurrencyId := sellCurrencyId
		eTradeBuyCurrencyId := buyCurrencyId

		// для истории сделок
		err = utils.DB.ExecSql("INSERT INTO e_trade ( user_id, sell_currency_id, sell_rate, amount, buy_currency_id, time, main ) VALUES ( ?, ?, ?, ?, ?, ?, 1 )", userId, eTradeSellCurrencyId, mySellRate, myAmount, eTradeBuyCurrencyId, curTime)
		if err != nil {
			return utils.ErrInfo(err)
		}

		// тот, чей ордер обрабатываем
		err = utils.DB.ExecSql("INSERT INTO e_trade ( user_id, sell_currency_id, sell_rate, amount, buy_currency_id, time ) VALUES ( ?, ?, ?, ?, ?, ? )", rowUserId, eTradeBuyCurrencyId, rowSellRate, debit, eTradeSellCurrencyId, curTime)
		if err != nil {
			return utils.ErrInfo(err)
		}

		// ==== Продавец валюты (тот, чей ордер обработали) ====
		// сколько продавец данного ордера продал валюты
		sellerSellAmount := debit

		// сколько продавец получил buy_currency_id с продажи суммы $seller_sell_amount по его курсу
		sellerBuyAmount := sellerSellAmount * (1 / rowSellRate)

		// начисляем валюту, которую продавец получил (R)
		userAmount := utils.EUserAmountAndProfit(rowUserId, rowBuyCurrencyId)
		newAmount_ := userAmount + sellerBuyAmount
		err = utils.UpdEWallet(rowUserId, rowBuyCurrencyId, utils.Time(), newAmount_, true)
		if err != nil {
			return utils.ErrInfo(err)
		}

		// ====== Покупатель валюты (наш юзер) ======

		// списываем валюту, которую мы продали (R)
		userAmount = utils.EUserAmountAndProfit(userId, rowBuyCurrencyId)
		newAmount_ = userAmount - sellerBuyAmount
		err = utils.UpdEWallet(userId, rowBuyCurrencyId, utils.Time(), newAmount_, true)
		if err != nil {
			return utils.ErrInfo(err)
		}

		// начисляем валюту, которую мы получили (U)
		userAmount = utils.EUserAmountAndProfit(userId, rowSellCurrencyId)
		newAmount_ = userAmount + sellerSellAmount
		err = utils.UpdEWallet(userId, rowSellCurrencyId, utils.Time(), newAmount_, true)
		if err != nil {
			return utils.ErrInfo(err)
		}

		if orderType == "buy" {
			totalBuyAmount -= rowAmount
			if totalBuyAmount <= 0 {
				userUnlock(rowUserId)
				log.Debug("total_buy_amount == 0 break")
				break // проход по ордерам прекращаем, т.к. наш запрос удовлетворен
			}
		} else {
			totalSellAmount -= rowAmount / rowSellRate
			if totalSellAmount <= 0 {
				userUnlock(rowUserId)
				log.Debug("total_sell_amount == 0 break")
				break // проход по ордерам прекращаем, т.к. наш запрос удовлетворен
			}
		}
		if rowUserId != userId {
			userUnlock(rowUserId)
		}
	}

	log.Debug("totalBuyAmount: %v / orderType: %v / sellRate: %v / reverseRate: %v", totalBuyAmount, orderType, sellRate, reverseRate)

	// если после прохода по всем имеющимся ордерам мы не набрали нужную сумму, то создаем свой ордер
	if totalBuyAmount > 0 || totalSellAmount > 0 {
		var newOrderAmount float64
		if orderType == "buy" {
			newOrderAmount = totalBuyAmount * sellRate
		} else {
			newOrderAmount = totalSellAmount
		}
		log.Debug("newOrderAmount: %v", newOrderAmount)
		if newOrderAmount >= 0.000001 {
			err = utils.DB.ExecSql("INSERT INTO e_orders ( time, user_id, sell_currency_id, sell_rate, begin_amount, amount, buy_currency_id ) VALUES ( ?, ?, ?, ?, ?, ?, ? )", curTime, userId, sellCurrencyId, sellRate, newOrderAmount, newOrderAmount, buyCurrencyId)
			if err != nil {
				return utils.ErrInfo(err)
			}

			// вычитаем с баланса сумму созданного ордера
			userAmount := utils.EUserAmountAndProfit(userId, sellCurrencyId)
			err = utils.DB.ExecSql("UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = ? AND currency_id = ?", userAmount-newOrderAmount, utils.Time(), userId, sellCurrencyId)
			if err != nil {
				return utils.ErrInfo(err)
			}
		}
	}

	userUnlock(userId)

	return nil
}
Example #13
0
func makeTemplate(html, name string, tData interface{}) (string, error) {

	defer func() {
		if r := recover(); r != nil {
			log.Error("makeTemplate Recovered", r)
			fmt.Println(r)
		}
	}()

	data, err := static.Asset("static/templates/" + html + ".html")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	signatures, err := static.Asset("static/templates/signatures.html")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	alert_success, err := static.Asset("static/templates/alert_success.html")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	funcMap := template.FuncMap{
		"makeCurrencyName": func(currencyId int64) string {
			if currencyId >= 1000 {
				return ""
			} else {
				return "d"
			}
		},
		"div": func(a, b interface{}) float64 {
			return utils.InterfaceToFloat64(a) / utils.InterfaceToFloat64(b)
		},
		"mult": func(a, b interface{}) float64 {
			return utils.InterfaceToFloat64(a) * utils.InterfaceToFloat64(b)
		},
		"round": func(a interface{}, num int) float64 {
			return utils.Round(utils.InterfaceToFloat64(a), num)
		},
		"len": func(s []map[string]string) int {
			return len(s)
		},
		"lenMap": func(s map[string]string) int {
			return len(s)
		},
		"sum": func(a, b interface{}) float64 {
			return utils.InterfaceToFloat64(a) + utils.InterfaceToFloat64(b)
		},
		"minus": func(a, b interface{}) float64 {
			return utils.InterfaceToFloat64(a) - utils.InterfaceToFloat64(b)
		},
		"noescape": func(s string) template.HTML {
			return template.HTML(s)
		},
		"js": func(s string) template.JS {
			return template.JS(s)
		},
		"join": func(s []string, sep string) string {
			return strings.Join(s, sep)
		},
		"strToInt64": func(text string) int64 {
			return utils.StrToInt64(text)
		},
		"strToInt": func(text string) int {
			return utils.StrToInt(text)
		},
		"bin2hex": func(text string) string {
			return string(utils.BinToHex([]byte(text)))
		},
		"int64ToStr": func(text int64) string {
			return utils.Int64ToStr(text)
		},
		"rand": func() int {
			return utils.RandInt(0, 99999999)
		},
		"append": func(args ...interface{}) string {
			var result string
			for _, value := range args {
				switch value.(type) {
				case int64:
					result += utils.Int64ToStr(value.(int64))
				case float64:
					result += utils.Float64ToStr(value.(float64))
				case string:
					result += value.(string)
				}
			}
			return result
		},
		"replaceCurrency": func(text, name string) string {
			return strings.Replace(text, "[currency]", name, -1)
		},
		"replaceCurrencyName": func(text, name string) string {
			return strings.Replace(text, "[currency]", "D"+name, -1)
		},
		"cfCategoryLang": func(lang map[string]string, name string) string {
			return lang["cf_category_"+name]
		},
		"progressBarLang": func(lang map[string]string, name string) string {
			return lang["progress_bar_pct_"+name]
		},
		"checkProjectPs": func(ProjectPs map[string]string, id string) bool {
			if len(ProjectPs["ps"+id]) > 0 {
				return true
			} else {
				return false
			}
		},
		"cfPageTypeLang": func(lang map[string]string, name string) string {
			return lang["cf_"+name]
		},
		"notificationsLang": func(lang map[string]string, name string) string {
			return lang["notifications_"+name]
		},
	}
	t := template.Must(template.New("template").Funcs(funcMap).Parse(string(data)))
	t = template.Must(t.Parse(string(alert_success)))
	t = template.Must(t.Parse(string(signatures)))
	b := new(bytes.Buffer)
	err = t.ExecuteTemplate(b, name, tData)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return b.String(), nil
}
Example #14
0
func (c *Controller) Assignments() (string, error) {

	var randArr []int64
	// Нельзя завершить голосование юзеров раньше чем через сутки, даже если набрано нужное кол-во голосов.
	// В голосовании нодов ждать сутки не требуется, т.к. там нельзя поставить поддельных нодов

	// Модерация новых майнеров
	// берем тех, кто прошел проверку нодов (type='node_voting')
	num, err := c.Single("SELECT count(id) FROM votes_miners WHERE votes_end  =  0 AND type  =  'user_voting'").Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if num > 0 {
		randArr = append(randArr, 1)
	}

	// Модерация promised_amount
	// вначале получим ID валют, которые мы можем проверять.
	currency, err := c.GetList("SELECT currency_id FROM promised_amount WHERE status IN ('mining', 'repaid') AND user_id = ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	addSql := ""
	currencyIds := strings.Join(currency, ",")
	if len(currencyIds) > 0 || c.SessUserId == 1 {
		if c.SessUserId != 1 {
			addSql = "AND currency_id IN (" + currencyIds + ")"
		}
		num, err := c.Single("SELECT count(id) FROM promised_amount WHERE status  =  'pending' AND del_block_id  =  0 " + addSql + "").Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if num > 0 {
			randArr = append(randArr, 2)
		}
	}

	log.Debug("randArr %v", randArr)

	var AssignType int64
	if len(randArr) > 0 {
		AssignType = randArr[utils.RandInt(0, len(randArr))]
	}

	cloneHosts := make(map[int64][]string)
	var photoHosts []string
	examplePoints := make(map[string]string)
	tplName := "assignments"
	tplTitle := "assignments"

	var txType string
	var txTypeId int64
	var timeNow int64
	var myRace, myCountry, mainQuestion, newPromiseAmount, videoHost string
	var promisedAmountData, userInfo map[string]string

	switch AssignType {
	case 1:

		// ***********************************
		// задания по модерации новых майнеров
		// ***********************************
		txType = "VotesMiner"
		txTypeId = utils.TypeInt(txType)
		timeNow = utils.Time()

		userInfo, err = c.OneRow(`
				SELECT miners_data.user_id,
							 votes_miners.id as vote_id,
							 face_coords,
							 profile_coords,
							 video_type,
							 video_url_id,
							 photo_block_id,
							 photo_max_miner_id,
							 miners_keepers,
							 http_host
				FROM votes_miners
				LEFT JOIN miners_data ON miners_data.user_id = votes_miners.user_id
				LEFT JOIN `+c.MyPrefix+`my_tasks ON `+c.MyPrefix+`my_tasks.id = votes_miners.id
				WHERE 	votes_end = 0 AND
						votes_miners.type = 'user_voting' AND
						(`+c.MyPrefix+`my_tasks.time IS NULL OR (`+c.MyPrefix+`my_tasks.time < ? AND `+c.MyPrefix+`my_tasks.type  =  'miner'))
				`, utils.Time()-consts.ASSIGN_TIME).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(userInfo) == 0 {
			tplName = "assignments"
			break
		}

		examplePoints, err = c.GetPoints(c.Lang)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// получим ID майнеров, у которых лежат фото нужного нам юзера
		minersIds := utils.GetMinersKeepers(userInfo["photo_block_id"], userInfo["photo_max_miner_id"], userInfo["miners_keepers"], true)
		if len(minersIds) > 0 {
			photoHosts, err = c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}

		// отрезки майнера, которого проверяем
		relations, err := c.OneRow("SELECT * FROM faces WHERE user_id  =  ?", userInfo["user_id"]).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// получим допустимые расхождения между точками и совместимость версий
		data_, err := c.OneRow("SELECT tolerances, compatibility FROM spots_compatibility").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		tolerances := make(map[string]map[string]string)
		if err := json.Unmarshal([]byte(data_["tolerances"]), &tolerances); err != nil {
			return "", utils.ErrInfo(err)
		}
		var compatibility []int
		if err := json.Unmarshal([]byte(data_["compatibility"]), &compatibility); err != nil {
			return "", utils.ErrInfo(err)
		}

		// формируем кусок SQL-запроса для соотношений отрезков
		addSqlTolerances := ""
		typesArr := []string{"face", "profile"}
		for i := 0; i < len(typesArr); i++ {
			for j := 1; j <= len(tolerances[typesArr[i]]); j++ {
				currentRelations := utils.StrToFloat64(relations[typesArr[i][:1]+utils.IntToStr(j)])
				diff := utils.StrToFloat64(tolerances[typesArr[i]][utils.IntToStr(j)]) * currentRelations
				if diff == 0 {
					continue
				}
				min := currentRelations - diff
				max := currentRelations + diff
				addSqlTolerances += typesArr[i][:1] + utils.IntToStr(j) + ">" + utils.Float64ToStr(min) + " AND " + typesArr[i][:1] + utils.IntToStr(j) + " < " + utils.Float64ToStr(max) + " AND "
			}
		}
		addSqlTolerances = addSqlTolerances[:len(addSqlTolerances)-4]

		// формируем кусок SQL-запроса для совместимости версий
		addSqlCompatibility := ""
		for i := 0; i < len(compatibility); i++ {
			addSqlCompatibility += fmt.Sprintf(`%d,`, compatibility[i])
		}
		addSqlCompatibility = addSqlCompatibility[:len(addSqlCompatibility)-1]

		// получаем из БД похожие фото
		rows, err := c.Query(c.FormatQuery(`
				SELECT miners_data.user_id,
							 photo_block_id,
							 photo_max_miner_id,
							 miners_keepers
				FROM faces
				LEFT JOIN miners_data ON
						miners_data.user_id = faces.user_id
				WHERE `+addSqlTolerances+` AND
							version IN (`+addSqlCompatibility+`) AND
				             faces.status = 'used' AND
				             miners_data.user_id != ?
				LIMIT 100
				`), userInfo["user_id"])
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var photo_block_id, photo_max_miner_id, miners_keepers string
			var user_id int64
			err = rows.Scan(&user_id, &photo_block_id, &photo_max_miner_id, &miners_keepers)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			// майнеры, у которых можно получить фото нужного нам юзера
			minersIds := utils.GetMinersKeepers(photo_block_id, photo_max_miner_id, miners_keepers, true)
			if len(minersIds) > 0 {
				photoHosts, err = c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
			}
			cloneHosts[user_id] = photoHosts
		}

		data, err := c.OneRow("SELECT race, country FROM " + c.MyPrefix + "my_table").Int64()
		myRace = c.Races[data["race"]]
		myCountry = consts.Countries[int(data["country"])]

		tplName = "assignments_new_miner"
		tplTitle = "assignmentsNewMiner"

	case 2:
		promisedAmountData, err = c.OneRow(`
				SELECT id,
							 currency_id,
							 amount,
							 user_id,
							 video_type,
							 video_url_id
				FROM promised_amount
				WHERE status =  'pending' AND
							 del_block_id = 0
				` + addSql + `
		`).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		promisedAmountData["currency_name"] = c.CurrencyList[utils.StrToInt64(promisedAmountData["currency_id"])]

		// проверим, не голосовали ли мы за это в последние 30 минут
		repeated, err := c.Single("SELECT id FROM "+c.MyPrefix+"my_tasks WHERE type  =  'promised_amount' AND id  =  ? AND time > ?", promisedAmountData["id"], utils.Time()-consts.ASSIGN_TIME).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if repeated > 0 {
			tplName = "assignments"
			tplTitle = "assignments"
			break
		}

		// если нету видео на ютубе, то получаем host юзера, где брать видео
		if promisedAmountData["video_url_id"] == "null" {
			videoHost, err = c.Single("SELECT http_host FROM miners_data WHERE user_id  =  ?", promisedAmountData["user_id"]).String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}

		// каждый раз обязательно проверяем, где находится юзер
		userInfo, err = c.OneRow(`
				SELECT latitude,
							 user_id,
							 longitude,
							 photo_block_id,
							 photo_max_miner_id,
							 miners_keepers,
							 http_host
				FROM miners_data
				WHERE user_id = ?
				`, promisedAmountData["user_id"]).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// получим ID майнеров, у которых лежат фото нужного нам юзера
		minersIds := utils.GetMinersKeepers(userInfo["photo_block_id"], userInfo["photo_max_miner_id"], userInfo["miners_keepers"], true)
		if len(minersIds) > 0 {
			photoHosts, err = c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}

		txType = "VotesPromisedAmount"
		txTypeId = utils.TypeInt(txType)
		timeNow = utils.Time()

		newPromiseAmount = strings.Replace(c.Lang["new_promise_amount"], "[amount]", promisedAmountData["amount"], -1)
		newPromiseAmount = strings.Replace(newPromiseAmount, "[currency]", promisedAmountData["currency_name"], -1)

		mainQuestion = strings.Replace(c.Lang["main_question"], "[amount]", promisedAmountData["amount"], -1)
		mainQuestion = strings.Replace(mainQuestion, "[currency]", promisedAmountData["currency_name"], -1)

		tplName = "assignments_promised_amount"
		tplTitle = "assignmentsPromisedAmount"

	default:
		tplName = "assignments"
		tplTitle = "assignments"
	}

	TemplateStr, err := makeTemplate(tplName, tplTitle, &AssignmentsPage{
		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,
		MainQuestion:       mainQuestion,
		NewPromiseAmount:   newPromiseAmount,
		MyRace:             myRace,
		MyCountry:          myCountry,
		ExamplePoints:      examplePoints,
		VideoHost:          videoHost,
		PhotoHosts:         photoHosts,
		PromisedAmountData: promisedAmountData,
		UserInfo:           userInfo,
		CloneHosts:         cloneHosts})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Example #15
0
func (c *Controller) GetMinerData() (string, error) {

	c.r.ParseForm()

	secs := float64(3600 * 24 * 365)

	userId := utils.StrToInt64(c.r.FormValue("userId"))
	if !utils.CheckInputData(userId, "int") {
		return `{"result":"incorrect userId"}`, nil
	}

	minersData, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", userId).String()
	if err != nil {
		return "", err
	}

	// получим ID майнеров, у которых лежат фото нужного нам юзера
	minersIds := utils.GetMinersKeepers(minersData["photo_block_id"], minersData["photo_max_miner_id"], minersData["miners_keepers"], false)
	hosts, err := c.GetList("SELECT http_host as host FROM miners_data WHERE miner_id IN (" + utils.JoinIntsK(minersIds, ",") + ")").String()
	if err != nil {
		return "", err
	}

	currencyList, err := c.GetCurrencyList(false)
	if err != nil {
		return "", err
	}

	_, _, promisedAmountListGen, err := c.GetPromisedAmounts(userId, c.Variables.Int64["cash_request_time"])
	log.Debug("promisedAmountListGen: %v", promisedAmountListGen)
	var data utils.DCAmounts
	if promisedAmountListGen[72].Amount > 0 {
		data = promisedAmountListGen[72]
	} else if promisedAmountListGen[23].Amount > 0 {
		data = promisedAmountListGen[23]
	} else {
		data = utils.DCAmounts{}
	}
	log.Debug("data: %v", data)

	promisedAmounts := ""
	prognosis := make(map[int64]float64)
	if data.Amount > 1 {
		promisedAmounts += RoundStr(utils.Float64ToStr(utils.Round(data.Amount, 0)), 0) + " " + currencyList[(data.CurrencyId)] + "<br>"
		prognosis[int64(data.CurrencyId)] += (math.Pow(1+data.PctSec, secs) - 1) * data.Amount
	}

	if len(promisedAmounts) > 0 {
		promisedAmounts = "<strong>" + promisedAmounts[:len(promisedAmounts)-4] + "</strong><br>" + c.Lang["promised"] + "<hr>"
	}

	/*
	 * На кошельках
	 * */

	balances, err := c.GetBalances(userId)
	if err != nil {
		return "", err
	}
	walletsByCurrency := make(map[int]utils.DCAmounts)
	for _, data := range balances {
		walletsByCurrency[int(data.CurrencyId)] = data
	}
	log.Debug("walletsByCurrency[72].Amount: %v", walletsByCurrency[72].Amount)
	if walletsByCurrency[72].Amount > 0 {
		data = walletsByCurrency[72]
	} else if walletsByCurrency[23].Amount > 0 {
		data = walletsByCurrency[23]
	} else {
		data = utils.DCAmounts{}
	}
	log.Debug("data: %v", data)

	wallets := ""
	var countersIds []string
	var pctSec float64
	if data.Amount > 0 {
		counterId := "map-" + utils.Int64ToStr(userId) + "-" + utils.Int64ToStr(data.CurrencyId)
		countersIds = append(countersIds, counterId)
		wallets = "<span class='dc_amount' id='" + counterId + "'>" + RoundStr(utils.Float64ToStr(data.Amount), 8) + "</span> d" + currencyList[(data.CurrencyId)] + "<br>"
		// прогноз
		prognosis[int64(data.CurrencyId)] += (math.Pow(1+data.PctSec, secs) - 1) * data.Amount
		pctSec = data.PctSec
	}

	if len(wallets) > 0 {
		wallets = wallets[:len(wallets)-4] + "<br>" + c.Lang["on_the_account"] + "<hr>"
	}

	/*
	 * Годовой прогноз
	 * */
	prognosisHtml := ""
	for currencyId, amount := range prognosis {
		if amount < 0.01 {
			continue
		} else if amount < 1 {
			amount = utils.Round(amount, 2)
		} else {
			amount = amount
		}
		prognosisHtml += "<span class='amount_1year'>" + RoundStr(utils.Float64ToStr(amount), 2) + " d" + currencyList[(currencyId)] + "</span><br>"
	}
	if len(prognosisHtml) > 0 {
		prognosisHtml = prognosisHtml[:len(prognosisHtml)-4] + "<br> " + c.Lang["profit_forecast"] + " " + c.Lang["after_1_year"]
	}

	prognosisHtml = ""

	result_ := minersDataType{Hosts: hosts, Lnglat: map[string]string{"lng": minersData["longitude"], "lat": minersData["latitude"]}, Html: promisedAmounts + wallets + "<div style=\"clear:both\"></div>" + prognosisHtml + "</p>", Counters: countersIds, PctSec: pctSec}
	log.Debug("result_", result_)
	result, err := json.Marshal(result_)
	if err != nil {
		return "", err
	}
	log.Debug(string(result))
	return string(result), nil
}
Example #16
0
func (p *Parser) VotesComplex() error {

	currencyVotes := make(map[string][]float64)

	if p.BlockData.BlockId > 77951 {
		vComplex, err := makeVcomplex(p.TxMap["json_data"])
		if err != nil {
			return p.ErrInfo(err)
		}
		currencyVotes = vComplex.Currency
		// голоса за реф. %
		p.selectiveLoggingAndUpd([]string{"first", "second", "third"}, []interface{}{vComplex.Referral["first"], vComplex.Referral["second"], vComplex.Referral["third"]}, "votes_referral", []string{"user_id"}, []string{string(p.TxMap["user_id"])})

		// раньше не было выборов админа
		if p.BlockData.BlockId >= 153750 && vComplex.Admin > 0 {
			p.selectiveLoggingAndUpd([]string{"admin_user_id", "time"}, []interface{}{vComplex.Admin, p.TxTime}, "votes_admin", []string{"user_id"}, []string{string(p.TxMap["user_id"])})
		}

	} else { // раньше не было рефских и выбора админа
		vComplex := make(map[string][]float64)
		err := json.Unmarshal(p.TxMap["json_data"], &vComplex)
		if err != nil {
			return p.ErrInfo(err)
		}
		currencyVotes = vComplex
	}

	var currencyIds []int
	for k := range currencyVotes {
		currencyIds = append(currencyIds, utils.StrToInt(k))
	}
	sort.Ints(currencyIds)
	//sort.Sort(sort.Reverse(sort.IntSlice(keys)))

	for _, currencyId := range currencyIds {

		data := currencyVotes[utils.IntToStr(currencyId)]
		currencyIdStr := utils.IntToStr(currencyId)
		UserIdStr := string(p.TxMap["user_id"])
		// miner_pct
		err := p.selectiveLoggingAndUpd([]string{"pct", "time"}, []interface{}{utils.Float64ToStr(data[0]), p.TxTime}, "votes_miner_pct", []string{"user_id", "currency_id"}, []string{UserIdStr, currencyIdStr})
		if err != nil {
			return p.ErrInfo(err)
		}

		// user_pct
		err = p.selectiveLoggingAndUpd([]string{"pct"}, []interface{}{utils.Float64ToStr(data[1])}, "votes_user_pct", []string{"user_id", "currency_id"}, []string{UserIdStr, currencyIdStr})
		if err != nil {
			return p.ErrInfo(err)
		}

		// max_promised_amount
		err = p.selectiveLoggingAndUpd([]string{"amount"}, []interface{}{int64(data[2])}, "votes_max_promised_amount", []string{"user_id", "currency_id"}, []string{UserIdStr, currencyIdStr})
		if err != nil {
			return p.ErrInfo(err)
		}

		// max_other_currencies
		err = p.selectiveLoggingAndUpd([]string{"count"}, []interface{}{int64(data[3])}, "votes_max_other_currencies", []string{"user_id", "currency_id"}, []string{UserIdStr, currencyIdStr})
		if err != nil {
			return p.ErrInfo(err)
		}

		// reduction
		err = p.selectiveLoggingAndUpd([]string{"pct", "time"}, []interface{}{int64(data[4]), p.TxTime}, "votes_reduction", []string{"user_id", "currency_id"}, []string{UserIdStr, currencyIdStr})
		if err != nil {
			return p.ErrInfo(err)
		}

		// проверим, не наш ли это user_id
		myUserId, myBlockId, myPrefix, _, err := p.GetMyUserId(p.TxUserID)
		if err != nil {
			return p.ErrInfo(err)
		}

		if p.TxUserID == myUserId && myBlockId <= p.BlockData.BlockId {
			// отметимся, что голосовали, чтобы не пришло уведомление о необходимости голосовать раз в 2 недели
			// может быть дубль, поэтому ошибки не проверяем
			p.ExecSql("INSERT INTO "+myPrefix+"my_complex_votes ( last_voting ) VALUES ( ? )", p.BlockData.Time)
		}
	}

	return nil
}