update_create is creating new feilds instead of updating total - django

payments = list((expense
.annotate(month=Month('startDate'))
.values('month')
.annotate(total=Sum('cost'))
.order_by('month')))
for i in payments:
paymentMonths = (i["month"])
paymentTotal= (i["total"])
obj, created = Payment.objects.update_or_create(
author=curruser,
date=paymentMonths,
total = paymentTotal,
defaults={"total": paymentTotal},
)
totalcost = Payment.objects.filter(author = curruser.id)
Apparently, it should update the (date = 12) total but it is making new ones with the updated value, it might be because the totaldate is diff or maybe I'm wrong it is confusing

I believe you just need to omit total = paymentTotal from your arguments.
obj, created = Payment.objects.update_or_create(
author=curruser,
date=paymentMonths,
defaults={"total": paymentTotal},
)
This is because it is querying the DB to see if a Payment with that total already exists, and if it doesn't, it's creating a new one. Instead, you want to query Payments with curruser as the author and with date as paymentMonths, while only updating total with the new paymentTotal

Related

Corda - problem using VaultCustomQueryCriteria

I'm trying to use a VaultCustomQueryCriteria (Corda - Java) with the aggregate function SUM, but I get no results.
If I use another VaultCustomQueryCriteria, the query works.
What am I doing wrong?
Below some examples:
Query OK:
QueryCriteria statusCriteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED);
Field name = ExampleSchemaV1.Ingestion.class.getDeclaredField("name");
QueryCriteria countCriteria = new QueryCriteria.VaultCustomQueryCriteria(Builder.equal(name, "Mark"));
List<StateAndRef<IngestionState>> results = rpcOps.vaultQueryByCriteria(countCriteria,IngestionState.class).getStates();
Query KO: (no results)
QueryCriteria statusCriteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED);
Field nr = ExampleSchemaV1.Ingestion.class.getDeclaredField("nr");
Field name = ExampleSchemaV1.Ingestion.class.getDeclaredField("name");
CriteriaExpression sumQta = Builder.sum(nr, Arrays.asList(name));
QueryCriteria sumQtaCriteria = new QueryCriteria.VaultCustomQueryCriteria(sumQta);
QueryCriteria criteria = statusCriteria.and(sumQtaCriteria);
List<StateAndRef<IngestionState>> results = rpcOps.vaultQueryByCriteria(criteria,IngestionState.class).getStates();
Each vault query returns a Vault.Page object. When performing a sum query, the result of the sum is accessible via Vault.Page.getOtherResults(), rather than via Vault.Page.getStates().
This is because the sum query doesn't return any actual states, but rather the result of a computation over these states.

How to change UnitPrice via Dynamics GP API

I would like to change UnitPrice when create an order via Dynamics GP API,
So I run next code:
// Create a sales order object
var salesOrder = new SalesOrder();
// Create a sales document type key for the sales order
var salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
// Populate the document type key of the sales order object
salesOrder.DocumentTypeKey = salesOrderType;
// Create a customer key
var customerKey = new CustomerKey();
customerKey.Id = customerSummary[0].Key.Id;
// Set the customer key property of the sales order object
salesOrder.CustomerKey = customerKey;
// Create a batch key
var batchKey = new BatchKey();
batchKey.Id = "01-INBOUND";
// Set the batch key property of the sales order object
salesOrder.BatchKey = batchKey;
// Create a sales order line to specify the ordered item
var salesOrderLine = new SalesOrderLine();
// Create an item key
var orderedItem = new ItemKey();
orderedItem.Id = "AA1111";
// Set the item key property of the sales order line object
salesOrderLine.ItemKey = orderedItem;
// Create a sales order quantity object
var orderedAmount = new Quantity();
orderedAmount.Value = 1;
// Set the quantity of the sales order line object
salesOrderLine.Quantity = orderedAmount;
// THIS DOESN'T WORK
salesOrderLine.UnitPrice = new MoneyAmount { Value = 1.11m, Currency = "USD" };
// Discount works ok
// salesOrderLine.Discount = new MoneyPercentChoice { Item = new MoneyAmount { Value = 1.25m } };
// Create an array of sales order lines
// Initialize the array with sales order line object
SalesOrderLine[] orders = { salesOrderLine };
// Add the sales order line array to the sales order
salesOrder.Lines = orders;
// Get the create policy for the sales order object
var salesOrderCreatePolicy = dynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
// Create the sales order
dynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
But line to change UnitPrice doesn't work.
salesOrderLine.UnitPrice = new MoneyAmount { Value = 1.11m, Currency = "USD" };
What I'm doing wrong? Appreciate any help.
Thank you!
Found solution:
In Dynamics GP Web Service Policy Configuration for Update Sales
Invoice Policy, you need to update the “Calculate Unit Price Behavior”
to “Do Not Calculate”.
Also, make Sure that you have selected the right Company and assigned
proper roles for the policy. The role should not be Default.
Source: https://www.cloudfronts.com/dynamics-gp-sales-invoice-unit-price-always-0/

Dynamodb pagination of 10 results

I have a message table which I would like to get the last 10 messages for that user and if they click more it would retrieve another 10 until there were no more message left. I could not see how to do this, so far I am able to get message based on time, but this is not exactly what I want. Reading through the documentation I can see it a method called LastEvaluatedKey, but where and how do I use this I can't find a working example of this. This is my code for time:
long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String startDate = df.format(startDateMilli);
String endDate = df.format(endDateMilli);
QuerySpec spec = new QuerySpec()
.withProjectionExpression("to,fr,sta,cr")
.withKeyConditionExpression("to = :v_to and cr between :v_start_dt and :v_end_dt")
.withValueMap(new ValueMap()
.withString(":v_id", username)
.withString(":v_start_dt", startDate)
.withString(":v_end_dt", endDate));
ItemCollection<QueryOutcome> items = table.query(spec);
System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
How can I modify this to eliminate the time based pagination and use instead a last 10 messages type of pagination?

What is the preferred method of updating Money fields in Dynamics CRM 2013 via Web Services?

I have an entity in CRM that has some Money fields on them. At the time of the creation of the entity there is no value for those fields, so the entity is created and saved. However if I then have values and go to update them (either through the UI or Web Services) I basically get an error stating "The currency cannot be null".
In the UI:
I then get a red circle with an X through it if I go to update the value.
In the code (web service call):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
I then get the "The currency cannot be null" on the .SaveChanges() call.
In the code (second attempt):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
var crmCurrency = crmService.TransactionCurrencySet.Where(c => c.ISOCurrencyCode == "AUD").First();
crmService.SetLink(crmAccount, "TransactionCurrency_Account", crmCurrency);
//crmService.SaveChanges() /* tried with this uncommented as well to try and "set currency" before setting value */
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
So this attempt fails in the same way, however if I run it a second time (without the currency and SetLink) so that the currency was saved before then it does work - hence the atempt to do a second .SaveChanges() but really need it to sort of work the first time through.
In the code (third attempt):
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.athos_MoneyValueItem= new CrmServiceReference.Money() { Value = 10.0m };
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
This doesn't appear to work either
When you create a new record containing a Money field (or updating an existing one where no Money fields are filled before) , you need to specify the currency, the right field to set is TransactionCurrencyId (logical name transactioncurrencyid), it's a lookup (so inside the code is an EntityReference) to the currency entity.
assuming you have the Guid of your currency stored inside the currencyId variable:
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.TransactionCurrencyId = new EntityReference(TransactionCurrency.LogicalName, currencyId);
crmAccount.myitems_MoneyValueItem = new Money(10.0m); //better to update the money field with this syntax
crmService.UpdateObject(crmAccount);
crmService.SaveChanges()
CRM 2013 expects a Money object for a currency field.
crmAccount.myitems_MoneyValueItem = new Money(10.0m);
You shouldn't have to explicitly declare a currency unless your CRM organization doesn't have a default currency set (and since you need to set this when creating an organization, it should always be set).
It looks like if I do a lookup on currency (shame as an extra data call) and then use that to set the TransactionCurrencyId it then "works" ... seems like I shouldn't have to do this as I do have a default set for the organisation though. But this does appear to be working in that it results in being able to update those fields.
var crmCurrency = crmService.TransactionCurrencySet.Where(c => c.ISOCurrencyCode == currencyCode).First();
var crmService = new CrmServiceReference.IFAAContext(new Uri(crmWebServicesUrl));
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
var crmAccount = crmService.AccountSet.Where(a => a.AccountId == accountId).FirstOrDefault();
crmAccount.TransactionCurrencyId = new CrmServiceReference.EntityReference() { Id = crmCurrency.TransactionCurrencyId, LogicalName = "transactioncurrency", Name = crmCurrency.CurrencyName };
crmAccount.myitems_MoneyValueItem.Value = 10.0m;
crmService.UpdateObject(crmAccount);
crmService.SaveChanges();
i am doing the same thing as you but unable to set the money field value during service.create.
I have already put in
entity.Attributes["transactioncurrencyid"] = currencyGuid;
entity.Attributes["new_moneyfield"] = new Money(123.45M);
but in the end, the record is created with the transactioncurrency field populated, while the money field is blank.
Its a custom workflow on CRM online 2016 by the way..

Great Plains Find Sales Orders

I have created sales orders in Great Plains, however, I cannot find them in the right place in the system. Although my code executes without any errors, I do not find this transaction under Sales > All Sales Transactions. Instead, I see them under Sales > Sales Documents.
Is it in a pending state?
public void CreateOrder()
{
CompanyKey companyKey;
Context context;
SalesOrder salesOrder;
SalesDocumentTypeKey salesOrderType;
CustomerKey customerKey;
BatchKey batchKey;
SalesOrderLine salesOrderLine;
ItemKey orderedItem;
Quantity orderedAmount;
Policy salesOrderCreatePolicy;
// Create a context with which to call the service
context = new Context();
// Specify which company to use (sample company)
companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
// Create a sales order object
salesOrder = new SalesOrder();
// Create a sales document type key for the sales order
salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
// Populate the document type key of the sales order object
salesOrder.DocumentTypeKey = salesOrderType;
// Create a customer key
customerKey = new CustomerKey();
customerKey.Id = "JONESJ008";
// Set the customer key property of the sales order object
salesOrder.CustomerKey = customerKey;
// Create a batch key
batchKey = new BatchKey();
batchKey.Id = "SALES ORDERS";
// Set the batch key property of the sales order object
salesOrder.BatchKey = batchKey;
// Create a sales order line to specify the ordered item
salesOrderLine = new SalesOrderLine();
// Create an item key
orderedItem = new ItemKey();
orderedItem.Id = "32X IDE";
// Set the item key property of the sales order line object
salesOrderLine.ItemKey = orderedItem;
// Create a sales order quantity object
orderedAmount = new Quantity();
orderedAmount.Value = 4;
// Set the quantity of the sales order line object
salesOrderLine.Quantity = orderedAmount;
// Create an array of sales order lines
// Initialize the array with sales order line object
SalesOrderLine[] orders = { salesOrderLine };
// Add the sales order line array to the sales order
salesOrder.Lines = orders;
// Get the create policy for the sales order object
salesOrderCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
// Create the sales order
wsDynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
}
I have looked in Sales > All Sales Transactions. I can use the API to pull this order out. I am using the sample company file, Fabrikam, Inc. Here's how I set up my context:
public GPOrders()
{
wsDynamicsGP = new DynamicsGP();
// Be sure the default credentials are used
wsDynamicsGP.UseDefaultCredentials = true;
// Create a context with which to call the web service
context = new Context();
// Specify which company to use (sample company)
companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
context.CultureName = "en-US";
}
I found them under Sales > Sales Documents. The transactions never posted, so they weren't under Sales > All Sales Transactions.