add photo integration

This commit is contained in:
Stanislaw-Golebiewski 2020-01-20 17:02:33 +01:00
parent 22ee8ab48d
commit 5a6ddce8ad
5 changed files with 90 additions and 33 deletions

View File

@ -17,20 +17,16 @@ from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin from django.contrib import admin
from django.urls import include, path from django.urls import include, path
from django.conf.urls import url from django.conf.urls import url
from knox import views as knox_views from knox import views as knox_views
from .views import LoginView from .views import LoginView
# from rest_framework.authtoken import views
from bills import endpoints from bills import endpoints
import core
urlpatterns = [ urlpatterns = [
# path('bills/', include('core.urls')), path('api/photo/', include('core.urls')),
path('api/admin/', admin.site.urls), path('api/admin/', admin.site.urls),
url('^api/', include(endpoints)), url('^api/', include(endpoints)),
# url(r'^api/auth/', views.obtain_auth_token)
# url(r'api/auth/', include('knox.urls'))
url(r'api/auth/login/', LoginView.as_view(), name='knox_login'), url(r'api/auth/login/', LoginView.as_view(), name='knox_login'),
url(r'api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout'), url(r'api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout'),
url(r'api/auth/logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), url(r'api/auth/logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'),

View File

@ -28,7 +28,7 @@ def upload_bill(request):
product_list = img_to_products(img) product_list = img_to_products(img)
products = [{'name': prod, 'price': pri} for _, prod, pri in product_list] products = [{'name': prod, 'price': pri} for _, prod, pri in product_list]
response = JsonResponse({'products': products}) response = JsonResponse({'products': products})
return HttpResponse(response) return response
@require_http_methods(["POST"]) @require_http_methods(["POST"])

View File

@ -12,7 +12,7 @@ import {
} from "semantic-ui-react"; } from "semantic-ui-react";
import { DateInput } from "semantic-ui-calendar-react"; import { DateInput } from "semantic-ui-calendar-react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import axios from "axios"; import axios, { post } from "axios";
import useGlobal from "../../../../utils/global_state"; import useGlobal from "../../../../utils/global_state";
import config from "../../../../config"; import config from "../../../../config";
@ -27,9 +27,52 @@ function AddMetadata() {
const [shopsLoading, setShopsLoading] = useState(true); const [shopsLoading, setShopsLoading] = useState(true);
const [globalState, globalActions] = useGlobal(); const [globalState, globalActions] = useGlobal();
const [pickedShop, changePickedShop] = useState(""); const [pickedShop, changePickedShop] = useState("");
const [photoIsLoading, setPhotoIsLoading] = useState(false);
const [productsFromPhoto, setProductsFromPhoto] = useState(null);
const uploadPhoto = event => { const uploadPhoto = event => {
setSelectedFile(URL.createObjectURL(event.target.files[0])); setPhotoIsLoading(true);
// setSelectedFile(URL.createObjectURL(event.target.files[0]));
fileUploadRequest(event.target.files[0], true)
.then(resp => {
const reader = new FileReader();
reader.addEventListener("loadend", e => {
const text = e.srcElement.result;
setProductsFromPhoto(JSON.parse(text).products);
});
reader.readAsText(resp.data);
})
.catch(error => {
console.log(error);
});
fileUploadRequest(event.target.files[0])
.then(resp => {
setSelectedFile(URL.createObjectURL(resp.data));
setPhotoIsLoading(false);
})
.catch(error => {
console.log(error);
setPhotoIsLoading(false);
});
};
const fileUploadRequest = (file, get_products = false) => {
let url = `${config.api_url}/api/photo/`;
if (!get_products) {
url += "debug_img/";
}
const formData = new FormData();
formData.append("image", file);
const cnf = {
headers: {
"content-type": "multipart/form-data",
Authorization: `Token ${globalState.auth_token}`
},
responseType: "blob"
};
return post(url, formData, cnf);
}; };
//set date to current day //set date to current day
@ -104,9 +147,7 @@ function AddMetadata() {
id="mypic" id="mypic"
accept="image/*" accept="image/*"
ref={fileInputRef} ref={fileInputRef}
onChange={stuff => { onChange={uploadPhoto}
uploadPhoto(stuff);
}}
/> />
<Button <Button
fluid fluid
@ -118,24 +159,35 @@ function AddMetadata() {
<Icon name="camera" /> <Icon name="camera" />
Dodaj zdjęcie Dodaj zdjęcie
</Button> </Button>
{pickedDate !== "" && pickedShop !== "" && (
<Button <Button
fluid fluid
icon icon
color="olive" disabled={pickedDate === "" || pickedShop === ""}
onClick={() => { color="olive"
history.push("/home/add_receipt/list", { onClick={() => {
shop: pickedShop, history.push("/home/add_receipt/list", {
date: pickedDate shop: pickedShop,
}); date: pickedDate,
}} products: productsFromPhoto
className="add-product-btn" });
> }}
<Icon name="arrow right" /> className="add-product-btn"
Dalej >
</Button> <Icon name="arrow right" />
Dalej
</Button>
{productsFromPhoto && (
<Container>Rozpoznane produkty: {productsFromPhoto.length}</Container>
)}
{selectedFile && <Image centered src={selectedFile} size="medium" />}
{photoIsLoading && (
<Dimmer active>
<Loader size="massive">Loading</Loader>
</Dimmer>
)} )}
{selectedFile && <Image centered src={selectedFile} size="small" />}
</div> </div>
</div> </div>
); );

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useState, useEffect } from "react";
import { Button, Container, Icon, Menu } from "semantic-ui-react"; import { Button, Container, Icon, Menu } from "semantic-ui-react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
@ -21,8 +21,17 @@ function ProductsList() {
const [pickedProduct, setPickedProduct] = useState(-1); const [pickedProduct, setPickedProduct] = useState(-1);
const history = useHistory(); const history = useHistory();
useEffect(() => {
const meta_products = history.location.state.products;
console.log(meta_products);
const new_products = [];
for (let i = 0; i < meta_products.length; i++) {
new_products.push({ name: meta_products[i].name, price: 0.0, tags: [] });
}
console.log(new_products);
setProducts(new_products);
}, []);
const meta_info = history.location.state; const meta_info = history.location.state;
const addItem = item => { const addItem = item => {
setProducts([...products, item]); setProducts([...products, item]);
}; };

View File

@ -81,7 +81,7 @@ function Receipts() {
const processResponse = data => { const processResponse = data => {
setReceipts(data.results); setReceipts(data.results);
setReceiptsLoading(false); setReceiptsLoading(false);
setMaxPage(Math.floor(data.count / 10)); setMaxPage(Math.ceil(data.count / 10));
}; };
return ( return (