Exemple #1
0
        public async Task <IActionResult> EditTransaction(int id, [FromBody] ApiTransaction model)
        {
            var transaction = await _uow.Transactions.GetByIdAsync(model.Id);

            var category = await _uow.Categories.GetByIdAsync(model.Category.Id);

            if (transaction != null)
            {
                transaction.DateModified = DateTime.UtcNow;
                transaction.Date         = model.Date;
                transaction.CategoryId   = category.Id;
                transaction.Category     = category;

                decimal delta = 0;
                if (transaction.Amount != model.Amount)
                {
                    delta = transaction.Amount - model.Amount;
                }

                transaction.Amount = model.Amount;

                _uow.Transactions.Update(transaction);

                UpdateTransaction(model, category, delta);

                await _uow.CommitAsync();

                model = _mapper.Map <Transaction, ApiTransaction>(transaction);
                return(new JsonResult(model));
            }

            return(new NotFoundResult());
        }
        public async Task <IActionResult> EditTransaction([FromBody] ApiTransaction model)
        {
            var transaction = await _uow.Transactions.GetByIdAsync(model.Id);

            var category = await _uow.Categories.GetByIdAsync(model.Category.Id);

            if (transaction != null)
            {
                transaction.DateModified = DateTime.UtcNow;
                transaction.Date         = model.Date;
                transaction.CategoryId   = category.Id;
                transaction.Category     = category;
                transaction.Amount       = model.Amount;
                transaction.Resolved     = model.Resolved;
                transaction.Notes        = model.Notes;

                _uow.Transactions.Update(transaction);

                UpdateTransaction(model);

                await _uow.CommitAsync();

                model = _mapper.Map <Transaction, ApiTransaction>(transaction);
                return(new JsonResult(model));
            }

            return(new NotFoundResult());
        }
        /// <summary>
        /// Broadcast a ledger to blockchain network.
        /// </summary>
        /// <param name="record">A ledger to broadcast.</param>
        /// <param name="waitForConfirm">Wait for ledger to store in a blockchain (Optional, default is true)</param>
        /// <returns>None. Transaction ID will be attached to the ledger object instead.</returns>
        public async Task BroadcastLedger(Ledger record, bool waitForConfirm = true)
        {
            var hexData     = record.GetOP_RETURN();
            var transaction = await api.BuildTransaction(userPrivateKey, record.UtxoReceiver, record.TokenReceiver, hexData);

            var tx = await api.BroadcastTransaction(transaction);

            record.TxId = tx.txid;

            if (waitForConfirm)
            {
                var currentTx = new ApiTransaction();
                while (currentTx.blocktime == 0)
                {
                    currentTx = await api.GetTransactionInfo(tx.txid);

                    record.Blockheight = currentTx.blockheight;
                    Thread.Sleep(3000);
                }
                record.Status          = ProcessStatus.NotProcessed;
                record.TokenSenderHash = userPrivateKey.PubKeyHash.ToBytes();
                ledger.Upsert(record);
                ledger.EnsureIndex(l => l.TxId);
                ledger.EnsureIndex(l => l.Blockheight);
                ledger.EnsureIndex(l => l.Operation);
                ledger.EnsureIndex(l => l.TokenSenderHash);
                ledger.EnsureIndex(l => l.TokenReceiverHash);
                ledger.EnsureIndex(l => l.Time);
            }
            else
            {
                record.Status = ProcessStatus.NotDefined;
            }
        }
Exemple #4
0
        public async Task <IActionResult> AddTransaction([FromBody] ApiTransaction model)
        {
            var budget = await _uow.Budgets.GetByIdAsync(model.BudgetId);

            var category = await _uow.Categories.GetByIdAsync(model.Category.Id);

            var transaction = new Transaction
            {
                DateAdded  = DateTime.UtcNow,
                BudgetId   = budget.Id,
                Budget     = budget,
                CategoryId = category.Id,
                Category   = category,
                Date       = model.Date,
                Amount     = model.Amount,
                UserId     = Token.UserId
            };

            await _uow.Transactions.AddAsync(transaction);

            UpdateTransaction(model, category, 0);

            await _uow.CommitAsync();

            model = _mapper.Map <Transaction, ApiTransaction>(transaction);

            return(new JsonResult(model));
        }
        public ApiTransaction CreateApiTransaction(
            AddApiTransactionRequest addApiTransactionRequest)
        {
            ApiTransaction apiTransaction =
                Create <AddApiTransactionRequest, ApiTransaction>(addApiTransactionMapper,
                                                                  addApiTransactionRequest);

            return(apiTransaction);
        }
        public ApiTransaction CreateRefundApiTransaction(ApiTransaction src)
        {
            ApiTransaction apiTransaction =
                Create <ApiTransaction, ApiTransaction>(addApiTransactionMapper, src);

            apiTransaction.transactionType = ApiTransactionType.rsl.GetDescription();
            apiTransaction.amount         *= -1;
            apiTransaction.notes           = $"refund for cancel:{src.transactionNumber}";
            return(apiTransaction);
        }
Exemple #7
0
            public void PostBroadcastTransactionInvalidTokenTest(string token)
            {
                var model = new ApiTransaction()
                {
                    Hex = TestData.GenerateString(8), Id = TestData.GenerateString(12)
                };
                var response = walletApi.BroadcastTransaction.PostBroadcastTransaction(model, token);

                response.Validate.StatusCode(HttpStatusCode.Unauthorized);
            }
Exemple #8
0
        private void UpdateTransaction(ApiTransaction model, Category category, decimal delta)
        {
            if (category.Type == CategoryType.Outgoing)
            {
                var outgoing = _uow.Outgoings.GetAll()
                               .Where(x => x.BudgetId == model.BudgetId)
                               .Where(x => x.CategoryId == model.Category.Id)
                               .FirstOrDefault();

                if (outgoing != null)
                {
                    outgoing.DateModified = DateTime.UtcNow;

                    if (delta == 0)
                    {
                        outgoing.Actual   += model.Amount;
                        outgoing.Remaining = outgoing.Remaining - model.Amount;
                    }
                    else
                    {
                        outgoing.Actual    -= delta;
                        outgoing.Remaining -= delta;
                    }

                    _uow.Outgoings.Update(outgoing);
                }
            }

            if (category.Type == CategoryType.Income)
            {
                var income = _uow.Incomes.GetAll()
                             .Where(x => x.BudgetId == model.BudgetId)
                             .Where(x => x.CategoryId == model.Category.Id)
                             .FirstOrDefault();

                if (income != null)
                {
                    income.DateModified = DateTime.UtcNow;

                    if (delta == 0)
                    {
                        income.Actual += model.Amount;
                    }
                    else
                    {
                        income.Actual -= delta;
                    }

                    _uow.Incomes.Update(income);
                }
            }
        }
        private void UpdateTransaction(ApiTransaction model)
        {
            if (model.Category.Type == CategoryType.Income)
            {
                var income = _uow.Incomes.GetAll()
                             .Where(x => x.BudgetId == model.BudgetId)
                             .Where(x => x.CategoryId == model.Category.Id)
                             .FirstOrDefault();

                if (income != null)
                {
                    income.Resolved     = model.Resolved;
                    income.DateModified = DateTime.UtcNow;
                    income.Total        = model.Amount;

                    _uow.Incomes.Update(income);
                }
            }
            else if (model.Category.Type == CategoryType.Dedicated || model.Category.Type == CategoryType.Variable)
            {
                var outgoing = _uow.Outgoings.GetAll()
                               .Where(x => x.BudgetId == model.BudgetId)
                               .Where(x => x.CategoryId == model.Category.Id)
                               .FirstOrDefault();

                if (outgoing != null)
                {
                    outgoing.DateModified = DateTime.UtcNow;
                    outgoing.Resolved     = model.Resolved;
                    outgoing.Actual      += model.Amount;
                    outgoing.Remaining    = outgoing.Remaining - model.Amount;

                    _uow.Outgoings.Update(outgoing);
                }
            }
            else if (model.Category.Type == CategoryType.Savings)
            {
                var saving = _uow.Savings.GetAll()
                             .Where(x => x.BudgetId == model.BudgetId)
                             .Where(x => x.CategoryId == model.Category.Id)
                             .FirstOrDefault();

                if (saving != null)
                {
                    saving.DateModified = DateTime.UtcNow;
                    saving.Resolved     = model.Resolved;
                    saving.Total        = model.Amount;

                    _uow.Savings.Update(saving);
                }
            }
        }
Exemple #10
0
            public void PostBroadcastTransactionInvalidTransactionTest()
            {
                var newUser          = new AccountRegistrationModel().GetTestModel();
                var registeredClient = walletApi.Registration.PostRegistrationResponse(newUser).GetResponseObject();
                var model            = new ApiTransaction()
                {
                    Hex = TestData.GenerateString(8), Id = TestData.GenerateString(12)
                };
                var response = walletApi.BroadcastTransaction.PostBroadcastTransaction(model, registeredClient.Result.Token);

                response.Validate.StatusCode(HttpStatusCode.OK);
                Assert.That(response.GetResponseObject().Error, Is.Not.Null);
            }
        public static string GetOwnerAddress(this ApiTransaction transaction)
        {
            var inAddr  = transaction.vin.FirstOrDefault(v => v.addr != null).addr;
            var outAddr = transaction.vout.FirstOrDefault(v => v.scriptPubKey.addresses != null).scriptPubKey.addresses.FirstOrDefault();

            if (inAddr == outAddr)
            {
                return(inAddr);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Extract ConsentAction information from OP_RETURN part
        /// </summary>
        /// <param name="transaction">The transaction to be extracted information from</param>
        /// <returns>If information is present, ConsentAction object is returned. Otherwise, null is returned.</returns>
        public static ConsentAction AsConsentAction(this ApiTransaction transaction)
        {
            try
            {
                var ca        = new ConsentAction();
                var op_return = transaction.GetOP_RETURN();
                if (string.IsNullOrEmpty(op_return) || !op_return.StartsWith("43504d4f2d5448"))
                {
                    return(null);
                }

                var firstIndex = op_return.IndexOf("3a");
                ca.Domain = Encoding.ASCII.GetString(FromHex(op_return.Substring(0, firstIndex)));
                var secondIndex = op_return.IndexOf("3a", firstIndex + 2);
                var action      = Encoding.ASCII.GetString(FromHex(op_return.Substring(firstIndex + 2, secondIndex - firstIndex - 2)));
                ca.DocumentHash = op_return.Substring(secondIndex + 2);

                if (ca.DocumentHash.Length > 64)
                {
                    return(null);
                }

                if (action == "ASK")
                {
                    ca.AskFrom     = transaction.vin[0].addr;
                    ca.AskTxId     = transaction.txid;
                    ca.AskTick     = transaction.blocktime;
                    ca.ApproveFrom = transaction.vout.First(v => v.scriptPubKey.addresses != null && v.scriptPubKey.addresses[0] != ca.AskFrom).scriptPubKey.addresses[0];
                    return(ca);
                }
                else if (action == "APPROVE")
                {
                    ca.ApproveFrom  = transaction.vin[0].addr;
                    ca.AskFrom      = transaction.vout.First(v => v.scriptPubKey.addresses != null && v.scriptPubKey.addresses[0] != ca.AskFrom).scriptPubKey.addresses[0];
                    ca.ApproveTxId  = transaction.txid;
                    ca.ApprovedTick = transaction.blocktime;
                    return(ca);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #13
0
        public async Task <IActionResult> DeleteTransaction(int id, [FromBody] ApiTransaction model)
        {
            var transaction = await _uow.Transactions.GetByIdAsync(id);

            var category = await _uow.Categories.GetByIdAsync(model.Category.Id);

            if (transaction != null)
            {
                UpdateTransaction(model, category, transaction.Amount);
                model.Amount = 0;
            }

            _uow.Transactions.Delete(id);
            await _uow.CommitAsync();

            return(new JsonResult(model));
        }
Exemple #14
0
        private async Task <PaypalRecordDto> AddTopUpApiTransactionViaAdminApi(PaypalRecordDto paypalRecordDto,
                                                                               AddApiTransactionRequest addApiTransactionRequest)
        {
            AddApiTransactionResponse addApiTransactionResponse = new AddApiTransactionResponse();

            try
            {
                addApiTransactionRequest.transactionType = topUpTransactionType;
                var api = this._myDbContext.Apis.Where(s => s.apiKey.ToString() == addApiTransactionRequest.userApiKey).FirstOrDefault();
                addApiTransactionRequest.apiId    = api.apiId;
                addApiTransactionRequest.createBy = api.apiId.ToString();
                ApiTransaction request = _addApiTransactionMapper.CreateApiTransaction(addApiTransactionRequest);

                string query =
                    "call P_AddApiTransaction(@apiId,@headId,@currencyCode,@transactionType,@amount,@notes,@createBy)";
                MySqlParameter pApiId           = new MySqlParameter("@apiId", request.apiId);
                MySqlParameter pHeadId          = new MySqlParameter("@headId", request.headId);
                MySqlParameter pCurrencyCode    = new MySqlParameter("@currencyCode", request.currencyCode);
                MySqlParameter pTransactionType = new MySqlParameter("@transactionType", request.transactionType);
                MySqlParameter pAmount          = new MySqlParameter("@amount", request.amount);
                MySqlParameter pNotes           = new MySqlParameter("@notes", request.notes);
                MySqlParameter pCreateBy        = new MySqlParameter("@createBy", request.createBy);

                var data = this._myDbContext.ApiTransactions.FromSqlRaw(query, pApiId, pHeadId, pCurrencyCode,
                                                                        pTransactionType,
                                                                        pAmount, pNotes, pCreateBy).AsNoTracking().AsEnumerable().ToList().FirstOrDefault();

                addApiTransactionResponse.apiTransactionId  = data.apiTransactionId;
                addApiTransactionResponse.transactionNumber = data.transactionNumber;
            }
            catch (Exception ex)
            {
                var aa = ex.ToString();
                addApiTransactionResponse = JsonConvert.DeserializeObject <AddApiTransactionResponse>(ex.Message) ??
                                            ErrorAddApiTransactionResponse();
                paypalRecordDto.resultMessage = addApiTransactionResponse.meta.error["message"];
            }

            if (paypalRecordDto.resultMessage.IsNullOrEmpty())
            {
                paypalRecordDto.paypalRecordPayload.apiTransactionNumber = addApiTransactionResponse.transactionNumber;
                paypalRecordDto.paypalRecordPayload.apiTransactionId     = addApiTransactionResponse.apiTransactionId;
            }

            return(paypalRecordDto);
        }
 public async Task <ApiUserTransactionsResponse> GetTransactions(ApiTransaction request)
 {
     try
     {
         return(await ApiPrivateService.GetUserTransactions(new ApiUserTransactionsRequest
         {
             Count = request.Count,
             Type = request.Type,
             UserId = new Guid(User.Identity.Name)
         }));
     }
     catch (Exception)
     {
         return(new ApiUserTransactionsResponse {
             Success = false, Error = "Bad Request"
         });
     }
 }
        public static Ledger ToLedger(this ApiTransaction transaction, WalletContract contract, ContractService service)
        {
            var ledger = new Ledger()
            {
                TxId        = transaction.txid,
                Blockheight = transaction.blockheight,
                Time        = new DateTime(1970, 1, 1).AddSeconds(transaction.blocktime)
            };
            var domain = BitConverter.ToString(Encoding.Default.GetBytes("RMUTSB.AC.TH")).Replace("-", "").ToLower();
            //var domain = "54534357414c4c4554";
            var data = transaction.GetOP_RETURN();

            try
            {
                if (data.StartsWith(domain))
                {
                    return(null);
                }
                var contractNameHex = data.Substring(0, 16);
                if (contract.NameHex == contractNameHex)
                {
                    ledger.Operation = (OperationCode)(ushort.Parse(data.Substring(16, 4), System.Globalization.NumberStyles.HexNumber));
                    var publicAddress = transaction.vin.First(v => !string.IsNullOrEmpty(v.addr)).addr;
                    var publicKey     = new BitcoinPubKeyAddress(publicAddress, service.MainNetwork);
                    ledger.TokenSenderHash      = publicKey.ExtractWitnessProgram();
                    ledger.TokenReceiverHashHex = data.Substring(20, 40);
                    ledger.Amount = BitConverterExtension.ToDecimal(data.Substring(60, 32).StringToByteArray());
                    if (data.Length > 92)
                    {
                        ledger.ReferenceCode = Encoding.Default.GetString(data.Substring(92).StringToByteArray());
                    }
                    return(ledger);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(null);
            }
        }
        public static string GetOP_RETURN(this ApiTransaction transaction)
        {
            var tx = transaction.vout.FirstOrDefault(v => v.scriptPubKey.hex.StartsWith("6a"));

            if (tx != null)
            {
                if (tx.scriptPubKey.hex.StartsWith("6a4c50"))
                {
                    return(tx.scriptPubKey.hex.Substring(6).ToLower());
                }
                else
                {
                    return(tx.scriptPubKey.hex.Substring(4).ToLower());
                }
            }
            else
            {
                return(null);
            }
        }
 public static string GetFirstSender(this ApiTransaction transaction)
 {
     return(transaction.vin.First(vin => !string.IsNullOrEmpty(vin.addr)).addr);
 }
Exemple #19
0
 public IResponse <ResponseModel> PostBroadcastTransaction(ApiTransaction model, string token)
 {
     return(Request.Post(resource).AddJsonBody(model).WithBearerToken(token).Build().Execute <ResponseModel>());
 }
 public static bool CheckReceiverExists(this ApiTransaction transaction, string publicKey)
 {
     return(transaction.vout.Exists(vout => vout.scriptPubKey.addresses != null && vout.scriptPubKey.addresses.Contains(publicKey)));
 }
 public static bool CheckReceiverAmount(this ApiTransaction transaction, string publicKey, decimal matchValue)
 {
     return(transaction.vout.Exists(vout => vout.scriptPubKey.addresses != null && vout.scriptPubKey.addresses.Contains(publicKey) &&
                                    decimal.Parse(vout.value) == matchValue));
 }
 public static bool CheckSenderExists(this ApiTransaction transaction, string publicKey)
 {
     return(transaction.vin.Exists(vin => vin.addr == publicKey));
 }
 public async Task DeleteTransaction(int id, [FromBody] ApiTransaction model)
 {
     UpdateTransaction(model);
     _uow.Transactions.Delete(id);
     await _uow.CommitAsync();
 }
 public void AssignAddApiTransactionResponse(ApiTransaction src, AddApiTransactionResponse des)
 {
     Assign <ApiTransaction, AddApiTransactionResponse>(addApiTransactionMapper, src, des);
 }