How to update sales orders in acumatica using API - soap

I'm not able to update my sales orders in acumatica using SOAP API.
Whenever i try to save with ORDERNBR it's save new order.
This is my code:
$Customer = new Value();
$Customer->Value = 'C000006';//$data['Customer'];
$Customer->FieldName = 'CustomerID';
$Customer->ObjectName = 'Document';
$Terms = new Value();
$Terms->Value = 'NET';
$Terms->FieldName = 'TermsID';
$Terms->ObjectName = 'CurrentDocument: 1';
$OrderType = new Value();
$OrderType->Value = $data['OrderType'];
$OrderType->FieldName = 'OrderType';
$OrderType->ObjectName = 'Document';
$Date = new Value();
$Date->Value = $data['Date'];
$Date->FieldName = 'OrderDate';
$Date->ObjectName = 'Document';
$RequestedOn = new Value();
$RequestedOn->Value = $data['RequestedOn'];
$RequestedOn->FieldName = 'RequestDate';
$RequestedOn->ObjectName = 'Document';
$CustomerOrder = new Value();
$CustomerOrder->Value = $data['CustomerOrder'];
$CustomerOrder->FieldName = 'CustomerOrderNbr';
$CustomerOrder->ObjectName = 'Document';
$Status = new Value();
$Status->Value = $data['Status'];
$Status->FieldName = 'Status';
$Status->ObjectName = 'Document';
$Currency = new Value();
$Currency->Value = $data['Currency'];
$Currency->FieldName = 'CuryID';
$Currency->ObjectName = 'Document';
$nbr = new Value();
$nbr->Value = '100064';
$nbr->FieldName = 'OrderNbr';
$nbr->ObjectName = 'Document';
//$nbr->LinkedCommand = $SO301000Content->GetSchemaResult->OrderSummary->OrderNbr;
//$SO301000Content->GetSchemaResult->OrderSummary->OrderNbr->Value = '100064';
//echo '<pre>';print_r($SO301000Content->GetSchemaResult->DocumentDetails->ServiceCommands);die;
$context->SO301000Clear();
$commands = array(
$Customer,
$Terms,
$OrderType,
$Date,
$RequestedOn,
$Status,
$CustomerOrder,
$Currency,
$nbr,
//$SO301000Content->GetSchemaResult->OrderSummary->CopyOrder,
//$SO301000Content->GetSchemaResult->OrderSummary->OrderNbr,
);
$commands[] = $SO301000Content->GetSchemaResult->Actions->Insert;
$commands[] = $SO301000Content->GetSchemaResult->OrderSummary->OrderNbr;
//echo '<pre>';print_r($commands);die;
$arr = array(
'commands'=>$commands,
);
$cus = $context->__soapCall('SO301000Submit', array($arr));

OrderType and OrderNbr must be set first in your command list, this way Acumatica will first navigate to the entry, and then update it.

Related

Woocommerce Custom Place Order API not working cart empty

public function RetriveCart($request){
global $woocommerce;
$woocommerce->frontend_includes();
$user_id = $request['user_id'];
wp_set_current_user( $user_id );
add_action('woocommerce_cart_calculate_fees', array($this,'woo_cart_fee_update'));
$woocommerce->session = new WC_Session_Handler();
$woocommerce->session->init();
$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
$woocommerce->cart = new WC_Cart();
$items = $woocommerce->cart->get_cart();
if(empty($items)){
$response['status'] = 0;
$response['message'] = __("Cart is empty", self::domainText);
$response['data'] = new stdClass();
return new WP_REST_Response($response, 200);
}
foreach($items as $item => $values) {
$_product = wc_get_product( $values['product_id']);
$cart[] = array('key'=>$item,
'product_id'=>$values['product_id'],
'title'=>$_product->get_title(),
'quantity'=>$values['quantity'],
'price'=>$_product->get_price(),
'subtotal'=> strval(($_product->get_price()+$addons_price) * $values['quantity']),
'currency_symbol'=>get_woocommerce_currency_symbol(),
);
}
WC()->cart->calculate_totals();
$shipping = $woocommerce->cart->fee_total;
$cart_summary = array('sub_total'=>$woocommerce->cart->subtotal,
'shipping_amount'=>$shipping,
'order_type'=>$order_type,
'is_deliverable'=>$is_deliverable,
'discount_amount'=>$woocommerce->cart->get_cart_discount_total(),
'tax_amount'=>$woocommerce->cart->tax_total,
'total_amount'=>$woocommerce->cart->total,
'currency_symbol'=>get_woocommerce_currency_symbol(),
);
$output['cart_summary'] = $cart_summary;
$output['items'] = $cart;
$response['status'] = 1;
$response['message'] = __("Cart Items found", self::domainText);
$response['data'] = $output;
return new WP_REST_Response($response, 200);
}
public function newOrder($request){
global $wpdb,$woocommerce;
$woocommerce->frontend_includes();
$orderRequest = $request['order'];
$user_id = $orderRequest['user_id'];
wp_set_current_user( $user_id );
$woocommerce->session = new WC_Session_Handler();
$woocommerce->session->init();
$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
$woocommerce->cart = new WC_Cart();
if ($woocommerce->cart->get_cart_contents_count() == 0) {
$response['status'] = 0;
$response['message'] = __('Cart is empty', self::domainText);
$response['data'] = new stdClass();
return new WP_REST_Response($response, 200);
}
$cart = $woocommerce->cart->get_cart();
$order = wc_create_order(array('customer_id' => get_current_user_id()));
$order_id = $order->id;
foreach($cart as $item => $values) {
$product = wc_get_product($values['product_id']);
$quantity = (int)$values['quantity'];
if(wc_prices_include_tax()){
$product_price = wc_get_price_including_tax($product);
}else{
$product_price = wc_get_price_excluding_tax($product);
}
$variationsArray = array();
$order->add_product($product, $quantity, $variationsArray);
}
$order->set_address( $orderRequest['billing_address'], 'billing' );
$order->set_address( $orderRequest['shipping_address'], 'shipping' );
$order->set_payment_method($orderRequest['payment_method']['id']);
$get_fees = $woocommerce->cart->get_fees();
foreach($get_fees as $fee_data){
$item_fee = new WC_Order_Item_Fee();
$item_fee->set_name($fee_data->name);
$item_fee->set_amount($fee_data->amount);
$item_fee->set_tax_class( '' );
$item_fee->set_tax_status( 'none' );
$item_fee->set_total($fee_data->total);
$item_fee->save();
$order->add_item($item_fee);
}
if(!empty($coupon)){
$order->apply_coupon($coupon[0]);
}
$order->update_status('created');
$order->calculate_totals();
$woocommerce->cart->empty_cart();
$customer_id = $order->get_user_id();
$response['status'] = 1;
$response['message'] = __("Order $order_id is successfully placed", self::domainText);
$response['order_id'] = $order_id;
return new WP_REST_Response($response, 200);
}
In RetriveCart() all datas are there when I try place order. Its give me an empty cart and fees not added.

Update controller method not rendering json data in Laravel

I have a simple form with some text inputs and uploading photos with that form. Store method working very well but I'm doing something wrong in update method.
This is my store method which works fine:
public function store(Request $request)
{
dd($request);
$post = new Post;
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = "asdasd";
$post->ip = request()->ip();
if($request->hasfile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
$post->slug = $post->id."-".$this->make_slug($request->title);
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('archive');
}
And this is my update method which saves everything but photos:
public function update(Request $request, $id)
{
if(Auth::user()->role == 3 || Auth::user()->id == Post::find($id)->user_id){
$post = Post::find($id);
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = $id."-".$this->make_slug($request->title);
$post->ip = request()->ip();
if($request->hasFile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."-edit-".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('new');
}
else
Session::flash('error', 'Shame on you :( ');
return redirect()->route('new');
}
When I'm updating any post, everything updating but photos and I don't have any idea what's wrong.
I don't know if it differs but I'm using Laravel 5,8

Laravel - paypal keep maximum 30 second exceed

Paypal in laravel keep returning maximum 30 seconds timeout, sometime it can proceed smoothly but when cart product increase, it will keep return this error, and sometime the error is when create payment, sometime is execute payment, extremely not stable, how can i solve this? i have tried extend the timeout setting to 300, but it still return me a timeout error.
here is my create payment code:
$item_array = [];
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$order = Order::findOrFail($id);
// change order product status
foreach ($order->orderProduct as $order_product_key => $order_product) {
// get variant
$variant_title_array = array();
if (count($order_product->variantValue) > 0) {
foreach ($order_product->variantValue->variantOption as $variant_option) {
array_push($variant_title_array, $variant_option->name);
}
}
$variant= "";
if (count($variant_title_array) > 0) {
$variant = " ( ".implode(', ', $variant_title_array)." )";
}
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$item = new Item();
$item->setName($order_product->product->title . $variant)
->setCurrency($currency)
->setQuantity($order_product->quantity)
->setSku(get_product_sku_in_cart ($order_product)) // Similar to `item_number` in Classic API
->setPrice((float) str_replace('RM ','', $product_price));
$item_array[$order_product_key] = $item;
$subtotal += (float) str_replace('RM ','', $product_price) * $order_product->quantity;
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
$itemList = new ItemList();
$itemList->setItems($item_array);
$shipping_address = new ShippingAddress();
$shipping_address->setCity('City')
->setCountryCode('AR')
->setPostalCode('200')
->setLine1('Adress Line1')
->setState('State')
->setRecipientName('Recipient Name');
$details = new Details();
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$total = $subtotal + $shipping + $tax_amount;
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$baseUrl = url('/');
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}
$approvalUrl = $payment->getApprovalLink();
$response = array(
'paymentID' => $payment->id
);
return json_encode($response);
here is my execute payment code:
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$paymentId = $request->paymentID;
$payment = Payment::get($paymentId, $apiContext);
$transaction = new Transaction();
$amount = new Amount();
$details = new Details();
$order = Order::findOrFail($id);
// store order address
$order_address = OrderAddress::firstOrCreate(
[
'order_id' => $order->id
],
[
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'city' => $request->shipping_city ,
'order_id' => $order->id
]
);
// update address if exist
$order_address->update([
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'order_id' => $order->id
]);
// change order product status
foreach ($order->orderProduct as $order_product) {
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$product_price = (float) str_replace("RM ","",$product_price);
// add promotion to order product if promotion exist
if ($compare_price != "") {
$order_product->order_promotion_id = $order->orderPromotion->promotion_id;
}
$order_product->price = $product_price;
$order_product->status = 2;
$subtotal += $product_price * $order_product->quantity;
$order_product->save();
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
// change cart detail
$current_date_time = Carbon::now();
$order->update([
'subtotal' => $subtotal,
'status' => 2,
'submited_on' => $current_date_time,
'payment_method' => "paypal"
]);
// update shipping fees
if ($shipping > 0) {
$order->shipping_fees = $shipping;
}
// update tax
if ($tax > 0) {
$order->tax = ($subtotal * $tax) / 100;
}
$order->save();
// paypal settings
$total = $subtotal + $shipping + $tax_amount;
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$amount->setCurrency($currency);
$amount->setTotal($total);
$amount->setDetails($details);
$transaction->setAmount($amount);
// Add the above transaction object inside our Execution object.
$execution->addTransaction($transaction);
try {
$result = $payment->execute($execution, $apiContext);
try {
$payment = Payment::get($paymentId, $apiContext);
} catch (Exception $ex) {
exit(1);
}
} catch (Exception $ex) {
exit(1);
}
echo "success";

Entity Framework not saving to the database

I have a challenge that I am trying to update a record from database But it is not saving to the database, and not showing any errors, it is giving a message that it has updated the record but there are no changes to the database. My code is as below. Any suggestions
dbEntities context = new dbEntities();
var query = context.ConsultantsProfiles.SingleOrDefault(c => c.Username == username);
if (query != null)
{
query.Summary = txtSummary.Text;
query.CareerTitle = txtTitle.Text;
query.ConsultantType = cbType.Text;
query.Username = username;
query.FirstName = txtFirstname.Text;
query.LastName = txtLastName.Text;
query.Email = txtEmail.Text;
query.DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
query.PhoneNumber = txtPhoneNumber.Text;
query.Website = txtWebsite.Text;
query.Town = txtTown.Text;
query.Country = txtCountry.Text;
if (FileUpload1.HasFile)
{
//image upload
HttpPostedFile postedFile = FileUpload1.PostedFile;
// HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
Stream stream = postedFile.InputStream;
BinaryReader reader = new BinaryReader(stream);
byte[] imgByte = reader.ReadBytes((int)stream.Length);
int imglength = FileUpload1.PostedFile.ContentLength;
query.ProfilePhoto = imgByte;
}
context.ConsultantsProfiles.Attach(query);
context.Entry(query).State = EntityState.Modified;
context.SaveChanges();
}
Response.Write("<script language=javascript>alert('Notification: The Profile Has been Updated');</script>");
}
dbEntities context = new dbEntities();
var consultantProfile = new ConsultantProfile
{
Summary = txtSummary.Text;
CareerTitle = txtTitle.Text;
ConsultantType = cbType.Text;
Username = username;
FirstName = txtFirstname.Text;
LastName = txtLastName.Text;
Email = txtEmail.Text;
DateofBirth = Convert.ToDateTime(dptDateofBirth.Value);
PhoneNumber = txtPhoneNumber.Text;
Website = txtWebsite.Text;
Town = txtTown.Text;
Country = txtCountry.Text;
}
if (FileUpload1.HasFile)
{
//image upload
HttpPostedFile postedFile = FileUpload1.PostedFile;
// HttpPostedFile postedFile = uploadControl.UploadedFiles[i];
Stream stream = postedFile.InputStream;
BinaryReader reader = new BinaryReader(stream);
byte[] imgByte = reader.ReadBytes((int)stream.Length);
int imglength = FileUpload1.PostedFile.ContentLength;
consultantProfile.ProfilePhoto = imgByte;
}
context.Entry(ConsultantsProfiles).State = EntityState.Modified;
context.SaveChanges();

EnvelopeID Changed after correction?

I have 2 signature document and the first signer already signed. The document is still in process. So I went to correct the second signer. I realised the envelopeID changed after the correction.
What will it happen to the old envelope? Voided?
function getDocuments($pdfbytes) {
$documents = array();
$id = 1;
$d = new Document();
$d->PDFBytes = $pdfbytes;
$d->Name = "Demo Document";
$d->ID = $id++;;
$d->FileExtension = "pdf";
array_push($documents, $d);
return $documents;
}
function buildEnvelope($pdfbytes) {
$envelope = new Envelope();
$envelope->Subject = $_SESSION["Taskmaster"];
$envelope->EmailBlurb = "Please Sign by logining ";
$envelope->AccountId = $_SESSION["AccountID"];
$envelope->Recipients = constructRecipients();
$envelope->Tabs = addTabs(count($envelope->Recipients));
$envelope = processOptions($envelope);
$envelope->Documents = getDocuments($pdfbytes);
return $envelope;
}
function constructRecipients() {
$recipients = array();
$r = new Recipient();
$r->UserName =$_SESSION["Secretaryname"];
$r->Email = $_SESSION["Secretaryemail"];
$r->RequireIDLookup = false;
$r->ID = 1;
$r->Type = RecipientTypeCode::Signer;
$r->RoutingOrder = "2";
// if(!isset($_POST['RecipientInviteToggle'][$i])){
$r->CaptiveInfo = new RecipientCaptiveInfo();
$r->CaptiveInfo->ClientUserId = 2;
$r->CaptiveInfo->embeddedRecipientStartURL=SIGN_AT_DOCUSIGN;
// }
array_push($recipients, $r);
if(empty($recipients)){
$_SESSION["errorMessage"] = "You must include at least 1 Recipient";
//header("Location: error.php");
exit;
}
return $recipients;
}
function sendNow($envelope) {
$api = getAPI();
$csParams = new CreateAndSendEnvelope();
$csParams->Envelope = $envelope;
//print_r($csParams);
try {
$status = $api->CreateAndSendEnvelope($csParams)->CreateAndSendEnvelopeResult;
//echo "Result for Create and Send <br>";
//print_r($status);
if ($status->Status == EnvelopeStatusCode::Sent) {
addEnvelopeID($status->EnvelopeID);
$correct = new Correction;
$correct->EnvelopeID = $status->EnvelopeID;
$correct->RecipientCorrections = addRecipientCorrection();
$correctparams = new CorrectAndResendEnvelope();
$correctparams->Correction = $correct;
//print_r($correctparams);
//Send
$response = $api->CorrectAndResendEnvelope($correctparams);
//print_r($response);
//exit;
$_SESSION["EnvelopeID"]=null;
$_SESSION["Direct"]="Yes";
header("Location: getstatusanddocs.php?envelopid=" . $status->EnvelopeID .
"&accountID=" . $envelope->AccountId . "&source=Document");
}
} catch (SoapFault $e) {
$_SESSION["errorMessage"] = $e;
header("Location: error.php");
}
}
function addRecipientCorrection(){
$correction = new RecipientCorrection();
$correction->PreviousUserName = "xxxxxx";
$correction->PreviousEmail = "xxxxxxx";
$correction->PreviousSignerName = $correction->PreviousUserName;
$correction->PreviousRoutingOrder = "2";
$correction->CorrectedUserName = $_SESSION["Secretaryname"];
$correction->CorrectedEmail = $_SESSION["Secretaryemail"];
$correction->CorrectedSignerName = $correction->CorrectedUserName;
return $correction;
}
//========================================================================
// Main
//========================================================================
loginCheck();
if($_SESSION["Taskmaster"]=="xxxxx"){
$api = getAPI();
$RequestPDFParam = new RequestPDF();
$RequestPDFParam->EnvelopeID = $_SESSION["EnvelopeID"];
$result = $api->RequestPDF($RequestPDFParam);
$envPDF = $result->RequestPDFResult;
//file_put_contents("./Cert/".$_SESSION["EnvelopeID"].".pdf", $envPDF->PDFBytes);
//echo "Stop here";
//exit;
$envelope = buildEnvelope($envPDF->PDFBytes);
sendNow($envelope);
}else{
echo "You have no power";
}
EnvelopeId does not change after correction. The envelopeID never changes. New envelopes can be created, but the original GUID that was used will keep living in the system.