Skip to content

Instantly share code, notes, and snippets.

@kevchentw
Created December 12, 2017 07:27
Show Gist options
  • Select an option

  • Save kevchentw/495fbcdbb4a8ef43b679a3489cca5cc7 to your computer and use it in GitHub Desktop.

Select an option

Save kevchentw/495fbcdbb4a8ef43b679a3489cca5cc7 to your computer and use it in GitHub Desktop.
{% extends 'base/base.html' %}
{% load static %}
{% block title %}收據製作{% endblock %}
{% block head_after %}
<script src="//cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
{% endblock %}
{% block content %}
<div class="ui grid">
<div class="row">
<div class="one wide column"></div>
<div class="fourteen wide column">
<h1>製作收據</h1>
<form action="javascript:void(0);" id="the_form" class="ui form">
<h3>第一步:上傳 CSV</h3>
<div>
<label for="file" class="ui icon green button">
<i class="file icon"></i> <span id="fn">選擇檔案</span>
</label>
<input type="file" id="file" style="display:none" required="required" accept=".csv">
</div>
<h3>第二步:確認檔案</h3>
<button class="ui blue button" id="receipt_btn">製作</button>
<button class="ui pink button" id="receipt_big5_btn">製作 (Windows)</button>
</form>
</div>
</div>
</div>
<script>
function fileInfo(e) {
var file = e.target.files[0];
if (file.name.split(".")[1].toUpperCase() != "CSV") {
alert('Invalid csv file !');
e.target.parentNode.reset();
return;
} else {
$('#fn').text(file.name);
}
}
function genCsvDict(csv) {
var nameArr = csv.data[1];
var result = [];
for (var i = 2; i < csv.data.length - 1; i++) {
var data = {};
for (var j = 0; j < csv.data[i].length; j++) {
data[nameArr[j]] = csv.data[i][j];
}
result.push(data);
}
return result;
}
function handleFileSelect(encoding) {
var file = document.getElementById("file").files[0];
Papa.parse(file, {
complete: function (results) {
var csv = genCsvDict(results);
generateReceipts(csv, encoding);
},
encoding: encoding
});
}
function print(doc) {
var w = window.open();
w.document.write(doc);
}
var receipt_url;
function get_receipt_url(encoding) {
if (encoding=='big5-hkscs') {
return '{% static 'receipt/receipt_big5.html' %}';
}
else {
return '{% static 'receipt/receipt.html' %}';
}
}
{% verbatim content %}
function generateReceipts(receipts_list, encoding) {
$.get(get_receipt_url(encoding), function (data) {
var template = Handlebars.compile(data);
var receipts = {
"receipts": receipts_list
};
var r = template(receipts);
print(r);
});
}
{% endverbatim content %}
document.getElementById('file').addEventListener('change', fileInfo, false);
$("#receipt_btn").click(function () {
handleFileSelect('utf-8');
});
$("#receipt_big5_btn").click(function () {
handleFileSelect('big5-hkscs');
});
</script>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment