| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <?php
- namespace App;
- use App\Constraint\Constraint;
- use App\Constraint\HasTextConstraint;
- use App\Constraint\StartsWithConstraint;
- use Exception;
- use RuntimeException;
- /**
- * @var string $action
- */
- $request = Request::fromRequest();
- header("Content-Type: application/json");
- try {
- switch($action) {
- case "suggest-sku":
- $supplier_id = $request->int("supplier_id");
- $product_type = $request->int("product_type");
- $supplier = Supplier::require($supplier_id);
- $product_prefix = Product::getSkuPrefix($product_type);
- if(!$supplier->sku_prefix) {
- JSON::fail("The supplier has no SKU prefix set.");
- }
- $products = Product::query([
- "sku" => (new StartsWithConstraint($supplier->sku_prefix . $product_prefix))
- ]);
- $sku_flags = [];
- foreach($products as $product) {
- if($product->sku) {
- $sku_flags[$product->sku] = true;
- }
- }
- $found_sku = null;
- foreach(range(1, 999) as $number) {
- $sku = $supplier->sku_prefix . $product_prefix . str_pad($number, 3, "0", STR_PAD_LEFT);
- if(isset($sku_flags[$sku])) {
- continue;
- }
- $found_sku = $sku;
- break;
- }
- if($found_sku) {
- JSON::success(["sku" => $found_sku]);
- }
- else {
- JSON::fail("An available SKU could not be found.");
- }
- break;
- case "get-markers":
- $customer_id = $request->int("customer_id");
- $customer = Customer::require($customer_id);
- $markers = [];
- $nvp = [];
- $location_id = $request->int("location_id");
- if($location_id) {
- $nvp["id"] = $location_id;
- }
- $name = $request->string("name");
- if($name) {
- $nvp["name"] = new HasTextConstraint($name);
- }
- $locations = $customer->getLocations($nvp);
- Address::load(array_column($locations, "address_id"));
- foreach($locations as $location) {
- $address = $location->getAddress();
- $customer = $location->getCustomer();
- if($address->hasGeolocation()) {
- $markers[] = [
- "id" => (int) $location->id,
- "customer" => [
- "id" => (int) $customer->id,
- "name" => $customer->name,
- "url" => $customer->getUrl()
- ],
- "name" => $location->name,
- "addressLinesHtml" => $address->getLinesHtml(),
- "latLng" => [
- "lat" => (float) $address->latitude,
- "lng" => (float) $address->longitude,
- ],
- "url" => $location->getUrl(),
- ];
- }
- }
- echo json_encode([
- "success" => true,
- "markers" => $markers
- ]);
- break;
- default:
- throw new RuntimeException(__("Invalid action."));
- }
- }
- catch(Exception $e) {
- Json::fail($e->getMessage());
- }
|