node 2022/02/16

무간·2022년 2월 16일

파일명 /routes/seller.js

// 시간대별 주문수량
// localhost:3000/seller/grouphour
// 판매자의 토큰이 전송되면 검증후에 이메일을 꺼냄
// item1걸렉션에 판매자의 상품코드를 꺼냄
// order1에 상품코드가 일치하는 것만 가져와서 group처리
router.get('/grouphour', checkToken, async function(req, res, next) {
    try{
        const email = req.body.uid;
        const dbconn = await db.connect(dburl);

        // 이메일이 일치하는 판매자의 물품코드 => [ 1,2,3,4 ]
        const collection = dbconn.db(dbname).collection('item1');
        // 고유값 꺼내기 distinct(교유값컬럼명,조건)
        const result = await collection.distinct("_id",{ seller : email });    
        // console.log('groupitem',result);


        const collection1 = dbconn.db(dbname).collection('order1');

        const result1 = await collection1.aggregate([
            { $match : { itemcode : { $in : result } } },
            {
                $project : {
                    orderdate: 1, //주문일자
                    ordercnt : 1, //주문수량
                    month    : {$month  : '$orderdate'}, // 주문일자를 이용해서 달
                    hour     : {$hour   : '$orderdate'}, // 주문일자를 이용해서 시
                    minute   : {$minute : '$orderdate'} // 주문일자를 이용해서 분
                }
            },
            {
                $group : {
                    _id     : '$hour', // 그룹할 항목
                    count   : { $sum : '$ordercnt' }
                }
            },
            {
                $sort : {
                  _id : 1 
                }
            }
        ]).toArray();

        return res.send({status:200, result:result1});
    }
    catch(e){
        console.error(e);
        return res.send({status:-1, message:e});
    }
});

===========================================

파일명 src/components/seller/Menu5.vue

<template>
    <div>
        <h3>src/components/seller/Menu5.vue</h3>
         <div style="width:500px; height:300px">
            <vue3-chart-js                 
                v-bind = "state"
                ref    = "chartRef">
            </vue3-chart-js>           
        </div>
    </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import Vue3ChartJs from '@j-t-mcc/vue3-chartjs'
import axios from 'axios';

export default {
    components:{
            Vue3ChartJs
    },
    setup () {  
        
        const chartRef = ref(null); // 차트를 업데이트하기 위해서 연결
        
        const state = reactive({ // Read            
            type : 'bar',
            data :{
                labels   : [],
                datasets : [{ 
                    label : '시간대별 주문수량',
                    backgroundColor: [],
                    data : []
                }],
            },
            token : sessionStorage.getItem("TOKEN")
        })

        // 현재 로그인한 판매자를 조건으로 시간대별 주문수량
        const handleLoadData = async () =>{
            const url = `/seller/grouphour`;
            const headers = {"Content-Type":"application/json", "token":state.token}
            const response = await axios.get(url,{headers});
            console.log("seller/Menu4/handleLoadData",response.data);
            if(response.data.status === 200){
                // [{_id:1051,count:2},{_id:1052,count:4}]

                let label      = []; // _id가 추가됨
                let background = []; // '#41B883'
                let data       = []; // count 추가됨

                for(let tmp of response.data.result){
                    label.push( tmp._id );
                    background.push( '#6569b5' );
                    data.push(tmp.count);
                }                
                state.data.labels = label;
                state.data.datasets[0]['backgroundColor'] = background;
                state.data.datasets[0]['data'] = data;

                chartRef.value.update(250);
            }            
        }
        onMounted(()=>{
            handleLoadData();
        })
        


        // 리턴함
        return {state, chartRef}
    }
}
</script>

<style lang="scss" scoped>

</style>
profile
당신을 한 줄로 소개해보세요

0개의 댓글