import from Fuelly complete

This commit is contained in:
Akhil Gupta
2021-06-27 11:04:58 +05:30
parent 5f96345828
commit f851a2dc19
10 changed files with 247 additions and 22 deletions

View File

@@ -17,9 +17,9 @@ func fuellyImport(c *gin.Context) {
c.JSON(http.StatusUnprocessableEntity, err)
return
}
err = service.FuellyImport(bytes, c.MustGet("userId").(string))
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
errors := service.FuellyImport(bytes, c.MustGet("userId").(string))
if len(errors) > 0 {
c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": errors})
return
}
c.JSON(http.StatusOK, gin.H{})

View File

@@ -117,6 +117,7 @@ type Fillup struct {
Date time.Time `json:"date"`
Currency string `json:"currency"`
DistanceUnit DistanceUnit `json:"distanceUnit"`
Source string `json:"source"`
}
func (v *Fillup) FuelUnitDetail() EnumDetail {
@@ -145,6 +146,7 @@ type Expense struct {
Date time.Time `json:"date"`
Currency string `json:"currency"`
DistanceUnit DistanceUnit `json:"distanceUnit"`
Source string `json:"source"`
}
type Setting struct {

View File

@@ -5,30 +5,33 @@ import (
"encoding/csv"
"fmt"
"strconv"
"strings"
"time"
"github.com/akhilrex/hammond/db"
"github.com/leekchan/accounting"
)
func FuellyImport(content []byte, userId string) error {
func FuellyImport(content []byte, userId string) []string {
stream := bytes.NewReader(content)
reader := csv.NewReader(stream)
records, err := reader.ReadAll()
var errors []string
if err != nil {
return err
errors = append(errors, err.Error())
return errors
}
vehicles, err := GetUserVehicles(userId)
if err != nil {
return err
errors = append(errors, err.Error())
return errors
}
user, err := GetUserById(userId)
if err != nil {
return err
errors = append(errors, err.Error())
return errors
}
var vehicleMap map[string]db.Vehicle = make(map[string]db.Vehicle)
@@ -41,8 +44,6 @@ func FuellyImport(content []byte, userId string) error {
layout := "2006-01-02 15:04"
altLayout := "2006-01-02 3:04 PM"
var errors []string
for index, record := range records {
if index == 0 {
continue
@@ -111,6 +112,7 @@ func FuellyImport(content []byte, userId string) error {
Date: date,
Currency: user.Currency,
DistanceUnit: user.DistanceUnit,
Source: "Fuelly",
})
}
@@ -128,12 +130,13 @@ func FuellyImport(content []byte, userId string) error {
Currency: user.Currency,
Date: date,
DistanceUnit: user.DistanceUnit,
Source: "Fuelly",
})
}
}
if len(errors) != 0 {
return fmt.Errorf(strings.Join(errors, "\n"))
return errors
}
tx := db.DB.Begin()
@@ -143,15 +146,22 @@ func FuellyImport(content []byte, userId string) error {
}
}()
if err := tx.Error; err != nil {
return err
errors = append(errors, err.Error())
return errors
}
if err := tx.Create(&fillups).Error; err != nil {
tx.Rollback()
return err
errors = append(errors, err.Error())
return errors
}
if err := tx.Create(&expenses).Error; err != nil {
tx.Rollback()
return err
errors = append(errors, err.Error())
return errors
}
return tx.Commit().Error
err = tx.Commit().Error
if err != nil {
errors = append(errors, err.Error())
}
return errors
}

View File

@@ -139,6 +139,7 @@ func CreateFillup(model models.CreateFillupRequest) (*db.Fillup, error) {
Date: model.Date,
Currency: user.Currency,
DistanceUnit: user.DistanceUnit,
Source: "API",
}
tx := db.DB.Create(&fillup)
@@ -166,6 +167,7 @@ func CreateExpense(model models.CreateExpenseRequest) (*db.Expense, error) {
Date: model.Date,
Currency: user.Currency,
DistanceUnit: user.DistanceUnit,
Source: "API",
}
tx := db.DB.Create(&expense)

View File

@@ -19,10 +19,10 @@ export default {
title: () => 'Quick Entries',
badge: () => this.unprocessedQuickEntries.length,
},
// {
// name: 'profile',
// title: () => 'Logged in as ' + this.currentUser.name,
// },
{
name: 'import',
title: () => 'Import',
},
{
name: 'settings',
title: 'Settings',

View File

@@ -392,6 +392,24 @@ export default [
},
props: (route) => ({ user: store.state.auth.currentUser || {} }),
},
{
path: '/import',
name: 'import',
component: () => lazyLoadView(import('@views/import.vue')),
meta: {
authRequired: true,
},
props: (route) => ({ user: store.state.auth.currentUser || {} }),
},
{
path: '/import/fuelly',
name: 'import-fuelly',
component: () => lazyLoadView(import('@views/import-fuelly.vue')),
meta: {
authRequired: true,
},
props: (route) => ({ user: store.state.auth.currentUser || {} }),
},
{
path: '/logout',
name: 'logout',
@@ -399,9 +417,7 @@ export default [
authRequired: true,
beforeResolve(routeTo, routeFrom, next) {
store.dispatch('auth/logOut').then((data) => {
const authRequiredOnPreviousRoute = routeFrom.matched.some(
(route) => route.meta.authRequired
)
const authRequiredOnPreviousRoute = routeFrom.matched.some((route) => route.meta.authRequired)
// Navigate back to previous page, or home as a fallback
next(authRequiredOnPreviousRoute ? { name: 'login' } : { ...routeFrom })
})

View File

@@ -0,0 +1,7 @@
import ImportFuelly from './import-fuelly'
describe('@views/import-fuelly', () => {
it('is a valid view', () => {
expect(ImportFuelly).toBeAViewComponent()
})
})

View File

@@ -0,0 +1,144 @@
<script>
import Layout from '@layouts/main.vue'
import { mapState } from 'vuex'
import axios from 'axios'
export default {
page: {
title: 'Import Fuelly',
meta: [{ name: 'description', content: 'The Import Fuelly page.' }],
},
components: { Layout },
computed: {
...mapState('utils', ['isMobile']),
uploadButtonLabel() {
if (this.isMobile) {
if (this.file == null) {
return 'Choose Photo'
} else {
return ''
}
} else {
if (this.file == null) {
return 'Choose CSV'
} else {
return ''
}
}
},
},
props: {
user: {
type: Object,
required: true,
},
},
data: function() {
return {
file: null,
tryingToCreate: false,
errors: [],
}
},
methods: {
importFuelly() {
if (this.file == null) {
return
}
this.tryingToCreate = true
this.errorMessage = ''
const formData = new FormData()
formData.append('file', this.file, this.file.name)
axios
.post(`/api/import/fuelly`, formData)
.then((data) => {
this.$buefy.toast.open({
message: 'Data Imported Successfully',
type: 'is-success',
duration: 3000,
})
this.file = null
})
.catch((ex) => {
this.$buefy.toast.open({
duration: 5000,
message: 'There was some issue with importing the file. Please check the error message',
position: 'is-bottom',
type: 'is-danger',
})
if (ex.response && ex.response.data.errors) {
this.errors = ex.response.data.errors
}
})
.finally(() => {
this.tryingToCreate = false
})
},
},
}
</script>
<template>
<Layout>
<div class="columns box">
<div class="column">
<h1 class="title">Import from Fuelly</h1>
</div>
</div>
<br />
<div class="columns">
<div class="column">
<p class="subtitle"> Steps to import data from Fuelly</p>
<ol>
<li
>Export your data from Fuelly in the CSV format. Steps to do that can be found
<a href="http://docs.fuelly.com/acar-import-export-center" target="_nofollow">here</a>.</li
>
<li>Make sure that you have already created the vehicles in Hammond platform.</li>
<li>Make sure that the Vehicle nickname in Hammond is exactly the same as the name on Fuelly CSV or the import will not work.</li>
<li
>Make sure that the <u>Currency</u> and <u>Distance Unit</u> are set correctly in Hammond. Import will not autodetect Currency from the
CSV but use the one set for the user.</li
>
<li>Similiarly, make sure that the <u>Fuel Unit</u> and <u>Fuel Type</u> are correctly set in the Vehicle.</li>
<li>Once you have checked all these points,just import the CSV below.</li>
<li><b>Make sure that you do not import the file again and that will create repeat entries.</b></li>
</ol>
</div>
</div>
<div class="section box">
<div class="columns">
<div class="column is-two-thirds"> <p class="subtitle">Choose the Fuelly CSV and press the import button.</p></div>
<div class="column is-one-third is-flex is-align-content-center">
<form @submit.prevent="importFuelly">
<div class="columns"
><div class="column">
<b-field class="file is-primary" :class="{ 'has-name': !!file }">
<b-upload v-model="file" class="file-label" accept=".csv">
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label">{{ uploadButtonLabel }}</span>
</span>
<span v-if="file" class="file-name" :class="isMobile ? 'file-name-mobile' : 'file-name-desktop'">
{{ file.name }}
</span>
</b-upload>
</b-field>
</div>
<div class="column">
<b-button tag="input" native-type="submit" :disabled="tryingToCreate" type="is-primary" value="Upload File" class="control">
Import
</b-button>
</div></div
>
</form>
</div>
</div>
</div>
<b-message v-if="errors.length" type="is-danger">
<ul>
<li v-for="error in errors" :key="error">{{ error }}</li>
</ul>
</b-message>
</Layout>
</template>

View File

@@ -0,0 +1,7 @@
import Import from './import'
describe('@views/import', () => {
it('is a valid view', () => {
expect(Import).toBeAViewComponent()
})
})

View File

@@ -0,0 +1,37 @@
<script>
import Layout from '@layouts/main.vue'
export default {
page: {
title: 'Import',
meta: [{ name: 'Import from other apps', content: 'The Import page.' }],
},
components: { Layout },
props: {
user: {
type: Object,
required: true,
},
},
}
</script>
<template>
<Layout>
<div class="columns box"
><div class="column">
<h1 class="title">Import data into Hammond</h1>
<p class="subtitle">Choose from the following options to import data into Fuelly</p>
</div></div
>
<br />
<div class="columns">
<div class="box column is-one-third" to="/import-fuelly">
<h1 class="title">Fuelly</h1>
<p>If you have been using Fuelly to store your vehicle data, export the CSV file from Fuelly and click here to import.</p>
<br />
<b-button type="is-primary" tag="router-link" to="/import/fuelly">Import</b-button>
</div>
</div>
</Layout>
</template>