diff --git a/lib/constants/constants.dart b/lib/constants/constants.dart index 0b1097e..19e2af5 100644 --- a/lib/constants/constants.dart +++ b/lib/constants/constants.dart @@ -38,4 +38,5 @@ const URL_JWT_TOKEN = '$URL_JWT_BASE/token'; const DEFAULT_WC_API_PATH = "/wp-json/wc/v3/"; const URL_WP_BASE = '/wp-json/wp/v2'; const URL_USER_ME = '$URL_WP_BASE/users/me'; -const URL_REGISTER_ENDPOINT = '$URL_WP_BASE/users/register'; \ No newline at end of file +const URL_REGISTER_ENDPOINT = '$URL_WP_BASE/users/register'; +const URL_COCART = '/wp-json/cocart/v2/'; \ No newline at end of file diff --git a/lib/models/cart.dart b/lib/models/cart.dart index b39f98a..26394f8 100644 --- a/lib/models/cart.dart +++ b/lib/models/cart.dart @@ -31,150 +31,138 @@ */ +import 'package:woocommerce/models/customer.dart'; + +import 'cart_item.dart'; +import 'shipping_rates.dart'; + class WooCart { - String? currency; - int? itemCount; - List? items; + WooCart({ + this.coupons, + this.shippingRates, + this.shippingAddress, + this.billingAddress, + this.items, + this.itemsCount, + this.itemsWeight, + this.needsPayment, + this.needsShipping, + this.totals, + this.errors, + }); + + List? coupons; + List? shippingRates; + Shipping? shippingAddress; + Billing? billingAddress; + List? items; + int? itemsCount; + int? itemsWeight; + bool? needsPayment; bool? needsShipping; - String? totalPrice; - int? totalWeight; - - WooCart( - {this.currency, - this.itemCount, - this.items, - this.needsShipping, - this.totalPrice, - this.totalWeight}); - - WooCart.fromJson(Map json) { - currency = json['currency']; - itemCount = json['item_count']; - if (json['items'] != null) { - items = []; - json['items'].forEach((v) { - items!.add(new WooCartItems.fromJson(v)); - }); - } - needsShipping = json['needs_shipping']; - totalPrice = json['total_price'].toString(); - totalWeight = json['total_weight']; - } - - Map toJson() { - final Map data = new Map(); - data['currency'] = this.currency; - data['item_count'] = this.itemCount; - if (this.items != null) { - data['items'] = this.items!.map((v) => v.toJson()).toList(); - } - data['needs_shipping'] = this.needsShipping; - data['total_price'] = this.totalPrice; - data['total_weight'] = this.totalWeight; - return data; - } + WooCartTotals? totals; + List? errors; + + factory WooCart.fromJson(Map json) => WooCart( + coupons: List.from(json["coupons"].map((x) => WooCartCoupon.fromJson(x))), + shippingRates: List.from(json["shipping_rates"].map((x) => ShippingRates.fromJson(x))), + shippingAddress: Shipping.fromJson(json["shipping_address"]), + billingAddress: Billing.fromJson(json["billing_address"]), + items: List.from(json["items"].map((x) => WooCartItem.fromJson(x))), + itemsCount: json["items_count"], + itemsWeight: json["items_weight"], + needsPayment: json["needs_payment"], + needsShipping: json["needs_shipping"], + totals: WooCartTotals.fromJson(json["totals"]), + errors: List.from(json["errors"].map((x) => x)), + ); + + Map toJson() => { + "coupons": coupons!.map((x) => x.toJson()).toList(), + "shipping_rates": shippingRates!.map((x) => x.toJson()).toList(), + "shipping_address": shippingAddress!.toJson(), + "billing_address": billingAddress!.toJson(), + "items": items!.map((x) => x.toJson()).toList(), + "items_count": itemsCount, + "items_weight": itemsWeight, + "needs_payment": needsPayment, + "needs_shipping": needsShipping, + "totals": totals!.toJson(), + "errors": List.from(errors!.map((x) => x)), + }; @override toString() => this.toJson().toString(); } -class WooCartItems { - String? key; - int? id; - int? quantity; - String? name; - String? sku; - String? permalink; - List? images; - String? price; - String? linePrice; - List? variation; - - WooCartItems( - {this.key, - this.id, - this.quantity, - this.name, - this.sku, - this.permalink, - this.images, - this.price, - this.linePrice, - this.variation}); - - WooCartItems.fromJson(Map json) { - key = json['key']; - id = json['id']; - quantity = json['quantity']; - name = json['name']; - sku = json['sku']; - permalink = json['permalink']; - if (json['images'] != null) { - images = []; - json['images'].forEach((v) { - images!.add(new WooCartImages.fromJson(v)); - }); - } - price = json['price']; - linePrice = json['line_price']; - variation = json['variation'].cast(); - } - - Map toJson() { - final Map data = new Map(); - data['key'] = this.key; - data['id'] = this.id; - data['quantity'] = this.quantity; - data['name'] = this.name; - data['sku'] = this.sku; - data['permalink'] = this.permalink; - if (this.images != null) { - data['images'] = this.images!.map((v) => v.toJson()).toList(); - } - data['price'] = this.price; - data['line_price'] = this.linePrice; - data['variation'] = this.variation; - return data; - } +class WooCartCoupon { + String? code; + String? discountType; + WooCartCouponTotals? totals; + + WooCartCoupon({ + this.code, + this.discountType, + this.totals, + }); + + factory WooCartCoupon.fromJson(Map json) => WooCartCoupon( + code: json['code'], + discountType: json['discount_type'], + totals: WooCartCouponTotals.fromJson(json['totals']), + ); + + Map toJson() => { + 'code': code, + 'discount_type': discountType, + 'totals': totals!.toJson(), + }; } -class WooCartImages { - String? id; - String? src; - String? thumbnail; - String? srcset; - String? sizes; - String? name; - String? alt; - - WooCartImages( - {this.id, - this.src, - this.thumbnail, - this.srcset, - this.sizes, - this.name, - this.alt}); - - WooCartImages.fromJson(Map json) { - id = json['id'].toString(); - src = json['src']; - thumbnail = json['thumbnail']; - srcset = json['srcset'].toString(); - sizes = json['sizes']; - name = json['name']; - alt = json['alt']; - } - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['src'] = this.src; - data['thumbnail'] = this.thumbnail; - data['srcset'] = this.srcset; - data['sizes'] = this.sizes; - data['name'] = this.name; - data['alt'] = this.alt; - return data; - } +class WooCartCouponTotals { + String? totalDiscount; + String? totalDiscountTax; + String? currencyCode; + String? currencySymbol; + int? currencyMinorUnit; + String? currencyDecimalSeparator; + String? currencyThousandSeparator; + String? currencyPrefix; + String? currencySuffix; + + WooCartCouponTotals({ + this.totalDiscount, + this.totalDiscountTax, + this.currencyCode, + this.currencySymbol, + this.currencyMinorUnit, + this.currencyDecimalSeparator, + this.currencyThousandSeparator, + this.currencyPrefix, + this.currencySuffix, + }); + + factory WooCartCouponTotals.fromJson(Map json) => WooCartCouponTotals( + totalDiscount: json['total_discount'], + totalDiscountTax: json['total_discount_tax'], + currencyCode: json['currency_code'], + currencySymbol: json['currency_symbol'], + currencyMinorUnit: json['currency_minor_unit'], + currencyDecimalSeparator: json['currency_decimal_separator'], + currencyThousandSeparator: json['currency_thousand_separator'], + currencyPrefix: json['currency_prefix'], + currencySuffix: json['currency_suffix'], + ); + + Map toJson() => { + 'total_discount': totalDiscount, + 'total_discount_tax': totalDiscountTax, + 'currency_code': currencyCode, + 'currency_symbol': currencySymbol, + 'currency_minor_unit': currencyMinorUnit, + 'currency_decimal_separator': currencyDecimalSeparator, + 'currency_thousand_separator': currencyThousandSeparator, + 'currency_prefix': currencyPrefix, + 'currency_suffix': currencySuffix, + }; } diff --git a/lib/models/cart_item.dart b/lib/models/cart_item.dart index 714cdcd..05d86ef 100644 --- a/lib/models/cart_item.dart +++ b/lib/models/cart_item.dart @@ -32,110 +32,359 @@ */ class WooCartItem { + WooCartItem({ + this.key, + this.id, + this.quantity, + this.quantityLimit, + this.name, + this.shortDescription, + this.description, + this.sku, + this.lowStockRemaining, + this.backOrdersAllowed, + this.showBackOrderBadge, + this.soldIndividually, + this.permalink, + this.images, + this.variation, + this.prices, + this.totals, + }); + String? key; int? id; int? quantity; + int? quantityLimit; String? name; + String? shortDescription; + String? description; String? sku; + dynamic? lowStockRemaining; + bool? backOrdersAllowed; + bool? showBackOrderBadge; + bool? soldIndividually; String? permalink; - List? images; - String? price; - String? linePrice; - List? variation; - - WooCartItem( - {this.key, - this.id, - this.quantity, - this.name, - this.sku, - this.permalink, - this.images, - this.price, - this.linePrice, - this.variation}); - - WooCartItem.fromJson(Map json) { - key = json['key']; - id = json['id']; - quantity = json['quantity']; - name = json['name']; - sku = json['sku']; - permalink = json['permalink']; - if (json['images'] != null) { - images = []; - json['images'].forEach((v) { - images!.add(new WooCartItemImages.fromJson(v)); - }); - } - price = json['price']; - linePrice = json['line_price']; - variation = json['variation'].cast(); - } + List? images; + List? variation; + WooCartPrices? prices; + WooCartItemTotals? totals; - Map toJson() { - final Map data = new Map(); - data['key'] = this.key; - data['id'] = this.id; - data['quantity'] = this.quantity; - data['name'] = this.name; - data['sku'] = this.sku; - data['permalink'] = this.permalink; - if (this.images != null) { - data['images'] = this.images!.map((v) => v.toJson()).toList(); + factory WooCartItem.fromJson(Map json) { + List images = []; + if (json["images"] is List) { + images = json["images"]; + } else { + for (int i = 1; i <= json["images"].length; i++) { + images.add(json["images"]["$i"]); + } } - data['price'] = this.price; - data['line_price'] = this.linePrice; - data['variation'] = this.variation; - return data; + return WooCartItem( + key: json["key"], + id: json["id"], + quantity: json["quantity"], + quantityLimit: json["quantity_limit"], + name: json["name"], + shortDescription: json["short_description"], + description: json["description"], + sku: json["sku"], + lowStockRemaining: json["low_stock_remaining"], + backOrdersAllowed: json["backorders_allowed"], + showBackOrderBadge: json["show_backorder_badge"], + soldIndividually: json["sold_individually"], + permalink: json["permalink"], + images: List.from(images.map((x) => WooCartImages.fromJson(x))), + variation: List.from(json["variation"].map((x) => x)), + prices: WooCartPrices.fromJson(json["prices"]), + totals: WooCartItemTotals.fromJson(json["totals"]), + ); } - @override - toString() => this.toJson().toString(); + Map toJson() => { + "key": key, + "id": id, + "quantity": quantity, + "quantity_limit": quantityLimit, + "name": name, + "short_description": shortDescription, + "description": description, + "sku": sku, + "low_stock_remaining": lowStockRemaining, + "backorders_allowed": backOrdersAllowed, + "show_backorder_badge": showBackOrderBadge, + "sold_individually": soldIndividually, + "permalink": permalink, + "images": images!.map((x) => x.toJson()).toList(), + "variation": variation!.map((x) => x).toList(), + "prices": prices!.toJson(), + "totals": totals!.toJson(), + }; } -class WooCartItemImages { - String? id; +class WooCartItemTotals { + WooCartItemTotals({ + this.currencyCode, + this.currencySymbol, + this.currencyMinorUnit, + this.currencyDecimalSeparator, + this.currencyThousandSeparator, + this.currencyPrefix, + this.currencySuffix, + this.lineSubtotal, + this.lineSubtotalTax, + this.lineTotal, + this.lineTotalTax, + }); + + String? currencyCode; + String? currencySymbol; + int? currencyMinorUnit; + String? currencyDecimalSeparator; + String? currencyThousandSeparator; + String? currencyPrefix; + String? currencySuffix; + String? lineSubtotal; + String? lineSubtotalTax; + String? lineTotal; + String? lineTotalTax; + + factory WooCartItemTotals.fromJson(Map json) => WooCartItemTotals( + currencyCode: json["currency_code"], + currencySymbol: json["currency_symbol"], + currencyMinorUnit: json["currency_minor_unit"], + currencyDecimalSeparator: json["currency_decimal_separator"], + currencyThousandSeparator: json["currency_thousand_separator"], + currencyPrefix: json["currency_prefix"], + currencySuffix: json["currency_suffix"], + lineSubtotal: json["line_subtotal"], + lineSubtotalTax: json["line_subtotal_tax"], + lineTotal: json["line_total"], + lineTotalTax: json["line_total_tax"], + ); + + Map toJson() => { + "currency_code": currencyCode, + "currency_symbol": currencySymbol, + "currency_minor_unit": currencyMinorUnit, + "currency_decimal_separator": currencyDecimalSeparator, + "currency_thousand_separator": currencyThousandSeparator, + "currency_prefix": currencyPrefix, + "currency_suffix": currencySuffix, + "line_subtotal": lineSubtotal, + "line_subtotal_tax": lineSubtotalTax, + "line_total": lineTotal, + "line_total_tax": lineTotalTax, + }; +} + +class WooCartImages { + WooCartImages({ + this.id, + this.src, + this.thumbnail, + this.srcset, + this.sizes, + this.name, + this.alt, + }); + + int? id; String? src; String? thumbnail; - bool? srcset; + String? srcset; String? sizes; String? name; String? alt; - WooCartItemImages( - {this.id, - this.src, - this.thumbnail, - this.srcset, - this.sizes, - this.name, - this.alt}); - - WooCartItemImages.fromJson(Map json) { - id = json['id'].toString(); - src = json['src']; - thumbnail = json['thumbnail']; - - if (json['srcset'] is String) { - srcset = bool.fromEnvironment(json['srcset']); - } else { - srcset = json['srcset']; - } - sizes = json['sizes']; - name = json['name']; - alt = json['alt']; - } + factory WooCartImages.fromJson(Map json) => WooCartImages( + id: json["id"], + src: json["src"], + thumbnail: json["thumbnail"], + srcset: json["srcset"], + sizes: json["sizes"], + name: json["name"], + alt: json["alt"], + ); - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['src'] = this.src; - data['thumbnail'] = this.thumbnail; - data['srcset'] = this.srcset; - data['sizes'] = this.sizes; - data['name'] = this.name; - data['alt'] = this.alt; - return data; - } + Map toJson() => { + "id": id, + "src": src, + "thumbnail": thumbnail, + "srcset": srcset, + "sizes": sizes, + "name": name, + "alt": alt, + }; +} + +class WooCartPrices { + WooCartPrices({ + this.currencyCode, + this.currencySymbol, + this.currencyMinorUnit, + this.currencyDecimalSeparator, + this.currencyThousandSeparator, + this.currencyPrefix, + this.currencySuffix, + this.price, + this.regularPrice, + this.salePrice, + this.priceRange, + this.rawPrices, + }); + + String? currencyCode; + String? currencySymbol; + int? currencyMinorUnit; + String? currencyDecimalSeparator; + String? currencyThousandSeparator; + String? currencyPrefix; + String? currencySuffix; + String? price; + String? regularPrice; + String? salePrice; + dynamic priceRange; + WooCartRawPrices? rawPrices; + + factory WooCartPrices.fromJson(Map json) => WooCartPrices( + currencyCode: json["currency_code"], + currencySymbol: json["currency_symbol"], + currencyMinorUnit: json["currency_minor_unit"], + currencyDecimalSeparator: json["currency_decimal_separator"], + currencyThousandSeparator: json["currency_thousand_separator"], + currencyPrefix: json["currency_prefix"], + currencySuffix: json["currency_suffix"], + price: json["price"], + regularPrice: json["regular_price"], + salePrice: json["sale_price"], + priceRange: json["price_range"], + rawPrices: WooCartRawPrices.fromJson(json["raw_prices"]), + ); + + Map toJson() => { + "currency_code": currencyCode, + "currency_symbol": currencySymbol, + "currency_minor_unit": currencyMinorUnit, + "currency_decimal_separator": currencyDecimalSeparator, + "currency_thousand_separator": currencyThousandSeparator, + "currency_prefix": currencyPrefix, + "currency_suffix": currencySuffix, + "price": price, + "regular_price": regularPrice, + "sale_price": salePrice, + "price_range": priceRange, + "raw_prices": rawPrices!.toJson(), + }; +} + +class WooCartRawPrices { + WooCartRawPrices({ + this.precision, + this.price, + this.regularPrice, + this.salePrice, + }); + + int? precision; + String? price; + String? regularPrice; + String? salePrice; + + factory WooCartRawPrices.fromJson(Map json) => WooCartRawPrices( + precision: json["precision"], + price: json["price"], + regularPrice: json["regular_price"], + salePrice: json["sale_price"], + ); + + Map toJson() => { + "precision": precision, + "price": price, + "regular_price": regularPrice, + "sale_price": salePrice, + }; +} + +class WooCartTotals { + WooCartTotals({ + this.currencyCode, + this.currencySymbol, + this.currencyMinorUnit, + this.currencyDecimalSeparator, + this.currencyThousandSeparator, + this.currencyPrefix, + this.currencySuffix, + this.totalItems, + this.totalItemsTax, + this.totalFees, + this.totalFeesTax, + this.totalDiscount, + this.totalDiscountTax, + this.totalShipping, + this.totalShippingTax, + this.totalPrice, + this.totalTax, + this.taxLines, + }); + + String? currencyCode; + String? currencySymbol; + int? currencyMinorUnit; + String? currencyDecimalSeparator; + String? currencyThousandSeparator; + String? currencyPrefix; + String? currencySuffix; + String? totalItems; + String? totalItemsTax; + String? totalFees; + String? totalFeesTax; + String? totalDiscount; + String? totalDiscountTax; + String? totalShipping; + String? totalShippingTax; + String? totalPrice; + String? totalTax; + List? taxLines; + + factory WooCartTotals.fromJson(Map json) => WooCartTotals( + currencyCode: json["currency_code"], + currencySymbol: json["currency_symbol"], + currencyMinorUnit: json["currency_minor_unit"], + currencyDecimalSeparator: json["currency_decimal_separator"], + currencyThousandSeparator: json["currency_thousand_separator"], + currencyPrefix: json["currency_prefix"], + currencySuffix: json["currency_suffix"], + totalItems: json["total_items"], + totalItemsTax: json["total_items_tax"], + totalFees: json["total_fees"], + totalFeesTax: json["total_fees_tax"], + totalDiscount: json["total_discount"], + totalDiscountTax: json["total_discount_tax"], + totalShipping: json["total_shipping"], + totalShippingTax: json["total_shipping_tax"], + totalPrice: json["total_price"], + totalTax: json["total_tax"], + taxLines: List.from(json["tax_lines"].map((x) => x)), + ); + + Map toJson() => { + "currency_code": currencyCode, + "currency_symbol": currencySymbol, + "currency_minor_unit": currencyMinorUnit, + "currency_decimal_separator": currencyDecimalSeparator, + "currency_thousand_separator": currencyThousandSeparator, + "currency_prefix": currencyPrefix, + "currency_suffix": currencySuffix, + "total_items": totalItems, + "total_items_tax": totalItemsTax, + "total_fees": totalFees, + "total_fees_tax": totalFeesTax, + "total_discount": totalDiscount, + "total_discount_tax": totalDiscountTax, + "total_shipping": totalShipping, + "total_shipping_tax": totalShippingTax, + "total_price": totalPrice, + "total_tax": totalTax, + "tax_lines": taxLines!.map((x) => x).toList(), + }; } diff --git a/lib/models/order.dart b/lib/models/order.dart index 55f1c27..cafdb91 100755 --- a/lib/models/order.dart +++ b/lib/models/order.dart @@ -277,7 +277,7 @@ class WooOrderCouponLine { String? code; String? discount; String? discountTax; - List metaData; + List metaData; WooOrderCouponLine( this.id, this.code, this.discount, this.discountTax, this.metaData); @@ -288,7 +288,7 @@ class WooOrderCouponLine { discount = json['discount'], discountTax = json['discount_tax'], metaData = (json['meta_data'] as List) - .map((i) => MetaData.fromJson(i)) + .map((i) => CouponMetaData.fromJson(i)) .toList(); Map toJson() { @@ -511,6 +511,115 @@ class MetaData { } } +class CouponMetaData { + int? id; + String? key; + CouponMetaDataValue? value; + String? displayKey; + CouponMetaDataValue? displayValue; + + CouponMetaData.fromJson(Map json) { + id = json['id']; + key = json['key']; + value = CouponMetaDataValue.fromJson(json['value']); + displayKey = json['display_key']; + displayValue = CouponMetaDataValue.fromJson(json['display_value']); + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['key'] = this.key; + data['value'] = this.value!.toJson(); + data['display_key'] = this.displayKey; + data['display_value'] = this.displayValue!.toJson(); + return data; + } +} + +class CouponMetaDataValue { + int? id; + String? code; + String? amount; + Map? dateCreated; + Map? dateModified; + Map? dateExpires; + String? discountType; + String? description; + int? usageCount; + bool? individualUse; + List? productIds; + List? excludedProductIds; + int? usageLimit; + int? usageLimitPerUser; + int? limitUsageToXItems; + bool? freeShipping; + List? productCategories; + List? excludedProductCategories; + bool? excludeSaleItems; + String? minimumAmount; + String? maximumAmount; + List? emailRestrictions; + bool? virtual; + List? metaData; + + CouponMetaDataValue.fromJson(Map json) { + id = json['id']; + code = json['code']; + amount = json['amount']; + dateCreated = json['date_created']; + dateModified = json['data_modified']; + dateExpires = json['date_expires']; + discountType = json['discount_type']; + description = json['description']; + usageCount = json['usage_count']; + individualUse = json['individual_use']; + productIds = json['product_ids'].cast(); + excludedProductIds = json['excluded_product_ids'].cast(); + usageLimit = json['usage_limit']; + usageLimitPerUser = json['usage_limit_per_user']; + limitUsageToXItems = json['limit_usage_to_x_items']; + freeShipping = json['free_shipping']; + productCategories = json['product_categories'].cast(); + excludedProductCategories = json['excluded_product_categories'].cast(); + excludeSaleItems = json['exclude_sale_items']; + minimumAmount = json['minimum_amount']; + maximumAmount = json['maximum_amount']; + emailRestrictions = json['email_restrictions'].cast(); + virtual = json['virtual']; + metaData = (json['meta_data'] as List).map((i) => MetaData.fromJson(i)).toList(); + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['code'] = this.code; + data['amount'] = this.amount; + data['date_created'] = this.dateCreated; + data['data_modified'] = this.dateModified; + data['date_expires'] = this.dateExpires; + data['discount_type'] = this.discountType; + data['description'] = this.description; + data['usage_count'] = this.usageCount; + data['individual_use'] = this.individualUse; + data['product_ids'] = this.productIds; + data['excluded_product_ids'] = this.excludedProductIds; + data['usage_limit'] = this.usageLimit; + data['usage_limit_per_user'] = this.usageLimitPerUser; + data['limit_usage_to_x_items'] = this.limitUsageToXItems; + data['free_shipping'] = this.freeShipping; + data['product_categories'] = this.productCategories; + data['excluded_product_categories'] = this.excludedProductCategories; + data['exclude_sale_items'] = this.excludeSaleItems; + data['minimum_amount'] = this.minimumAmount; + data['maximum_amount'] = this.maximumAmount; + data['email_restrictions'] = this.emailRestrictions; + data['virtual'] = this.virtual; + data['meta_data'] = this.metaData!.map((v) => v.toJson()); + return data; + } +} + class Refunds { int? id; String? reason; diff --git a/lib/models/order_payload.dart b/lib/models/order_payload.dart index 8c798d6..98f050f 100755 --- a/lib/models/order_payload.dart +++ b/lib/models/order_payload.dart @@ -34,12 +34,14 @@ class WooOrderPayload { String? paymentMethod; String? paymentMethodTitle; + String? transactionId; bool? setPaid; String? status; String? currency; int? customerId; String? customerNote; int? parentId; + String? createdVia; List? metaData; List? feeLines; List? couponLines; @@ -51,11 +53,13 @@ class WooOrderPayload { WooOrderPayload( {this.paymentMethod, this.paymentMethodTitle, + this.transactionId, this.setPaid, this.status, this.currency, this.customerId, this.customerNote, + this.createdVia, this.parentId, this.metaData, this.feeLines, @@ -68,12 +72,14 @@ class WooOrderPayload { WooOrderPayload.fromJson(Map json) { paymentMethod = json['payment_method']; paymentMethodTitle = json['payment_method_title']; + transactionId = json['transaction_id']; setPaid = json['set_paid']; status = json['status']; currency = json['currency']; customerId = json['customer_id']; customerNote = json['customer_note']; parentId = json['parent_id']; + createdVia = json['created_via']; if (json['meta_data'] != null) { metaData = []; json['meta_data'].forEach((v) { @@ -116,12 +122,14 @@ class WooOrderPayload { final Map data = new Map(); data['payment_method'] = this.paymentMethod; data['payment_method_title'] = this.paymentMethodTitle; + data['transaction_id'] = this.transactionId; data['set_paid'] = this.setPaid; data['status'] = this.status; data['currency'] = this.currency; data['customer_id'] = this.customerId; data['customer_note'] = this.customerNote; data['parent_id'] = this.parentId; + data['created_via'] = this.createdVia; if (this.metaData != null) { data['meta_data'] = this.metaData!.map((v) => v.toJson()).toList(); } diff --git a/lib/models/product_variation.dart b/lib/models/product_variation.dart index 8db2eb9..e399fb7 100755 --- a/lib/models/product_variation.dart +++ b/lib/models/product_variation.dart @@ -119,9 +119,9 @@ class WooProductVariation { status = json['status'], description = json['description'], sku = json['sku'], - price = json['price'], - regularPrice = json['regular_price'], - salePrice = json['sale_price'], + price = json['price'].toString(), + regularPrice = json['regular_price'].toString(), + salePrice = json['sale_price'].toString(), onSale = json['on_sale'], purchasable = json['purchasable'], virtual = json['virtual'], @@ -149,7 +149,8 @@ class WooProductVariation { .toList(), metaData = (json['meta_data'] as List) .map((i) => WooProductVariationMetaData.fromJson(i)) - .toList(); + .toList(), + image = WooProductVariationImage.fromJson(json['image']); } class WooProductVariationMetaData { diff --git a/lib/models/products.dart b/lib/models/products.dart index a778449..bdaddf7 100755 --- a/lib/models/products.dart +++ b/lib/models/products.dart @@ -165,13 +165,13 @@ class WooProduct { description = json['description'], shortDescription = json['short_description'], sku = json['sku'], - price = json['price'], - regularPrice = json['regular_price'], - salePrice = json['sale_price'], + price = json['price'].toString(), + regularPrice = json['regular_price'].toString(), + salePrice = json['sale_price'].toString(), priceHtml = json['price_html'], onSale = json['on_sale'], purchasable = json['purchasable'], - totalSales = json['total_sales'], + totalSales = int.tryParse(json['total_sales'].toString()), virtual = json['virtual'], downloadable = json['downloadable'], downloads = (json['downloads'] as List) diff --git a/lib/models/shipping_rates.dart b/lib/models/shipping_rates.dart new file mode 100644 index 0000000..60e8194 --- /dev/null +++ b/lib/models/shipping_rates.dart @@ -0,0 +1,110 @@ +class ShippingRates { + int? packageId; + String? name; + dynamic destination, items; + List? shippingRates; + + ShippingRates({ + this.packageId, + this.name, + this.destination, + this.items, + this.shippingRates, + }); + + factory ShippingRates.fromJson(Map json) => ShippingRates( + packageId: json['package_id'], + name: json['name'], + destination: json['destination'], + items: json['items'], + shippingRates: List.from(json['shipping_rates']!.map((x) => ShippingMethodRates.fromJson(x))), + ); + + Map toJson() => { + 'package_id': packageId, + 'name': name, + 'destination': destination, + 'items': items, + 'shipping_rates': shippingRates!.map((x) => x.toJson()).toList(), + }; +} + +class ShippingMethodRates { + String? rateId; + String? name; + String? description; + String? deliveryTime; + String? price; + String? taxes; + int? instanceId; + String? methodId; + dynamic metaData; + bool? selected; + String? currencyCode; + String? currencySymbol; + int? currencyMinorUnit; + String? currencyDecimalSeparator; + String? currencyThousandSeparator; + String? currencyPrefix; + String? currencySuffix; + + ShippingMethodRates({ + this.rateId, + this.name, + this.description, + this.deliveryTime, + this.price, + this.taxes, + this.instanceId, + this.methodId, + this.metaData, + this.selected, + this.currencyCode, + this.currencySymbol, + this.currencyMinorUnit, + this.currencyDecimalSeparator, + this.currencyThousandSeparator, + this.currencyPrefix, + this.currencySuffix, + }); + + factory ShippingMethodRates.fromJson(Map json) => ShippingMethodRates( + rateId: json['rate_id'], + name: json['name'], + description: json['description'], + deliveryTime: json['delivery_time'], + price: json['price'].toString(), + taxes: json['taxes'], + instanceId: json['instance_id'], + methodId: json['method_id'], + metaData: json['meta_data'], + selected: json['selected'], + currencyCode: json['currency_code'], + currencySymbol: json['currency_symbol'], + currencyMinorUnit: json['currency_minor_unit'], + currencyDecimalSeparator: json['currency_decimal_separator'], + currencyThousandSeparator: json['currency_thousand_separator'], + currencyPrefix: json['currency_prefix'], + currencySuffix: json['currency_suffix'], + ); + + Map toJson() => { + 'rate_id': rateId, + 'name': name, + 'description': description, + 'delivery_time': deliveryTime, + 'price': price, + 'taxes': taxes, + 'instance_id': instanceId, + 'method_id': methodId, + 'meta_data': metaData, + 'selected': selected, + 'currency_code': currencyCode, + 'currency_symbol': currencySymbol, + 'currency_minor_unit': currencyMinorUnit, + 'currency_decimal_separator': currencyDecimalSeparator, + 'currency_thousand_separator': currencyThousandSeparator, + 'currency_prefix': currencyPrefix, + 'currency_suffix': currencySuffix, + }; +} diff --git a/lib/utilities/local_db.dart b/lib/utilities/local_db.dart index 815de0d..dea1e70 100644 --- a/lib/utilities/local_db.dart +++ b/lib/utilities/local_db.dart @@ -31,6 +31,8 @@ */ +import 'dart:math'; + import 'package:flutter_secure_storage/flutter_secure_storage.dart'; class LocalDatabaseService { @@ -53,4 +55,18 @@ class LocalDatabaseService { return token; } + Future getCartKey() async { + String? key = await securityToken.read(key: 'cartKey'); + if (key == null) { + key = _createCartKey(); + await securityToken.write(key: 'cartKey', value: key); + } + return key; + } + + String _createCartKey() { + const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'; + Random _rnd = Random(); + return String.fromCharCodes(Iterable.generate(40, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length)))); + } } \ No newline at end of file diff --git a/lib/woocommerce.dart b/lib/woocommerce.dart index 616ba68..5c6ee39 100644 --- a/lib/woocommerce.dart +++ b/lib/woocommerce.dart @@ -155,6 +155,8 @@ class WooCommerce { String? _authToken; String? get authToken => _authToken; + String _cartKey = ''; + Uri? queryUri; String get apiResourceUrl => queryUri.toString(); @@ -163,6 +165,24 @@ class WooCommerce { String get urlHeader => _urlHeader['Authorization'] = 'Bearer ' + authToken!; LocalDatabaseService _localDbService = LocalDatabaseService(); + /// Initialize the cart key. + /// + /// Executes when woocommerce instance is created. + Future getCartKey() async { + if (_cartKey == '') { + _cartKey = await _localDbService.getCartKey(); + } + return _cartKey; + } + + Future getCartKeyParam({bool getCartKeyAnyway = false}) async { + if (!await isCustomerLoggedIn() || getCartKeyAnyway) { + String key = await getCartKey(); + return '?cart_key=' + key; + } + return ''; + } + /// Authenticates the user using WordPress JWT authentication and returns the access [_token] string. /// /// Associated endpoint : yourwebsite.com/wp-json/jwt-auth/v1/token @@ -278,10 +298,11 @@ class WooCommerce { /// Creates a new Woocommerce Customer and returns the customer object. /// /// Accepts a customer object as required parameter. - Future createCustomer(WooCustomer customer) async { + createCustomer(WooCustomer customer) async { _printToLog('Creating Customer With info : ' + customer.toString()); _setApiResourceUrl(path: 'customers'); final response = await post(queryUri.toString(), customer.toJson()); + return response; _printToLog('created customer : ' + response.toString()); final cus = WooCustomer.fromJson(response); if (cus is WooCustomer) { @@ -314,7 +335,7 @@ class WooCommerce { 'order': order, 'orderby': orderBy, //'email': email, 'role': role, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List customers = []; @@ -464,7 +485,7 @@ class WooCommerce { 'max_price': maxPrice, 'stock_status': stockStatus, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); _printToLog("Parameters: " + payload.toString()); @@ -541,7 +562,7 @@ class WooCommerce { 'max_price': maxPrice, 'stock_status': stockStatus, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List productVariations = []; _setApiResourceUrl( @@ -656,7 +677,7 @@ class WooCommerce { 'product': product, 'slug': slug, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List productAttributeTerms = []; _setApiResourceUrl( @@ -697,8 +718,8 @@ class WooCommerce { {int? page, int? perPage, String? search, - //List exclude, - //List include, + List? exclude, + List? include, String? order, String? orderBy, bool? hideEmpty, @@ -709,12 +730,12 @@ class WooCommerce { ({ 'page': page, 'per_page': perPage, 'search': search, - //'exclude': exclude, 'include': include, + 'exclude': exclude, 'include': include, 'order': order, 'orderby': orderBy, 'hide_empty': hideEmpty, 'parent': parent, 'product': product, 'slug': slug, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List productCategories = []; @@ -773,7 +794,7 @@ class WooCommerce { 'product': product, 'slug': slug, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List productShippingClasses = []; _setApiResourceUrl( @@ -810,8 +831,8 @@ class WooCommerce { {int? page, int? perPage, String? search, - //List exclude, - //List include, + List? exclude, + List? include, int? offset, String? order, String? orderBy, @@ -821,12 +842,12 @@ class WooCommerce { Map payload = {}; ({ 'page': page, 'per_page': perPage, 'search': search, - // 'exclude': exclude, 'include': include, + 'exclude': exclude, 'include': include, 'offset': offset, 'order': order, 'orderby': orderBy, 'hide_empty': hideEmpty, 'product': product, 'slug': slug, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List productTags = []; _printToLog('making request with payload : ' + payload.toString()); @@ -876,7 +897,7 @@ class WooCommerce { 'rating': rating, 'verified': verified, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); WooProductReview productReview; @@ -898,14 +919,14 @@ class WooCommerce { String? search, String? after, String? before, - //List exclude, - //List include, + List? exclude, + List? include, int? offset, String? order, String? orderBy, List? reviewer, - //List reviewerExclude, - //List reviewerEmail, + List? reviewerExclude, + List? reviewerEmail, List? product, String? status}) async { Map payload = {}; @@ -913,20 +934,22 @@ class WooCommerce { ({ 'page': page, 'per_page': perPage, 'search': search, 'after': after, 'before': before, - //'exclude': exclude, 'include': include, + 'exclude': exclude, + 'include': include, 'offset': offset, - 'order': order, 'orderby': orderBy, + 'order': order, + 'orderby': orderBy, 'reviewer': reviewer, - //'reviewer_exclude': reviewerExclude, 'reviewer_email': reviewerEmail, + 'reviewer_exclude': reviewerExclude, + 'reviewer_email': reviewerEmail, 'product': product, 'status': status, }).forEach((k, v) { - if (v != null) payload[k] = v; + if (v != null) payload[k] = _paramToString(v); }); - String meQueryPath = 'products/reviews' + getQueryString(payload); List productReviews = []; - //_setApiResourceUrl(path: 'products/reviews', queryParameters: payload); - final response = await get(meQueryPath); + _setApiResourceUrl(path: 'products/reviews', queryParameters: payload); + final response = await get(queryUri.toString()); _printToLog('response gotten : ' + response.toString()); for (var r in response) { var rev = WooProductReview.fromJson(r); @@ -1002,31 +1025,41 @@ class WooCommerce { /// Related endpoint : wc/store/cart /// - Future addToMyCart( + Future addToMyCart( {required String itemId, required String quantity, - List? variations}) async { + Map? variations}) async { Map data = { 'id': itemId, 'quantity': quantity, + 'return_item': 'false', }; if (variations != null) data['variations'] = variations; await getAuthTokenFromDb(); - _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + String keyParam = ''; + if (await isCustomerLoggedIn()) { + _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + } else { + keyParam = await getCartKeyParam(); + } + print(keyParam); final response = await http.post( - Uri.parse(this.baseUrl + URL_STORE_API_PATH + 'cart/items'), + Uri.parse(this.baseUrl + URL_COCART + 'cart/add-item' + keyParam), headers: _urlHeader, body: data); - + print(response.body); + print('uper added to cart data'); if (response.statusCode >= 200 && response.statusCode < 300) { - final jsonStr = json.decode(response.body); + /* final jsonStr = json.decode(response.body); _printToLog('added to my cart : ' + jsonStr.toString()); - return WooCartItem.fromJson(jsonStr); + return WooCartItem.fromJson(jsonStr); */ + return true; } else { - WooCommerceError err = + return false; + /* WooCommerceError err = WooCommerceError.fromJson(json.decode(response.body)); - throw err; + throw err; */ } } @@ -1082,17 +1115,58 @@ class WooCommerce { throw err; } } + + Future getCart() async { + WooCart cart; + String keyParam = await getCartKeyParam(); + var url = Uri.parse(this.baseUrl + URL_STORE_API_PATH + 'cart' + keyParam); + print(url); + final response = await http.get(url); + print(response.body); + print(response.statusCode); + _printToLog('response gotten : ' + response.toString()); + if (response.statusCode >= 200 && response.statusCode < 300) { + final jsonStr = json.decode(response.body); + cart = WooCart.fromJson(jsonStr); + return cart; + } else { + _printToLog(' error : ' + response.body); + WooCommerceError err = WooCommerceError.fromJson(json.decode(response.body)); + throw err; + } + } + + Future mergeCarts() async { + await getAuthTokenFromDb(); + _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + String keyParam = await getCartKeyParam(getCartKeyAnyway: true); + final response = await http.get( + Uri.parse(this.baseUrl + URL_COCART + 'cart' + keyParam), + headers: _urlHeader); + _printToLog('response gotten : ' + response.toString()); + if (response.statusCode >= 200 && response.statusCode < 300) { + return true; + } else { + return false; + } + } Future deleteMyCartItem({required String key}) async { Map data = { 'key': key, + 'return_cart': 'false', }; _printToLog('Deleting CartItem With Payload : ' + data.toString()); await getAuthTokenFromDb(); - _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + String keyParam = ''; + if (await isCustomerLoggedIn()) { + _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + } else { + keyParam = await getCartKeyParam(); + } final http.Response response = await http.delete( - Uri.parse(this.baseUrl + URL_STORE_API_PATH + 'cart/items/' + key), + Uri.parse(this.baseUrl + URL_COCART + 'cart/item/' + key + keyParam), headers: _urlHeader, ); _printToLog('response of delete cart : ' + response.body.toString()); @@ -1114,10 +1188,15 @@ class WooCommerce { Future deleteAllMyCartItems() async { await getAuthTokenFromDb(); - _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + String keyParam = ''; + if (await isCustomerLoggedIn()) { + _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + } else { + keyParam = await getCartKeyParam(); + } - final http.Response response = await http.delete( - Uri.parse(this.baseUrl + URL_STORE_API_PATH + 'cart/items/'), + final http.Response response = await http.post( + Uri.parse(this.baseUrl + URL_COCART + 'cart/clear' + keyParam), headers: _urlHeader, ); _printToLog('response of delete cart : ' + response.body.toString()); @@ -1153,7 +1232,7 @@ class WooCommerce { } } - Future updateMyCartItemByKey( + Future updateMyCartItemByKey( {required String key, required int id, required int quantity, @@ -1162,24 +1241,32 @@ class WooCommerce { 'key': key, 'id': id.toString(), 'quantity': quantity.toString(), + 'return_cart': 'false', }; if (variations != null) data['variations'] = variations; await getAuthTokenFromDb(); - _urlHeader['Authorization'] = 'Bearer ' + _authToken!; - final response = await http.put( - Uri.parse(this.baseUrl + URL_STORE_API_PATH + 'cart/items/' + key), + String keyParam = ''; + if (await isCustomerLoggedIn()) { + _urlHeader['Authorization'] = 'Bearer ' + _authToken!; + } else { + keyParam = await getCartKeyParam(); + } + final response = await http.post( + Uri.parse(this.baseUrl + URL_COCART + 'cart/item/' + key + keyParam), headers: _urlHeader, body: data); if (response.statusCode >= 200 && response.statusCode < 300) { - final jsonStr = json.decode(response.body); + /* final jsonStr = json.decode(response.body); _printToLog('added to my cart : ' + jsonStr.toString()); - return WooCartItem.fromJson(jsonStr); + return WooCartItem.fromJson(jsonStr); */ + return true; } else { - WooCommerceError err = + /* WooCommerceError err = WooCommerceError.fromJson(json.decode(response.body)); - throw err; + throw err; */ + return false; } } @@ -1236,7 +1323,7 @@ class WooCommerce { 'product': product, 'dp': dp, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List orders = []; _printToLog('Getting Order With Payload : ' + payload.toString()); @@ -1320,7 +1407,7 @@ class WooCommerce { 'exclude_sale_items': excludeSaleItems, 'minimum_amount': minimumAmount, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); WooCoupon coupon; _setApiResourceUrl( @@ -1341,8 +1428,8 @@ class WooCommerce { String? search, String? after, String? before, - //List exclude, - //List include, + List? exclude, + List? include, int? offset, String? order, String? orderBy, @@ -1352,11 +1439,11 @@ class WooCommerce { ({ 'page': page, 'per_page': perPage, 'search': search, 'after': after, 'before': before, - //'exclude': exclude, 'include': include, + 'exclude': exclude, 'include': include, 'offset': offset, 'order': order, 'orderby': orderBy, 'code': code, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List? coupons; _printToLog('Getting Coupons With Payload : ' + payload.toString()); @@ -1397,7 +1484,7 @@ class WooCommerce { 'orderby': orderBy, 'class': taxClass, }).forEach((k, v) { - if (v != null) payload[k] = v.toString(); + if (v != null) payload[k] = _paramToString(v); }); List taxRates = []; _printToLog('Getting Taxrates With Payload : ' + payload.toString()); @@ -1732,6 +1819,8 @@ class WooCommerce { return _authToken; } + String _paramToString(param) => param is List ? param.join(',') : param.toString(); + // Sets the Uri for an endpoint. String _setApiResourceUrl({ required String path,