Compare commits

..

No commits in common. "master" and "cocart" have entirely different histories.

33 changed files with 207 additions and 512 deletions

13
.idea/compiler.xml generated
View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel>
<module name="app" target="1.8" />
<module name="cocart" target="1.7" />
<module name="core" target="1.7" />
<module name="firebasecart" target="1.8" />
<module name="offlinecart" target="1.8" />
<module name="woodroid" target="1.8" />
</bytecodeTargetLevel>
</component>
</project>

1
.idea/gradle.xml generated
View File

@ -15,7 +15,6 @@
<option value="$PROJECT_DIR$/cocart" />
<option value="$PROJECT_DIR$/core" />
<option value="$PROJECT_DIR$/firebasecart" />
<option value="$PROJECT_DIR$/offlinecart" />
<option value="$PROJECT_DIR$/woodroid" />
</set>
</option>

View File

@ -237,10 +237,5 @@ The sample app implements an MVVM approach which would look slightly different f
## Contribution
Contributions are highly welcomed, just create a PR
## Slack
You can also reach out through <a href="https://join.slack.com/t/woodroid/shared_invite/enQtODg1ODYzMDAzOTcxLTE4NDA0MTYyYjY5ZmVmNTU4OTEzYWQzZDcwN2Y1ZTZkMzk4ZDY0ZGU4NmZlMzQ1NjlhM2RlZDc4Mjc4ZjE2NzI">slack</a> in case of any issues with installation or feature request
## Love the Project?
You can donate to support the project futher.<a class="donate-with-crypto" href="https://commerce.coinbase.com/checkout/3efb7008-27b1-4c64-934b-791e5c1a6cda"> Donate with Crypto </a>

View File

@ -200,9 +200,6 @@ dependencies {
implementation project(path: ':firebasecart')
implementation project(path: ':core')
implementation project(path: ':cocart')
implementation project(path: ':offlinecart')
debugImplementation 'im.dino:dbinspector:3.4.1@aar'
implementation 'org.fabiomsr:moneytextview:1.1.0'

View File

@ -5,7 +5,6 @@ import dagger.Provides
import me.gilo.woodroid.app.Config
import me.gilo.woodroid.app.WcApp
import me.gilo.woodroid.Woocommerce
import me.gilo.woodroid.offlinecart.repo.RoomCartRepository
import javax.inject.Singleton
@ -36,11 +35,4 @@ class AppModule {
.build()
}
@Provides
@Singleton
internal fun providesRoomCartRepository(): RoomCartRepository = RoomCartRepository(app!!.baseContext)
}

View File

@ -7,16 +7,14 @@ import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import me.gilo.cocart.model.CartItem
import me.gilo.woodroid.app.common.CompletionGenericLiveData
import me.gilo.woodroid.app.common.QueryLiveData
import me.gilo.woodroid.app.common.WooLiveData
import me.gilo.woodroid.app.models.CartLineItem
import me.gilo.woodroid.Woocommerce
import me.gilo.woodroid.core.cart.Cart
import me.gilo.woodroid.core.cart.CartItem
import me.gilo.woodroid.models.Product
import me.gilo.woodroid.offlinecart.repo.RoomCartRepository
import javax.inject.Inject
open class CartRepository @Inject
@ -74,4 +72,33 @@ constructor() {
}
}
fun addToCart(product: Product): CompletionGenericLiveData<DocumentReference> {
val completion = CompletionGenericLiveData<DocumentReference>()
val lineItem = CartLineItem()
lineItem.setProductId(product.id)
lineItem.product = product
lineItem.setQuantity(1)
cart.add(lineItem).addOnCompleteListener(completion)
return completion
}
fun addToCart(context: Context, productId: Int, quantity: Int): WooLiveData<CartItem> {
val callBack = WooLiveData<CartItem>()
woocommerce.CartRepository(context).addToCart(productId, quantity).enqueue(callBack)
return callBack
}
fun cart(context: Context, customerId: String): WooLiveData<Map<String, CartItem>> {
val callBack = WooLiveData<Map<String, CartItem>>()
woocommerce.CartRepository(context).cart(customerId).enqueue(callBack)
return callBack
}
}

View File

@ -18,7 +18,7 @@ constructor() {
fun create(category: Category): WooLiveData<Category> {
val callBack = WooLiveData<Category>()
woocommerce.CategoryRepository().create(category).enqueue(callBack)
woocommerce!!.CategoryRepository().create(category).enqueue(callBack)
return callBack
}
@ -26,42 +26,42 @@ constructor() {
fun category(id: Int): WooLiveData<Category> {
val callBack = WooLiveData<Category>()
woocommerce.CategoryRepository().category(id).enqueue(callBack)
woocommerce!!.CategoryRepository().category(id).enqueue(callBack)
return callBack
}
fun categories(): WooLiveData<List<Category>> {
val callBack = WooLiveData<List<Category>>()
woocommerce.CategoryRepository().categories().enqueue(callBack)
woocommerce!!.CategoryRepository().categories().enqueue(callBack)
return callBack
}
fun categories(productCategoryFilter: ProductCategoryFilter): WooLiveData<List<Category>> {
val callBack = WooLiveData<List<Category>>()
woocommerce.CategoryRepository().categories(productCategoryFilter).enqueue(callBack)
woocommerce!!.CategoryRepository().categories(productCategoryFilter).enqueue(callBack)
return callBack
}
fun update(id: Int, category: Category): WooLiveData<Category> {
val callBack = WooLiveData<Category>()
woocommerce.CategoryRepository().update(id, category).enqueue(callBack)
woocommerce!!.CategoryRepository().update(id, category).enqueue(callBack)
return callBack
}
fun delete(id: Int): WooLiveData<Category> {
val callBack = WooLiveData<Category>()
woocommerce.CategoryRepository().delete(id).enqueue(callBack)
woocommerce!!.CategoryRepository().delete(id).enqueue(callBack)
return callBack
}
fun delete(id: Int, force: Boolean): WooLiveData<Category> {
val callBack = WooLiveData<Category>()
woocommerce.CategoryRepository().delete(id, force).enqueue(callBack)
woocommerce!!.CategoryRepository().delete(id, force).enqueue(callBack)
return callBack
}

View File

@ -23,9 +23,7 @@ import me.gilo.woodroid.app.models.CartLineItem
import me.gilo.woodroid.app.ui.state.ProgressDialogFragment
import me.gilo.woodroid.app.utils.AppUtils
import me.gilo.woodroid.app.viewmodels.ProductViewModel
import me.gilo.woodroid.core.cart.CartItem
import me.gilo.woodroid.models.Product
import me.gilo.woodroid.offlinecart.repo.RoomCartRepository
import org.greenrobot.eventbus.EventBus
@ -55,42 +53,86 @@ class ProductActivity : BaseActivity() {
if (productId != 0){
product(productId)
checkIfExistsInCart(productId)
}
cart()
viewCart(AppUtils(baseContext).cartSession)
}
private fun checkIfExistsInCart(productId: Int) {
RoomCartRepository(baseContext).exists(productId).observe(this, Observer {productExists ->
if (productExists) {
fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.carnation_red))
fab.setImageDrawable(ContextCompat.getDrawable(baseContext, R.drawable.baseline_remove_shopping_cart_24))
}else{
fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.colorPrimary))
fab.setImageDrawable(ContextCompat.getDrawable(baseContext, R.drawable.baseline_add_shopping_cart_24))
}
productInCart = productExists
})
}
private fun addToCart(product: Product) {
RoomCartRepository(baseContext).addToCart(
CartItem(
productId = product.id,
productImage = product.getFeatureImage(),
quantity = 1,
productPrice = product.price
)
viewModel.addToCart(baseContext, product.id, 1).observe(this, Observer { response ->
when (response!!.status()) {
Status.LOADING -> {
)
}
Status.SUCCESS -> {
toast("success!")
val cartItem = response.data()
AppUtils(baseContext).saveCartSession(cartItem.key, "")
}
Status.ERROR -> {
toast("error : " + response.error().message)
}
Status.EMPTY -> {
}
}
})
}
private fun viewCart(customerId: String) {
viewModel.cart(baseContext, customerId).observe(this, Observer { response ->
when (response!!.status()) {
Status.LOADING -> {
}
Status.SUCCESS -> {
toast("success!")
}
Status.ERROR -> {
toast("error : " + response.error().message)
}
Status.EMPTY -> {
}
}
})
}
private fun removeFromCart(cartLineItem: CartLineItem) {
viewModel.deleteItem(cartLineItem).observe(this, androidx.lifecycle.Observer { response ->
when (response!!.status()) {
Status.LOADING -> {
}
Status.SUCCESS -> {
}
Status.ERROR -> {
toast("error : " + response.error().message)
}
Status.EMPTY -> {
}
}
})
}
@ -126,7 +168,7 @@ class ProductActivity : BaseActivity() {
private fun cart() {
viewModel.cart().observe(this, Observer { response ->
viewModel.cart().observe(this, androidx.lifecycle.Observer { response ->
when (response!!.status()) {
Status.LOADING -> {
@ -147,6 +189,8 @@ class ProductActivity : BaseActivity() {
}
}
toggleFab()
if (cartItems.size == 0 && tvCartCounter != null){
tvCartCounter?.visibility = View.GONE
}else{
@ -164,6 +208,7 @@ class ProductActivity : BaseActivity() {
Status.EMPTY -> {
productInCart = false
cartItems.clear()
toggleFab()
if (cartItems.size == 0 && tvCartCounter != null){
tvCartCounter?.visibility = View.GONE
@ -178,6 +223,17 @@ class ProductActivity : BaseActivity() {
}
private fun toggleFab() {
if (productInCart) {
fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.carnation_red))
fab.setImageDrawable(ContextCompat.getDrawable(baseContext, R.drawable.baseline_remove_shopping_cart_24))
}else{
fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.colorPrimary))
fab.setImageDrawable(ContextCompat.getDrawable(baseContext, R.drawable.baseline_add_shopping_cart_24))
}
}
private fun setUpPage(product: Product) {
tvTitle.text = product.name
tvDescription.text = Html.fromHtml(product.description)

View File

@ -137,6 +137,26 @@ class ShopActivity : BaseActivity() {
private fun cart() {
val cartKey = AppUtils(baseContext).cartSession
viewModel.cart(baseContext, cartKey).observe(this, androidx.lifecycle.Observer { response ->
when (response!!.status()) {
Status.LOADING -> {
}
Status.SUCCESS -> {
val cartResponse = response.data()
}
Status.ERROR -> {
}
Status.EMPTY -> {
}
}
})
}
private fun search(query : String) {

View File

@ -31,6 +31,10 @@ public final class CartViewModel extends ViewModel {
this.customerRepository = customerRepository;
}
public CompletionGenericLiveData<DocumentReference> addToCart(Product product) {
return cartRepository.addToCart(product);
}
public QueryLiveData<CartLineItem> cart() {
return cartRepository.cart();
}
@ -47,6 +51,10 @@ public final class CartViewModel extends ViewModel {
return cartRepository.setQuantity(cartLineItem, quantity);
}
// public WooLiveData<Map<String, CartLineItem>> cart(Context context) {
// return cartRepository.cart(context);
// }
public WooLiveData<Order> createOrder(Order order) {
return orderRepository.create(order);
}

View File

@ -2,6 +2,10 @@ package me.gilo.woodroid.app.viewmodels;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import android.content.Context;
import com.google.firebase.firestore.DocumentReference;
import me.gilo.cocart.model.CartItem;
import me.gilo.woodroid.app.common.CompletionGenericLiveData;
import me.gilo.woodroid.app.common.QueryLiveData;
import me.gilo.woodroid.app.common.WooLiveData;
@ -9,7 +13,7 @@ import me.gilo.woodroid.app.models.CartLineItem;
import me.gilo.woodroid.app.repo.CartRepository;
import me.gilo.woodroid.app.repo.OrderRepository;
import me.gilo.woodroid.app.repo.ProductRepository;
import me.gilo.woodroid.models.LineItem;
import me.gilo.woodroid.models.Order;
import me.gilo.woodroid.models.Product;
import me.gilo.woodroid.models.ProductReview;
@ -48,6 +52,9 @@ public final class ProductViewModel extends ViewModel {
return productRepository.products();
}
public CompletionGenericLiveData<DocumentReference> addToCart(Product product) {
return cartRepository.addToCart(product);
}
public WooLiveData<Order> addToCart(int productId) {
return orderRepository.addToCart(productId);
@ -69,6 +76,14 @@ public final class ProductViewModel extends ViewModel {
return cartRepository.setQuantity(cartLineItem, quantity);
}
public WooLiveData<Map<String, CartItem>> cart(Context context, String customerId) {
return cartRepository.cart(context, customerId);
}
public WooLiveData<CartItem> addToCart(Context context, int productId, int quantity) {
return cartRepository.addToCart(context, productId, quantity);
}
public WooLiveData<List<Product>> products(ProductFilter filter) {
return productRepository.products(filter);
}

View File

@ -10,7 +10,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0-alpha02'
classpath 'com.android.tools.build:gradle:4.0.0-alpha04'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.2.0'
classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.1.0'

View File

@ -1,7 +1,6 @@
package me.gilo.woodroid.core.cart
import androidx.lifecycle.LiveData
import me.gilo.woodroid.core.cart.lines.FeeLine
import me.gilo.woodroid.core.cart.lines.LineItem
import me.gilo.woodroid.core.cart.lines.ShippingLine
@ -33,7 +32,6 @@ data class Cart(
var feeLines: List<FeeLine> = ArrayList(),
var couponLines: List<Any> = ArrayList(),
var items: LiveData<List<CartItem>>
var couponLines: List<Any> = ArrayList()
)

View File

@ -1,16 +0,0 @@
package me.gilo.woodroid.core.cart
data class CartItem (
var id: Int? = null,
var createdAt: Long? = null,
var modifiedAt: Long? = null,
var productId: Int = 0,
var variationId: Int? = 0,
var quantity: Int = 0,
var productName: String? = "",
var productPrice: String? = "",
var productImage: String? = ""
)

View File

@ -8,10 +8,10 @@ abstract class CartRepository{
abstract fun clear(): LiveData<String>
abstract fun count(id: Int): LiveData<Int>
abstract fun cart(): LiveData<Cart>
abstract fun addToCart(cartItem: CartItem)
abstract fun cart(): LiveData<List<LineItem>>
abstract fun addToCart(lineItem: LineItem): LiveData<LineItem>
abstract fun delete(cartId: String): LiveData<String>
abstract fun restore(cartId: String): LiveData<String>
abstract fun update(cartId: String, quantity: Int)
abstract fun update(cartId: String, quantity: Int): LiveData<LineItem>
}

View File

@ -1,16 +1,51 @@
package me.gilo.woodroid.firebasecart
import androidx.lifecycle.LiveData
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import me.gilo.woodroid.core.cart.CartRepository
import me.gilo.woodroid.core.cart.lines.LineItem
open class FirebaseCartRepository(userId : String){
open class FirebaseCartRepository(userId : String) : CartRepository() {
private val cart: CollectionReference = FirebaseFirestore.getInstance()
.collection("users")
.document(userId)
.collection("cart")
override fun cart(): LiveData<List<LineItem>> {
TODO("not implemented")
}
override fun clear(): LiveData<String> {
TODO("not implemented")
}
override fun count(id: Int): LiveData<Int> {
TODO("not implemented")
}
override fun addToCart(lineItem: LineItem): LiveData<LineItem> {
TODO("not implemented")
}
override fun delete(cartId: String): LiveData<String> {
TODO("not implemented")
}
override fun restore(cartId: String): LiveData<String> {
TODO("not implemented")
}
override fun update(cartId: String, quantity: Int): LiveData<LineItem> {
TODO("not implemented")
}
}

View File

@ -1,6 +1,6 @@
#Tue Mar 17 11:45:23 EAT 2020
#Sat Nov 30 11:05:14 EAT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-rc-1-all.zip

View File

@ -1,60 +0,0 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
kapt "androidx.lifecycle:lifecycle-compiler:2.3.0-alpha01"
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.2.0'
implementation 'androidx.paging:paging-runtime-ktx:2.1.1'
// Room components
implementation "androidx.room:room-runtime:2.2.4"
kapt "androidx.room:room-compiler:2.2.4"
androidTestImplementation "androidx.room:room-testing:2.2.4"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
implementation project(path: ':core')
implementation 'androidx.core:core-ktx:1.2.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

View File

@ -1,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -1,24 +0,0 @@
package me.gilo.woodroid.offlinecart
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("me.gilo.woodroid.offlinecart.test", appContext.packageName)
}
}

View File

@ -1,2 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.gilo.woodroid.offlinecart" />

View File

@ -1,5 +0,0 @@
package me.gilo.woodroid.offlinecart.config;
public class Config {
public static String DB_NAME = "db_woodroid_cart";
}

View File

@ -1,32 +0,0 @@
package me.gilo.woodroid.offlinecart.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import me.gilo.woodroid.offlinecart.entity.CartItemEntity
@Dao
interface CartItemDao {
@Insert
fun insert(category: CartItemEntity?): Long?
@Query("SELECT * FROM cart_item ORDER BY created_at desc")
fun fetchAll(): List<CartItemEntity>
@Query("SELECT * FROM cart_item ORDER BY created_at desc")
fun items(): LiveData<List<CartItemEntity>>
@Query("SELECT COUNT(*) FROM cart_item")
fun count(): LiveData<Int>
@Query("SELECT COUNT(*) FROM cart_item where product_id = :productId")
fun exists(productId: Int): LiveData<Boolean>
@Query("SELECT * FROM cart_item WHERE id =:id")
operator fun get(id: Int): LiveData<CartItemEntity>
@Update
fun update(category: CartItemEntity?)
@Delete
fun delete(category: CartItemEntity?)
}

View File

@ -1,15 +0,0 @@
package me.gilo.woodroid.offlinecart.db
import androidx.room.Database
import androidx.room.RoomDatabase
import me.gilo.woodroid.offlinecart.dao.CartItemDao
import me.gilo.woodroid.offlinecart.entity.CartItemEntity
@Database(
entities = [
CartItemEntity::class
], version = 1, exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun cartItemDao(): CartItemDao
}

View File

@ -1,60 +0,0 @@
package me.gilo.woodroid.offlinecart.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import me.gilo.woodroid.core.cart.CartItem
@Entity(tableName = "cart_item")
data class CartItemEntity (
@PrimaryKey(autoGenerate = true)
var id: Int?,
@ColumnInfo(name = "created_at")
var createdAt: Long? = null,
@ColumnInfo(name = "modified_at")
var modifiedAt: Long? = null,
@ColumnInfo(name = "product_id")
var productId: Int = 0,
@ColumnInfo(name = "quantity")
var quantity: Int = 0,
@ColumnInfo(name = "variation_id")
var variationId: Int? = 0,
@ColumnInfo(name = "product_name")
var productName: String? = "",
@ColumnInfo(name = "product_price")
var productPrice: String? = "",
@ColumnInfo(name = "product_image")
var productImage: String? = ""
)
fun CartItemEntity.toCartItem() = CartItem(
id = this.id,
createdAt = this.createdAt,
modifiedAt = this.modifiedAt,
productId = this.productId,
quantity = this.quantity,
variationId = this.variationId,
productName = this.productName,
productPrice = this.productPrice,
productImage = this.productImage
)
fun CartItem.toCartItemEntity() = CartItemEntity(
id = this.id,
createdAt = this.createdAt,
modifiedAt = this.modifiedAt,
productId = this.productId,
quantity = this.quantity,
variationId = this.variationId,
productName = this.productName,
productPrice = this.productPrice,
productImage = this.productImage
)

View File

@ -1,69 +0,0 @@
package me.gilo.woodroid.offlinecart.repo
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.room.Room
import me.gilo.woodroid.offlinecart.task.DeleteCartItem
import me.gilo.woodroid.offlinecart.task.InsertCartItem
import me.gilo.woodroid.offlinecart.task.UpdateCartItem
import me.gilo.woodroid.core.cart.Cart
import me.gilo.woodroid.core.cart.CartItem
import me.gilo.woodroid.offlinecart.config.Config
import me.gilo.woodroid.offlinecart.db.AppDatabase
import me.gilo.woodroid.offlinecart.entity.CartItemEntity
import me.gilo.woodroid.offlinecart.entity.toCartItem
import me.gilo.woodroid.offlinecart.utils.AppUtils
class RoomCartRepository(val context: Context){
private val appDatabase: AppDatabase = Room
.databaseBuilder(context, AppDatabase::class.java, Config.DB_NAME)
.fallbackToDestructiveMigration()
.build()
fun addToCart(cartItem: CartItem) {
if (cartItem.createdAt == null) {
cartItem.createdAt = AppUtils.currentDateTime.time
}
InsertCartItem(appDatabase, cartItem).execute()
}
fun update(cartItem: CartItem) {
cartItem.modifiedAt = AppUtils.currentDateTime.time
UpdateCartItem(appDatabase, cartItem).execute()
}
fun count(): LiveData<Int> {
return appDatabase.cartItemDao().count()
}
fun exists(productId: Int): LiveData<Boolean> {
return appDatabase.cartItemDao().exists(productId)
}
fun delete(cartItem: CartItem) {
DeleteCartItem(appDatabase, cartItem).execute()
}
fun cartItem(id: Int): LiveData<CartItem> {
return Transformations.map(
appDatabase.cartItemDao().get(id)
) { cartItemEntity: CartItemEntity? -> cartItemEntity?.toCartItem()
}
}
fun cart(): Cart {
return Cart(
items = Transformations.map(appDatabase.cartItemDao().items()){
it.map { cartItemEntity -> cartItemEntity.toCartItem() }
}
)
}
}

View File

@ -1,47 +0,0 @@
package me.gilo.woodroid.offlinecart.task
import android.os.AsyncTask
import androidx.lifecycle.MutableLiveData
import me.gilo.woodroid.core.cart.Cart
import me.gilo.woodroid.core.cart.CartItem
import me.gilo.woodroid.offlinecart.db.AppDatabase
import me.gilo.woodroid.offlinecart.entity.toCartItem
import me.gilo.woodroid.offlinecart.entity.toCartItemEntity
import java.util.*
import kotlin.collections.ArrayList
class InsertCartItem(
private val appDatabase: AppDatabase,
private val cartItem: CartItem
) :
AsyncTask<Void, Void, Long?>() {
override fun doInBackground(vararg voids: Void): Long? {
return appDatabase.cartItemDao()
.insert(cartItem.toCartItemEntity())
}
}
class UpdateCartItem(
private val appDatabase: AppDatabase,
private val cartItem: CartItem
) :
AsyncTask<Void, Void, Unit>() {
override fun doInBackground(vararg voids: Void) {
return appDatabase.cartItemDao().update(cartItem.toCartItemEntity())
}
}
class DeleteCartItem(
private val appDatabase: AppDatabase,
private val cartItem: CartItem
) :
AsyncTask<Void, Void, Unit>() {
override fun doInBackground(vararg voids: Void) {
return appDatabase.cartItemDao().delete(cartItem.toCartItemEntity())
}
}

View File

@ -1,35 +0,0 @@
package me.gilo.woodroid.offlinecart.utils
import android.content.Context
import android.widget.Toast
import androidx.annotation.StringRes
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/*
*
*/
class AppUtils(internal var context: Context) {
internal var token: String? = null
internal var expiry: String? = null
companion object {
val currentDateTime: Date
get() = Calendar.getInstance().time
fun getFormattedDateString(date: Date?): String? {
try {
var spf = SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy")
val dateString = spf.format(date)
val newDate = spf.parse(dateString)
spf = SimpleDateFormat("dd MMM yyyy HH:mm:ss")
return spf.format(newDate)
} catch (e: ParseException) {
e.printStackTrace()
}
return null
}
}
}

View File

@ -1,19 +0,0 @@
package me.gilo.woodroid.offlinecart.utils
import androidx.room.TypeConverter
import java.util.*
class Converters {
@TypeConverter
public fun fromTimestamp(value: Long?): Date? {
return if (value == null) null else Date(value)
}
@TypeConverter
public fun dateToTimestamp(date: Date?): Long? {
return date?.time
}
}

View File

@ -1,17 +0,0 @@
package me.gilo.woodroid.offlinecart
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

View File

@ -1,3 +1,2 @@
include ':app', ':woodroid', ':firebasecart', ':core'
include ':cocart'
include ':offlinecart'

View File

@ -1,6 +1,5 @@
package me.gilo.woodroid.models
import com.google.gson.annotations.SerializedName
import java.io.Serializable
import java.util.ArrayList
import java.util.Date
@ -62,23 +61,13 @@ class Product : Serializable {
lateinit var purchase_note: String
lateinit var categories: ArrayList<Category>
lateinit var tags: ArrayList<Tag>
@SerializedName("attributes")
lateinit var productAttributes: ArrayList<ProductAttribute>
lateinit var default_attributes: ArrayList<DefaultAttribute>
lateinit var variations: ArrayList<Int>
lateinit var grouped_products: ArrayList<Int>
var menu_order: Int = 0
lateinit var meta_data: ArrayList<Metadata>
lateinit var images: ArrayList<Image>
fun getFeatureImage(): String{
if(this.images.isEmpty()){
return ""
}
return this.images.first().src!!
}
}